From 5e757b835988d38de57e9fc40ff79eadcdcaa722 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 13:59:57 +1100 Subject: [PATCH 01/81] perf(skippy): reuse prompt prefixes without eager KV snapshots Retain attention cells through native cache ownership and bound recurrent checkpoints independently of persistent storage. Export complete state to persistent L3 on cold eviction, with bounded reservations and segmented writes. Account for the full unified KV pool during admission. Bump the native ABI to 0.1.76 and invalidate superseded disk representations. Preserve existing attention read ranges; the experimental window optimization is excluded after real-model numerical validation failed. --- mesh/website/src/docs/pages/skippy-api.md | 59 +- skippy/crates/skippy-cache/README.md | 506 +-------- skippy/crates/skippy-cache/src/identity.rs | 3 +- skippy/crates/skippy-cache/src/radix.rs | 83 +- .../src/radix/resident_matching.rs | 172 ++++ skippy/crates/skippy-cache/src/tier.rs | 224 +--- .../skippy-cache/src/tier/spill_payload.rs | 195 ++++ .../skippy-cache/src/tier/spill_segments.rs | 185 ++++ skippy/crates/skippy-cli/src/conversion.rs | 3 +- skippy/crates/skippy-cli/src/serve.rs | 2 +- .../skippy-cli/src/serve_settings/catalog.rs | 2 +- .../src/serve_settings/resolution.rs | 6 +- .../skippy-cli/src/serve_settings/tests.rs | 21 +- skippy/crates/skippy-ffi/src/dynamic.rs | 3 + skippy/crates/skippy-ffi/src/lib.rs | 8 +- skippy/crates/skippy-protocol/src/config.rs | 6 +- skippy/crates/skippy-runtime/src/lib.rs | 1 + .../skippy-runtime/src/resident_prefix.rs | 134 +++ skippy/crates/skippy-runtime/src/session.rs | 17 + skippy/crates/skippy-runtime/src/types.rs | 6 + .../binary_messaging/prefill_recording.rs | 5 +- .../restore_prefill_decode.rs | 2 +- .../src/binary_transport/stage_execution.rs | 12 +- .../src/frontend/local_generation/tests.rs | 40 +- .../local_generation/token_generation.rs | 5 +- .../token_generation/exact_state_recording.rs | 28 +- .../src/frontend/prefix_cache.rs | 12 +- .../skippy-serving/src/frontend/prompting.rs | 5 +- .../frontend/tests/prefix_cache_lifecycle.rs | 4 + .../src/kv_integration/cache_affinity.rs | 102 +- .../src/kv_integration/cache_payload.rs | 17 +- .../src/kv_integration/config.rs | 262 +---- .../kv_integration/config/durable_spill.rs | 108 +- .../kv_integration/config/resident_policy.rs | 42 + .../config/tests/cache_admission.rs | 2 + .../config/tests/runtime_admission.rs | 243 +++++ .../src/kv_integration/exact_state.rs | 109 +- .../skippy-serving/src/kv_integration/mod.rs | 77 +- .../src/kv_integration/record_worker.rs | 58 ++ .../src/kv_integration/resident_offload.rs | 211 ++++ .../src/kv_integration/resident_prefix.rs | 304 +----- .../resident_prefix/recording.rs | 397 +++++++ .../resident_prefix/selection.rs | 27 + .../skippy-serving/src/runtime_state.rs | 59 +- .../src/runtime_state/context_capacity.rs | 198 ++++ .../src/runtime_state/lane_lifecycle.rs | 6 + .../src/runtime_state/resident_prefix.rs | 52 + skippy/docs/KV_CACHE_DISK.md | 25 +- skippy/docs/PROMPT_CACHE.md | 270 ++--- ...ippy-define-graph-derived-native-ABI.patch | 50 +- ...ize-admitted-stages-from-live-graphs.patch | 965 +++++++++--------- ...e-native-runtime-and-backend-support.patch | 9 +- ...cover-live-graph-and-state-contracts.patch | 609 ++++++++++- ...rd-per-token-logprobs-while-sampling.patch | 16 +- 54 files changed, 3771 insertions(+), 2196 deletions(-) create mode 100644 skippy/crates/skippy-cache/src/radix/resident_matching.rs create mode 100644 skippy/crates/skippy-cache/src/tier/spill_payload.rs create mode 100644 skippy/crates/skippy-cache/src/tier/spill_segments.rs create mode 100644 skippy/crates/skippy-runtime/src/resident_prefix.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/resident_policy.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/record_worker.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs create mode 100644 skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs create mode 100644 skippy/crates/skippy-serving/src/runtime_state/resident_prefix.rs diff --git a/mesh/website/src/docs/pages/skippy-api.md b/mesh/website/src/docs/pages/skippy-api.md index 01e6b39fef..dc93d75e49 100644 --- a/mesh/website/src/docs/pages/skippy-api.md +++ b/mesh/website/src/docs/pages/skippy-api.md @@ -216,6 +216,9 @@ Current generated surface: **21 headers** and **131 exported functions**. skippy_import_cachegen_kv_page_v1 skippy_session_save_prefix skippy_session_restore_prefix + skippy_session_export_resident_kv_page + skippy_session_export_resident_recurrent_state + skippy_session_resident_prefix_bytes skippy_session_memory_used_cells skippy_session_drop_sequence @@ -1805,7 +1808,7 @@ LLAMA_API enum skippy_status skippy_export_full_state( #### `skippy_export_recurrent_state` -Exports recurrent state for models that maintain recurrent memory. +Exports only recurrent memory; attention pages are exported independently. ```cpp LLAMA_API enum skippy_status skippy_export_recurrent_state( @@ -1834,7 +1837,7 @@ LLAMA_API enum skippy_status skippy_import_full_state( #### `skippy_import_recurrent_state` -Imports recurrent state into a session. +Imports recurrent-only state into a session. ```cpp LLAMA_API enum skippy_status skippy_import_recurrent_state( @@ -1932,7 +1935,7 @@ LLAMA_API enum skippy_status skippy_import_cachegen_kv_page_v1( #### `skippy_session_save_prefix` -Saves a session prefix into a resident cache sequence. +Retains shared attention cells and an immutable recurrent checkpoint owned by the cache. Recurrent memory requires token_count equal to the current session position. ```cpp LLAMA_API enum skippy_status skippy_session_save_prefix( @@ -1945,7 +1948,7 @@ LLAMA_API enum skippy_status skippy_session_save_prefix( #### `skippy_session_restore_prefix` -Restores a session prefix from a resident cache sequence. +Shares retained attention cells and restores a private mutable recurrent row. Token identity must match; recurrent prefixes require the exact saved boundary. ```cpp LLAMA_API enum skippy_status skippy_session_restore_prefix( @@ -1956,6 +1959,54 @@ LLAMA_API enum skippy_status skippy_session_restore_prefix( struct skippy_error ** out_error); ``` + +#### `skippy_session_export_resident_kv_page` + +Exports a cache-owned attention page for cold offload without claiming or restoring an execution lane. + +```cpp +LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( + struct skippy_session * session, + int32_t cache_seq_id, + int32_t layer_start, + int32_t layer_end, + uint64_t token_start, + uint64_t token_count, + struct skippy_kv_page_desc * out_desc, + void * output, + size_t output_capacity, + size_t * out_bytes, + struct skippy_error ** out_error); +``` + + +#### `skippy_session_export_resident_recurrent_state` + +Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors. + +```cpp +LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( + struct skippy_session * session, + int32_t cache_seq_id, + void * output, + size_t output_capacity, + size_t * out_bytes, + struct skippy_error ** out_error); +``` + + +#### `skippy_session_resident_prefix_bytes` + +Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool. + +```cpp +LLAMA_API enum skippy_status skippy_session_resident_prefix_bytes( + struct skippy_session * session, + int32_t cache_seq_id, + uint64_t * out_bytes, + struct skippy_error ** out_error); +``` + #### `skippy_session_memory_used_cells` diff --git a/skippy/crates/skippy-cache/README.md b/skippy/crates/skippy-cache/README.md index 4af55b57d2..3b85fdc64a 100644 --- a/skippy/crates/skippy-cache/README.md +++ b/skippy/crates/skippy-cache/README.md @@ -1,464 +1,54 @@ # skippy-cache -`skippy-cache` owns the cache model for staged serving. It does not talk to -llama.cpp, open sockets, route OpenAI requests, or plan topology. Those -responsibilities stay in `skippy-serving`, `skippy-runtime`, and mesh. - -The crate answers cache questions: - -- what exact prefix identity should be used for this stage? -- which prefix lengths should be looked up or recorded? -- which resident cache entry should be evicted? -- how should exact state payload bytes be represented and deduplicated? - -The cache is deliberately exact. It does not guess that two prompts are -"similar enough"; it reuses runtime state only when the model, topology, stage, -layer range, runtime layout, position, and token prefix all match. - -## Boundaries - -```mermaid -flowchart LR - OpenAI["skippy-inference-api"] --> Server["skippy-serving"] - Server --> Runtime["skippy-runtime"] - Runtime --> ABI["llama.cpp stage ABI"] - - Server --> Cache["skippy-cache"] - Cache --> Identity["prefix identity"] - Cache --> Resident["resident prefix / activation caches"] - Cache --> Payload["exact state payloads"] - Payload --> Blocks["BLAKE3 block store"] - - Cache -. no runtime calls .- Runtime -``` - -`skippy-serving` remains the adapter. It turns protocol messages into cache -lookups, performs the runtime save/restore/import/export calls, and records -telemetry. `skippy-cache` only owns pure data structures and policies. - -## Prefix Identity - -Prefix identity is exact. A hit is valid only for the same: - -- model id -- topology id -- stage id and stage index -- layer range -- runtime ABI schema -- KV layout and dtype -- context/position configuration -- token start and token ids - -The identity hash uses BLAKE3 over these fields. The short page id is derived -from the hash and is suitable for logs and resident-cache maps. - -```mermaid -flowchart TD - Tokens["token ids + token_start"] --> Hash["BLAKE3 prefix hash"] - Stage["model/topology/stage/layers"] --> Hash - Runtime["ABI + layout + dtype + ctx"] --> Hash - Hash --> Page["page id"] - Page --> Lookup["resident/exact-state lookup"] -``` - -## Resident Cache Flow - -The current resident path keeps reusable state inside the live llama.cpp -session. `skippy-cache` chooses candidates and tracks entries; `skippy-serving` -does the native sequence copy/drop calls. - -```mermaid -sequenceDiagram - participant S as skippy-serving - participant C as skippy-cache - participant R as skippy-runtime - - S->>C: candidate prefix identities - C-->>S: longest-first lookup candidates - S->>C: lookup resident entry - alt hit - C-->>S: cache seq id - S->>R: restore resident prefix - S->>S: compute only suffix or forward cached activation - else miss - S->>R: prefill normally - S->>C: allocate record slot - C-->>S: cache seq id + evictions - S->>R: drop evicted seq ids - S->>R: save resident prefix - S->>C: commit record - end -``` - -Activation frames are cached separately by `act:{page_id}:w{activation_width}`. -In a split topology, an upstream stage may reuse both its resident prefix and -the activation frame it would have forwarded downstream. - -For dense models this is the production fast path. It is intentionally close to -the llama-server slot contract: keep usable KV resident in the runtime and -continue from it. The difference is that Skippy gives the resident state a -backend-neutral prefix identity, keeps hot lane prefixes borrowed in place when -possible, and can reuse the same prefix across Rust-owned serving, staged -execution, and activation forwarding. - -## Exact State Payloads - -The payload module models the portable exact-cache path we need for -recurrent/stateful families: - -| Payload | Contents | Use | -| --- | --- | --- | -| `FullState` | whole exported sequence state | diagnostic/reference only; not selected by production serving policy | -| `RecurrentOnly` | recurrent/SSM state only | diagnostic; not generally exact for non-final stages | -| `KvRecurrent` | attention KV plus recurrent/SSM state | preferred exact payload for hybrid/recurrent repeated-prefix cache | - -Large payloads are split into 1 MiB BLAKE3-addressed blocks. Repeated blocks are -stored once, so capacity is accounted by physical bytes as well as logical -payload bytes. - -`KvRecurrent` is the production method for hybrid/recurrent families. It moves -attention KV together with recurrent/SSM state, because KV alone is not the full -continuation state for those models. That is where the largest wins come from: -llama-server warm slots still have to reprocess the recurrent prefix in many -request shapes, while Skippy can restore the exact compact state and decode. - -Durable L3 manifests identify runtime-native KV segments as -`native-kv-page/1`. Those segments are the bytes exported by the active runtime -and are stored and restored verbatim; F32, F16, Q8_0, and Q4_0 remain in their -active runtime representation when that backend supports the type. Recurrent -and other auxiliary continuation state stays `raw/1`, with a hard segment -boundary between the representations. Before reading native segment bytes, -the server checks the manifest's runtime page descriptor against the located -prefix and encoded KV length. The exact-state identity already binds the -runtime ABI, platform, model, layer range, and KV configuration. - -```mermaid -flowchart LR - Payload["KV + recurrent payload"] --> Split["1 MiB chunks"] - Split --> H1["BLAKE3 block A"] - Split --> H2["BLAKE3 block B"] - Split --> H3["BLAKE3 block A reused"] - H1 --> Store["block store"] - H2 --> Store - H3 -. refcount .-> Store - Store --> Stats["logical / physical / saved bytes"] -``` - -## Family Cache Policy - -Cache support is family-dependent because different model families have -different continuation state. - -| Family shape | Safe cache shape | Notes | -| --- | --- | --- | -| Dense attention models such as Llama, Qwen3 dense, DeepSeek2, DeepSeek3, GLM4, GLM-4.7 Flash, OLMo, Gemma, MiniMax-M2.7 | `ResidentKv` | Attention KV is the continuation state for the certified prompt-continuation path. The cache entry is resident in the live runtime, so serving reuses llama.cpp sequence state without serializing bytes. | -| Hybrid/recurrent models such as Qwen3Next, Falcon-H1, RWKV/Mamba-like tensors | `KvRecurrent` only | KV-only reuse is disabled; recurrent/SSM state must be restored with KV for exact continuation. | -| Families with uncertain state layout | disabled until certified | Unknown families should not silently reuse state. | -| Diagnostic/correctness runs | `FullState`, `RecurrentOnly`, or `KvRecurrent` | Used to prove exactness and payload economics before enabling serving policy. | - -The serving integration currently scans GGUF tensor names and disables the -KV-only resident path when recurrent/stateful tensors are present, including -`.ssm`, `ssm_`, `time_mix`, `recurrent`, and `rwkv`. That guard prevents a -hybrid model from importing attention KV while missing the recurrent state that -changes the next token. - -The intended recurrent/stateful serving path is: - -1. lookup exact prefix identity -2. import/restore `KvRecurrent` -3. recompute safely on any miss or incompatible payload -4. record a new exact payload after successful prefill - -Serving schedules stage-zero exact-state exports as detached FIFO runtime work. -The checkpoint command is ordered before any later iteration that can advance -the session, while the request worker can continue without waiting for export, -block hashing, or radix insertion. Exported bytes retain their contiguous -allocation while the blob store indexes them by block, so an unfragmented hit -is imported without first reconstructing a second full-size buffer. - -Prefill-only requests (`max_tokens=0`) retain a synchronous chat-prefix export. -That fallback must capture the checkpoint before the same scheduler operation -advances through the remaining suffix; a detached command could only run after -the named native position had passed. Generation requests use the detached path -described above. - -The OpenAI serving path now uses the same cache policy. A cache-enabled stage -selects one payload shape: - -- `ResidentKv` for certified dense families where resident llama.cpp sequence - copy is enough -- `KvRecurrent` for hybrid/recurrent families where attention KV and recurrent - state must move together - -`FullState` is intentionally not selected by the production family policy. It is -kept as a correctness/certification tool so a family can first prove exact -restore behavior before we design and promote a compact serving payload. - -## Why Skippy Cache Beats llama-server - -llama-server slots are very good at one thing: keeping a prompt prefix warm -inside a server slot. Skippy preserves that behavior for dense single-stage -serving, then extends it in several important ways. - -| Method | Where it wins | Why | -| --- | --- | --- | -| Exact prefix identity | all cache modes | Prefixes are keyed by model ref, topology, stage, layer range, ABI/layout, position, and token ids, so state can be reused safely outside a single llama-server slot. | -| `ResidentKv` | dense attention families | KV stays resident in the live runtime. Hot-lane hits borrow the existing prefix instead of paying serialize/restore costs, matching llama-server's slot model while using Skippy's lower-overhead Rust serving path. | -| `KvRecurrent` | Qwen3Next, Falcon-H1, and other hybrid/recurrent families | Attention KV and recurrent/SSM state move together. llama-server has no equivalent production cache for this exact state shape, so repeated prefixes avoid expensive recurrent-prefix reprocessing. | -| Activation-frame cache | split serving | A stage can reuse the activation it would have forwarded downstream, so cache hits can remove work from both the local stage and the next stage boundary. | -| BLAKE3 deduped exact payloads | portable exact-state cache | Large exported states are indexed as content-addressed blocks while retaining contiguous backing for zero-copy restore when possible. Shared blocks are materialized only when their last contiguous owner is evicted, preserving exact physical-capacity accounting. | -| Package-backed stage cache | giant staged models | A materialized stage can cache only the state for the layer range it owns, without loading or merging a monolithic full GGUF. | - -The headline pattern in the benchmark table follows from those methods: - -- Hybrid/recurrent families show the largest wins because `KvRecurrent` - restores state llama-server otherwise has to regenerate. -- Dense families show parity to moderate wins because `ResidentKv` keeps the - same warm-slot advantage while avoiding extra serving-path overhead. -- DeepSeek3 is package-only evidence: it proves the selected cache method for a - materialized stage, not a full-GGUF llama-server comparison. - -The cache does not claim fuzzy semantic reuse, approximate prefix matching, or -`FullState` production speedups. `FullState` remains a certification tool only. - -```mermaid -flowchart LR - Request["request tokens"] --> Identity["exact prefix identity"] - Identity --> Hit{"cache hit?"} - Hit -- dense --> Resident["ResidentKv: borrow resident runtime KV"] - Hit -- recurrent --> Recurrent["KvRecurrent: restore KV + recurrent state"] - Hit -- split --> Activation["activation frame reuse"] - Hit -- miss --> Prefill["normal prefill"] - Prefill --> Record["record exact state"] - Record --> Dedupe["BLAKE3 block dedupe + capacity accounting"] -``` - -```mermaid -sequenceDiagram - participant O as skippy-inference-api - participant S as skippy-serving - participant C as skippy-cache - participant R as skippy-runtime - - O->>S: request - S->>C: longest-prefix identities - alt exact hit - C-->>S: KvRecurrent payload - S->>R: import state into lane - S->>R: decode next token - else resident hit - C-->>S: resident seq id - S->>R: restore resident prefix - S->>R: decode next token - else miss - S->>R: prefill - S->>R: export selected payload - S->>C: dedupe/store and evict by cap - S->>R: decode next token - end -``` - -## Benchmark Evidence - -README performance claims must be backed by correctness runs and comparable -llama-server baselines. Rows marked `untested` are intentionally not promoted as -default evidence yet. - -Reproduce the family evidence and README tables with the pinned operator JSON -profile described in [the cache-family skill](../../../.agents/skills/skippy-cache-family-bench/SKILL.md). -Preparation observes the model shards, binaries, native build and selected toolkit -directories before launching the producer. Keep those inputs fixed across both arms: - -```bash -SKIPPY_CACHE_OPERATOR_INPUT=/absolute/cache-operator.json \ - skippy/evals/skippy-cache-family-bench.sh /tmp/skippy-cache-family-bench -``` - -For a faster rerun after building locally: - -```bash -SKIPPY_CACHE_OPERATOR_INPUT=/absolute/cache-operator.json SKIPPY_CACHE_SKIP_BUILD=1 \ - skippy/evals/skippy-cache-family-bench.sh /tmp/skippy-cache-family-bench -``` - -For an MoE tensor-presence/cache smoke, reuse an observed correctness profile from -`cache-family-run prepare-full`. For example, with the current DeepSeek2 catalog -model already present, select its 27-layer profile and the pinned native -`skippy-package-builder` inspector from the same build: - -```bash -jq --arg inspector "$SKIPPY_CACHE_MODEL_INSPECTOR" \ - --arg sha "$SKIPPY_CACHE_MODEL_INSPECTOR_SHA256" \ - --arg commit "$SKIPPY_CACHE_NATIVE_SOURCE_COMMIT" ' - .profiles.deepseek2.correctness as $profile | - {schema_version:1, inspector:$inspector, inspector_sha256:$sha, - inspector_source_commit:$commit, execution_seconds:3600, - cases:[{layer_end:27, correctness:($profile + { - prefix_tokens:32, runtime_lane_count:4, cache_hit_repeats:3, - execution_seconds:900, cell_seconds:900, - topologies:["one-stage","split-middle","split-final"]})}]} -' /absolute/preparation/cache-family-input.json > /tmp/moe-input.json -just automation-run automation cache-family-moe \ - --input /tmp/moe-input.json --output /tmp/moe-smoke-fresh -``` - -The inspector path is absolute; its SHA-256 binds the supplied executable, while -the source commit is caller-declared provenance. Other current catalog profiles -can be supplied explicitly with their actual layer count; `split-stage0` is also -supported. Missing models, unknown catalog keys, changed pins and absent expert -tensors refuse admission. The former `olmoe`/`qwen2moe`/`qwen3moe` default aliases -are absent from the current catalog and do not select a substitute model. - -The command retains `moe-expert-smoke.json`, the flattened observation table -`moe-expert-smoke-table.json`, and Markdown tables. Acceptance follows the final -completed parent receipt. The table keeps tensor ranges/counts/bytes, suffix and -cache-hit results, resident/cache storage and serialized bytes. Native sequence -IDs remain unmeasured because the current correctness report does not expose -them. These checks establish expert tensor presence plus cache correctness; -real model/backend execution and performance claims require their own results. - -Local correctness evidence below was collected on the same machine with -`n_predict = 1`, `n_gpu_layers = -1`, Skippy `--runtime-lane-count 1`, and -llama-server `--parallel 1`. The payload column is the production serving -payload, not an experimental fallback. Results use median warm-hit latency from -matched repeated prompts. The full-GGUF table uses the same 128-token requested -prefix and one generated token for every row so each Skippy result is compared -against the matching llama-server workload. - -`Cache bytes` is serialized payload size for `KvRecurrent` and measured native -KV-page footprint for `ResidentKv` when the runtime can expose it. Rows marked -`metadata-derived` use the same llama.cpp KV dimensions from GGUF metadata: -active KV layers, KV heads, key/value head lengths, SWA pattern, shared-KV -layers, token count, and f16 KV element size. - -### Full-GGUF llama-server vs Skippy - -Rows are ordered so related runtime/cache families appear next to each other. - -| Family | Representative model ref | Production payload | Correctness | Prefix tokens | Prompt tokens | llama-server warm median ms | Skippy hit median ms | Skippy win | Cache bytes | Size method | Notes | -| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | --- | -| Qwen3Next | `bartowski/Qwen_Qwen3-Coder-Next-GGUF:IQ2_XS` | `KvRecurrent` | pass | 128 | 129 | 318.0 | 26.4 | **12.06x faster** | 78.4 MiB | measured | Recurrent-backed state reuse makes llama-server reprocess work Skippy skips. | -| Falcon-H1 | `tiiuae/Falcon-H1-1.5B-Instruct-GGUF:Q4_K_M` | `KvRecurrent` | pass | 128 | 129 | 105.2 | 12.0 | **8.73x faster** | 76.0 MiB | measured | Same recurrent-state advantage on the Falcon-H1 cache payload. | -| Llama | `hugging-quants/Llama-3.2-1B-Instruct-Q4_K_M-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 8.8 | 4.5 | **1.95x faster** | 4.0 MiB | measured | Matches the llama-server slot contract, then wins on overhead. | -| Qwen3 dense | `Qwen/Qwen3-0.6B:Q8_0` | `ResidentKv` | pass | 128 | 129 | 7.4 | 6.8 | **1.08x faster** | 14.0 MiB | measured | Correct and faster; this is the narrowest win in the normalized matrix. | -| DeepSeek2 | `bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 12.6 | 9.6 | **1.32x faster** | 33.8 MiB | measured | Correct and faster on the resident prefix path. | -| GLM-4.7 Flash | `unsloth/GLM-4.7-Flash-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 26.0 | 18.9 | **1.38x faster** | 12.5 MiB | metadata-derived | Correct and faster under the normalized 128-token workload. | -| GLM4 | `meshllm/glm-4-9b-0414-parity-q4_k_m-gguf:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 23.2 | 18.9 | **1.23x faster** | 5.0 MiB | measured | Correct and faster. | -| Gemma4 A4B | `batiai/Gemma-4-26B-A4B-it-GGUF:Q6_K` | `ResidentKv` | pass | 128 | 129 | 21.0 | 17.6 | **1.20x faster** | 27.5 MiB | metadata-derived | Correct and faster with SWA KV dimensions accounted for in sizing. | -| Gemma4 E4B | `unsloth/gemma-4-E4B-it-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 20.7 | 16.1 | **1.29x faster** | 7.0 MiB | metadata-derived | Correct and faster with shared-KV layers accounted for in sizing. | -| Gemma3 | `ggml-org/gemma-3-1b-it-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 10.1 | 7.0 | **1.45x faster** | 3.2 MiB | metadata-derived | Hot-lane resident prefix reuse beats llama-server warm slots. | -| Gemma2 | `bartowski/gemma-2-2b-it-GGUF:Q4_K_M` | `ResidentKv` | pass | 128 | 129 | 12.1 | 8.5 | **1.43x faster** | 13.0 MiB | metadata-derived | Correct and faster. | -| OLMo | `meshllm/olmo-7b-instruct-hf-parity-f16-gguf:F16` | `ResidentKv` | pass | 128 | 129 | 28.9 | 24.0 | **1.20x faster** | 64.0 MiB | measured | Correct and faster. | -| MiniMax M2.7 | `unsloth/MiniMax-M2.7-GGUF:UD-Q2_K_XL` | `ResidentKv` | pass | 128 | 129 | 39.5 | 31.9 | **1.24x faster** | 31.0 MiB | measured | Correct and faster on the large sharded GGUF. | - -### Use-Case Benchmark Matrix - -This matrix uses one Hugging Face-sourced representative prompt per use case, -the same `128` requested prefix tokens, one generated token, Skippy -`--runtime-lane-count 1`, llama-server `--parallel 1`, and the same full-GGUF -family set as the table above. Values are Skippy warm-hit latency speedup over -llama-server warm-cache latency. DeepSeek3 stays in the package-only section -because there is no practical local full-GGUF llama-server baseline for that -artifact. - -| Use case | Qwen3Next | Falcon-H1 | Llama | Qwen3 dense | DeepSeek2 | GLM-4.7 Flash | GLM4 | Gemma4 A4B | Gemma4 E4B | Gemma3 | Gemma2 | OLMo | MiniMax M2.7 | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| Tool calling | 15.23x | 8.53x | 1.33x | 1.32x | 1.60x | 1.30x | 1.27x | 1.04x | 1.33x | 1.58x | 1.40x | 1.21x | 1.19x | -| Text-to-SQL | 15.42x | 8.58x | 1.69x | 1.35x | 1.52x | 1.19x | 1.13x | 1.30x | 1.26x | 1.64x | 1.41x | 1.08x | 1.14x | -| Coding agent loop | 14.62x | 8.24x | 1.56x | 1.68x | 1.47x | 1.24x | 1.28x | 1.32x | 1.25x | 1.54x | 1.52x | 1.24x | 1.26x | -| Issue fixing | 14.45x | 8.84x | 1.74x | 1.68x | 1.56x | 1.24x | 1.30x | 1.28x | 1.29x | 1.65x | 1.49x | 1.12x | 1.28x | -| Code refinement | 14.55x | 8.65x | 1.98x | 1.43x | 1.53x | 1.25x | 1.23x | 1.27x | 1.43x | 1.76x | 1.47x | 1.25x | 1.21x | -| Few-shot reasoning | 14.44x | 8.55x | 1.73x | 1.64x | 1.56x | 1.26x | 1.21x | 1.08x | 1.33x | 1.61x | 1.52x | 1.20x | 1.18x | -| Open chat | 13.74x | 9.15x | 1.62x | 1.35x | 1.60x | 1.30x | 1.23x | 1.36x | 1.31x | 1.58x | 1.28x | 1.06x | 1.27x | -| Summarization/RAG | 13.89x | 8.94x | 1.81x | 1.41x | 1.67x | 1.26x | 1.13x | 1.27x | 1.32x | 1.55x | 1.61x | 1.20x | 1.19x | - -Prompt sources are checked in at `skippy/evals/skippy-usecase-corpus.json` with source -dataset metadata: - -| Use case | Dataset | Config | Split | Row | -| --- | --- | --- | --- | ---: | -| Tool calling | `glaiveai/glaive-function-calling-v2` | `default` | `train` | 1 | -| Text-to-SQL | `gretelai/synthetic_text_to_sql` | `default` | `test` | 0 | -| Coding agent loop | `SWE-bench/SWE-smith-trajectories` | `default` | `tool` | 0 | -| Issue fixing | `SWE-bench/SWE-bench` | `default` | `dev` | 0 | -| Code refinement | `google/code_x_glue_cc_code_refinement` | `small` | `test` | 0 | -| Few-shot reasoning | `openai/gsm8k` | `main` | `test` | 0 | -| Open chat | `HuggingFaceH4/mt_bench_prompts` | `default` | `train` | 0 | -| Summarization/RAG | `nvidia/ChatRAG-Bench` | `doc2dial` | `test` | 0 | - -### Package-Only Giant Models - -These rows validate cache strategy for models where a full llama-server -baseline is not operationally useful because monolithic residency is too large. - -| Family | Representative model ref | Production payload | Correctness | Prefix tokens | Prompt tokens | Baseline | Skippy hit median ms | Skippy win | Cache bytes | Size method | Notes | -| --- | --- | --- | --- | ---: | ---: | --- | ---: | ---: | ---: | --- | --- | -| DeepSeek3 | `unsloth/DeepSeek-V3.2-GGUF:UD-Q4_K_XL` | `ResidentKv` | pass | 4 | 5 | Skippy stage recompute | 3.4 | **4.40x faster** | 8.5 KiB | metadata-derived | Package-only proof on expert slice `3..4`; selected 7.47 GB stage part plus upstream `0..3`, no full 406.8 GB layer set loaded or merged. | - -DeepSeek3 uses `ResidentKv` for package-backed serving. The local gate verifies -the package stage cache without requiring a monolithic full-GGUF baseline: -`0..1` passed with real token input, `3..4` passed with a real upstream `0..3` -activation producer, and late layers `30..31` plus `60..61` passed with -deterministic synthetic upstream activations so only the owned stage range had -to be materialized. - -`state-handoff` reports distinguish behavioral exactness from byte-stable state -re-export. `status = pass` means the restored cache state produced the same next -token/output and repeat hits matched. `roundtrip_state_matches = false` means a -state exported after import was not byte-for-byte identical; that is a -canonicalization/deduplication diagnostic, not a serving correctness failure. -Raw reports from this run are under -`/tmp/skippy-cache-production-bench-track1-apples-p128`. - -### Current Performance Read - -With llama-server-compatible thread defaults, hot-lane resident prefix reuse, -and the production borrowed-prefix path, Skippy is at parity or ahead for every -locally available family in the normalized single-stage matrix: - -| Scenario | Current read | Why | -| --- | --- | --- | -| Recurrent/hybrid families | Strong wins where compact recurrent state is exported | Falcon-H1 and Qwen3Next avoid llama-server reprocessing by restoring `KvRecurrent` state. | -| Dense attention families | Parity to moderate wins | Hot-lane resident prefix reuse preserves the same lane-local slot behavior that made llama-server fast, while the resident cache still supports later exact-prefix reuse. | -| Full-state diagnostics | Not a production target | `FullState` can prove restore exactness, but it is not selected by serving policy and should not be benchmarked as a cache win/loss. | -| Split serving | Still needs its own benchmark | Single-stage numbers do not prove end-to-end split wins because activation transfer, stage scheduling, and upstream/downstream cache hits change the cost model. | - -Before claiming a new family is faster than llama-server, run the reproducible -benchmark wrapper and keep the matched conditions fixed: same GGUF, backend, -context size, prompt tokens, generated tokens, slot/parallel settings, and -warm-cache policy. The README table is a serving-correctness table first; -performance wins are only promoted for rows whose matched speedup is above -1.0x. - -## Module Map - -| Module | Responsibility | -| --- | --- | -| `config` | candidate prefix lengths, record limits, resident cache sizing | -| `identity` | exact prefix hash and page ids | -| `resident` | resident prefix and activation LRU bookkeeping | -| `payload` | exact state payloads and BLAKE3 block dedupe | - -## Testing - -The crate is intentionally lightweight. It should test without building or -linking llama.cpp: - -```bash -cargo test -p skippy-cache --lib -``` - -Supported-family cache safety is smoked through the topology capability -registry: +`skippy-cache` owns prefix identity, the radix index, reference leases, eviction +policy, activation caching, and portable state storage. It does not execute a +model, call native code, serve HTTP, or choose topology. Its primary consumer +is [`skippy-serving`](../skippy-serving/README.md), which connects these data +structures to [`skippy-runtime`](../skippy-runtime/README.md). + +## Resident ownership + +Token paths in the radix tree identify retained native state. Entries own +native cache sequence references independently of execution lanes. Attention +cells can be shared by several prefixes and active requests. Recurrent models +also need immutable checkpoints at exact saved token boundaries; a common +prefix inside a later checkpoint is not a valid recurrent restore point. + +The index distinguishes these matching rules and pins selected entries while +serving restores them. Eviction removes only unpinned entries. Serving releases +the corresponding native resources when it commits an eviction. + +Identity binds tokens and namespace to numerical model weights, layer range, +runtime ABI, layout, dtype, and position configuration. Payload hashes are not +used to discover shared resident prefixes. Attention admission uses physical +native occupancy rather than summing overlapping logical prefix lengths. +Recurrent checkpoint RAM is bounded separately and works with disk disabled. + +This adopts SGLang's separation of radix-owned attention blocks and recurrent +checkpoints through llama.cpp's native memory interfaces. It does not embed +SGLang's Torch runtime. See [the prompt-cache design](../../docs/PROMPT_CACHE.md) +for lifetime, matching, budget, and persistence behavior. + +## Portable state + +The crate also owns `FullState`, `RecurrentOnly`, and `KvRecurrent` payloads, +BLAKE3-addressed storage, and durable manifests for explicit transfer and +runtimes without complete resident support. These APIs remain separate from +warm resident retention. Resident-capable serving does not eagerly export, +reconstruct, or hash the attention payload on each cache record. Configured +persistent L3 receives cold eviction offloads and can fill resident misses +after a restart; payload integrity verification stays at that storage boundary. + +Activation frames are cached separately so a split stage can reuse the boundary +activation associated with its exact prefix. Cache data structures remain +backend neutral; native memory ownership and import/export belong to runtime +and serving adapters. + +Run the crate's tests from the workspace root: ```bash -cargo test -p skippy-topology reviewed_supported_families_smoke --lib +cargo test -p skippy-cache ``` -That smoke does not execute model files. It verifies that every reviewed -supported family can be inferred and emits the expected recurrent/sticky and -sideband policy signals. Activation transport is fixed raw f32 and is not a -family capability. - -Server/runtime integration tests belong in `skippy-serving`, -`skippy-runtime`, and `skippy-correctness`. +The [previous serialized-cache measurements](https://github.com/Mesh-LLM/mesh-llm/blob/18fef3a042847463f13844304b0e9100e49a2f6b/skippy/crates/skippy-cache/README.md#benchmark-evidence) +remain historical evidence; they do not qualify the new ownership path. diff --git a/skippy/crates/skippy-cache/src/identity.rs b/skippy/crates/skippy-cache/src/identity.rs index 27b1541366..50dbfb37c0 100644 --- a/skippy/crates/skippy-cache/src/identity.rs +++ b/skippy/crates/skippy-cache/src/identity.rs @@ -1,6 +1,7 @@ use skippy_protocol::{FlashAttentionType, LoadMode, StageConfig, StageKvCacheCodec}; -pub const NATIVE_KV_RUNTIME_ABI_VERSION: &str = "stage-abi-0.1.52/native-kv-page-v3"; +pub const NATIVE_KV_RUNTIME_ABI_VERSION: &str = + "stage-abi-0.1.76/native-kv-page-v3/recurrent-component-v1"; pub const NATIVE_KV_DTYPE: &str = "ggml-native-kv"; const NATIVE_KV_LAYER_CONTIGUOUS_LAYOUT: i32 = 4; diff --git a/skippy/crates/skippy-cache/src/radix.rs b/skippy/crates/skippy-cache/src/radix.rs index 1a4255b8a7..e6a480ee3f 100644 --- a/skippy/crates/skippy-cache/src/radix.rs +++ b/skippy/crates/skippy-cache/src/radix.rs @@ -1,3 +1,6 @@ +mod resident_matching; +use resident_matching::resident_backing_prefix; + use std::collections::{BTreeMap, HashMap}; use anyhow::{Result, bail}; @@ -709,86 +712,6 @@ fn ensure_node<'a, R, E>( .expect("new split radix child should exist") } -/// Find the longest query prefix backed by any resident sequence. -/// -/// Unlike recurrent checkpoints, native resident KV can be sliced when copied: -/// a cached sequence for `[1, 2, 3, 4]` can restore `[1, 2]` for a request that -/// diverges at token 3. Native restore only reads the stored resident source, -/// so multiple restores may hold references concurrently; eviction remains -/// blocked until every reference is released. -fn resident_backing_prefix( - root: &RadixNode, - tokens: &[i32], -) -> Option<(usize, Vec)> { - let mut node = root; - let mut remaining = tokens; - let mut consumed = 0usize; - let mut path = Vec::new(); - let mut best = None; - - if node.components.resident.is_some() { - best = Some((0, Vec::new())); - } - - while let Some(first) = remaining.first() { - let Some(child) = node.children.get(first) else { - // The query can diverge exactly at an existing branch point. No - // child starts with its next token, but any resident descendant - // still owns a native sequence that can be sliced to `consumed`. - // Without this fallback, the first two branches split the edge - // and every later sibling incorrectly becomes a full miss. - if consumed > 0 - && let Some(stored_tokens) = nearest_resident_descendant(node, &path) - { - best = Some((consumed, stored_tokens)); - } - break; - }; - let common = common_prefix_len(&child.edge, remaining); - if common < child.edge.len() { - let mut child_path = path.clone(); - child_path.extend_from_slice(&child.edge); - if common > 0 - && let Some(stored_tokens) = nearest_resident_descendant(child, &child_path) - { - best = Some((consumed.saturating_add(common), stored_tokens)); - } - break; - } - consumed = consumed.saturating_add(common); - remaining = &remaining[common..]; - path.extend_from_slice(&child.edge); - node = child; - if node.components.resident.is_some() { - best = Some((consumed, path.clone())); - } - } - - if remaining.is_empty() - && let Some(stored_tokens) = nearest_resident_descendant(node, &path) - { - best = Some((consumed, stored_tokens)); - } - best.filter(|(matched, _)| *matched > 0) -} - -fn nearest_resident_descendant( - node: &RadixNode, - node_path: &[i32], -) -> Option> { - if node.components.resident.is_some() { - return Some(node_path.to_vec()); - } - for child in node.children.values() { - let mut child_path = node_path.to_vec(); - child_path.extend_from_slice(&child.edge); - if let Some(candidate) = nearest_resident_descendant(child, &child_path) { - return Some(candidate); - } - } - None -} - fn longest_component_prefix( root: &RadixNode, tokens: &[i32], diff --git a/skippy/crates/skippy-cache/src/radix/resident_matching.rs b/skippy/crates/skippy-cache/src/radix/resident_matching.rs new file mode 100644 index 0000000000..5cd204eb37 --- /dev/null +++ b/skippy/crates/skippy-cache/src/radix/resident_matching.rs @@ -0,0 +1,172 @@ +use super::{RadixNode, common_prefix_len}; + +/// Find the longest query prefix backed by any resident sequence. +/// +/// Unlike recurrent checkpoints, native resident KV can be sliced when copied: +/// a cached sequence for `[1, 2, 3, 4]` can restore `[1, 2]` for a request that +/// diverges at token 3. Native restore only reads the stored resident source, +/// so multiple restores may hold references concurrently; eviction remains +/// blocked until every reference is released. +pub(super) fn resident_backing_prefix( + root: &RadixNode, + tokens: &[i32], +) -> Option<(usize, Vec)> { + let mut node = root; + let mut remaining = tokens; + let mut consumed = 0usize; + let mut path = Vec::new(); + let mut best = None; + + if node.components.resident.is_some() { + best = Some((0, Vec::new())); + } + + while let Some(first) = remaining.first() { + let Some(child) = node.children.get(first) else { + // The query can diverge exactly at an existing branch point. No + // child starts with its next token, but any resident descendant + // still owns a native sequence that can be sliced to `consumed`. + // Without this fallback, the first two branches split the edge + // and every later sibling incorrectly becomes a full miss. + if consumed > 0 + && let Some(stored_tokens) = nearest_resident_descendant(node, &path) + { + best = Some((consumed, stored_tokens)); + } + break; + }; + let common = common_prefix_len(&child.edge, remaining); + if common < child.edge.len() { + let mut child_path = path.clone(); + child_path.extend_from_slice(&child.edge); + if common > 0 + && let Some(stored_tokens) = nearest_resident_descendant(child, &child_path) + { + best = Some((consumed.saturating_add(common), stored_tokens)); + } + break; + } + consumed = consumed.saturating_add(common); + remaining = &remaining[common..]; + path.extend_from_slice(&child.edge); + node = child; + if node.components.resident.is_some() { + best = Some((consumed, path.clone())); + } + } + + if remaining.is_empty() + && let Some(stored_tokens) = nearest_resident_descendant(node, &path) + { + best = Some((consumed, stored_tokens)); + } + best.filter(|(matched, _)| *matched > 0) +} + +fn nearest_resident_descendant( + node: &RadixNode, + node_path: &[i32], +) -> Option> { + if node.components.resident.is_some() { + return Some(node_path.to_vec()); + } + for child in node.children.values() { + let mut child_path = node_path.to_vec(); + child_path.extend_from_slice(&child.edge); + if let Some(candidate) = nearest_resident_descendant(child, &child_path) { + return Some(candidate); + } + } + None +} + +use super::{ + ComponentKind, RadixMatch, UnifiedRadixCache, longest_component_prefix, node_at, node_at_mut, +}; + +impl UnifiedRadixCache { + /// Match only complete stored checkpoints that are prefixes of the query. + /// Recurrent state cannot be truncated to an arbitrary common prefix. + pub fn peek_resident_checkpoint( + &self, + namespace: &str, + tokens: &[i32], + ) -> Option> { + let root = self.roots.get(namespace)?; + let matched = longest_component_prefix(root, tokens, ComponentKind::ResidentKv)?; + let entry = node_at(root, &tokens[..matched])? + .components + .resident + .as_ref()?; + Some(RadixMatch { + matched_tokens: matched, + stored_tokens: tokens[..matched].to_vec(), + logical_bytes: entry.logical_bytes, + active_refs: entry.active_refs, + value: entry.value.clone(), + }) + } + + /// Pin the exact recurrent checkpoint chosen by the non-mutating probe. + pub fn acquire_resident_checkpoint( + &mut self, + namespace: &str, + tokens: &[i32], + ) -> Option> { + let mut hit = self.peek_resident_checkpoint(namespace, tokens)?; + self.clock = self.clock.saturating_add(1); + let entry = node_at_mut(self.roots.get_mut(namespace)?, &hit.stored_tokens)? + .components + .resident + .as_mut()?; + entry.last_used = self.clock; + entry.active_refs = entry.active_refs.saturating_add(1); + hit.active_refs = entry.active_refs; + Some(hit) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recurrent_match_never_slices_a_descendant_checkpoint() { + let mut tree = UnifiedRadixCache::::new(); + tree.insert_resident_if_vacant("model", &[1, 2, 3, 4], 64, 4) + .unwrap(); + assert!(tree.peek_resident_checkpoint("model", &[1, 2]).is_none()); + assert!(tree.peek_resident_checkpoint("model", &[1, 2, 8]).is_none()); + tree.insert_resident_if_vacant("model", &[1, 2], 32, 2) + .unwrap(); + let hit = tree + .peek_resident_checkpoint("model", &[1, 2, 3, 9]) + .unwrap(); + assert_eq!(hit.matched_tokens, 2); + assert_eq!(hit.stored_tokens, [1, 2]); + assert_eq!( + tree.peek_resident_checkpoint("model", &[1, 2, 3, 4, 5]) + .unwrap() + .value, + 4 + ); + assert!( + tree.peek_resident_checkpoint("other", &[1, 2, 3, 4]) + .is_none() + ); + } + + #[test] + fn checkpoint_pin_protects_its_native_owner_until_release() { + let mut tree = UnifiedRadixCache::::new(); + tree.insert_resident_if_vacant("model", &[1, 2], 32, 2) + .unwrap(); + let hit = tree + .acquire_resident_checkpoint("model", &[1, 2, 3]) + .unwrap(); + assert_eq!(hit.active_refs, 1); + assert!(tree.evict_resident_candidate("model", &[1, 2]).is_none()); + assert!(tree.release_resident("model", &hit.stored_tokens)); + assert!(tree.evict_resident_candidate("model", &[1, 2]).is_some()); + } +} diff --git a/skippy/crates/skippy-cache/src/tier.rs b/skippy/crates/skippy-cache/src/tier.rs index dce3154955..e6284972a3 100644 --- a/skippy/crates/skippy-cache/src/tier.rs +++ b/skippy/crates/skippy-cache/src/tier.rs @@ -10,12 +10,18 @@ use std::sync::atomic::Ordering; +mod spill_payload; +mod spill_segments; +use spill_payload::SpillPayload; + +#[cfg(test)] +use crate::l3::SegmentCodecIdentity; use anyhow::{Context, Result, bail}; use serde::Serialize; use crate::l3::{ HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, MANIFEST_VERSION, PayloadCodec, - PayloadGeometry, SegmentCodecIdentity, StoreLimits, StoreUsage, segment_digest, + PayloadGeometry, StoreLimits, StoreUsage, segment_digest, }; use crate::manager::{ BenefitRestoreObservation, L3ActivitySnapshot, L3CacheManager, L3EffectiveStatus, @@ -130,58 +136,6 @@ pub struct L3Tier { segment_bytes: usize, } -#[derive(Debug, Clone, PartialEq, Eq)] -enum SegmentRepresentation { - Raw, - NativeKvPage, - CacheGenKv { - decoded_len: u64, - calibration_digest: String, - }, -} - -impl SegmentRepresentation { - fn identity(&self, encoded_len: u64) -> SegmentCodecIdentity { - match self { - Self::Raw => SegmentCodecIdentity::raw(encoded_len), - Self::NativeKvPage => SegmentCodecIdentity::native_kv_page(encoded_len), - Self::CacheGenKv { - decoded_len, - calibration_digest, - } => SegmentCodecIdentity::cachegen_archive(*decoded_len, calibration_digest.clone()), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct SegmentCut { - offset: u64, - len: u64, - label: String, - representation: SegmentRepresentation, -} - -fn append_fixed_cuts( - cuts: &mut Vec, - offset: &mut u64, - bytes: u64, - segment_bytes: u64, - representation: SegmentRepresentation, -) { - let mut remaining = bytes; - while remaining > 0 { - let len = segment_bytes.max(1).min(remaining); - cuts.push(SegmentCut { - offset: *offset, - len, - label: String::new(), - representation: representation.clone(), - }); - *offset = offset.saturating_add(len); - remaining -= len; - } -} - impl L3Tier { /// Open a tier capped by `budget_bytes` with no free-space reserve. /// Prefer [`Self::open_with_limits`]. @@ -425,81 +379,12 @@ impl L3Tier { cost, mut cachegen, } = options; - if payload.byte_len() == 0 { - bail!( - "refusing to spill an empty exact-state payload: no state component was exported" - ); - } let token_count = token_ids.len() as u64; - let (mut kv, recurrent): (Vec, Vec) = match payload.kind() { - ExactStatePayloadKind::FullState => ( - payload - .full_state_bytes_timed() - .context("failed to reconstruct full state for spill")? - .0 - .into_owned(), - Vec::new(), - ), - ExactStatePayloadKind::RecurrentOnly => ( - Vec::new(), - payload - .recurrent_state_bytes() - .context("failed to reconstruct recurrent state for spill")? - .into_owned(), - ), - ExactStatePayloadKind::KvRecurrent => ( - { - let kv = payload - .kv_bytes() - .context("failed to reconstruct KV bytes for spill")? - .map(|bytes| bytes.into_owned()) - .unwrap_or_default(); - if kv.is_empty() { - bail!("refusing to spill kv-recurrent state without a KV component"); - } - kv - }, - payload - .recurrent_state_bytes() - .context("failed to reconstruct recurrent state for spill")? - .into_owned(), - ), - }; - - let kv_decoded_bytes = kv.len() as u64; - if let Some(cachegen) = cachegen.as_mut() { - if payload.kind() != ExactStatePayloadKind::KvRecurrent - || cachegen.archive.is_empty() - || cachegen.decoded_len != kv_decoded_bytes - || cachegen.calibration_digest.is_empty() - || kv_desc_json.as_deref().is_none_or(str::is_empty) - { - bail!( - "invalid CacheGen spill: archive, descriptor, and decoded KV length are required" - ); - } - let decoded_len = usize::try_from(cachegen.decoded_len) - .context("CacheGen decoded KV length exceeds usize")?; - crate::cachegen::archive::validate_archive(&cachegen.archive, decoded_len) - .context("invalid CacheGen archive supplied for L3 spill")?; - kv = std::mem::take(&mut cachegen.archive); - } - - // For full-state and recurrent-only exactly one component is populated, - // and KV states reach gigabytes: concatenating would peak at twice the - // payload for no benefit. Only a genuine composite needs the copy. - let (kv_bytes, recurrent_bytes) = (kv.len() as u64, recurrent.len() as u64); - let wire = if recurrent.is_empty() { - kv - } else if kv.is_empty() { - recurrent - } else { - let mut wire = Vec::with_capacity(kv.len() + recurrent.len()); - wire.extend_from_slice(&kv); - wire.extend_from_slice(&recurrent); - wire - }; - let payload_digest = segment_digest(&wire); + let wire = SpillPayload::new(payload, cachegen.as_mut(), kv_desc_json.as_deref())?; + let kv_decoded_bytes = wire.decoded_kv_bytes; + let kv_bytes = wire.kv_bytes(); + let recurrent_bytes = wire.recurrent_bytes(); + let payload_digest = wire.digest(); let mut manifest = HandoffManifest::new_for_model( self.model_identity.clone(), @@ -543,79 +428,22 @@ impl L3Tier { } matches }); - let cuts = match geometry { - Some(geometry) => geometry - .plan(self.segment_bytes as u64) - .into_iter() - .map(|(offset, len, label)| SegmentCut { - offset, - len, - representation: if native_kv_passthrough && offset < kv_bytes { - SegmentRepresentation::NativeKvPage - } else { - SegmentRepresentation::Raw - }, - label, - }) - .collect(), - None => { - let mut cuts = Vec::new(); - let mut offset = 0u64; - if let Some(cachegen) = cachegen.as_ref() { - cuts.push(SegmentCut { - offset: 0, - len: kv_bytes, - representation: SegmentRepresentation::CacheGenKv { - decoded_len: cachegen.decoded_len, - calibration_digest: cachegen.calibration_digest.clone(), - }, - label: "cachegen-kv-archive".to_string(), - }); - offset = kv_bytes; - append_fixed_cuts( - &mut cuts, - &mut offset, - recurrent_bytes, - self.segment_bytes as u64, - SegmentRepresentation::Raw, - ); - } else if native_kv_passthrough { - append_fixed_cuts( - &mut cuts, - &mut offset, - kv_bytes, - self.segment_bytes as u64, - SegmentRepresentation::NativeKvPage, - ); - append_fixed_cuts( - &mut cuts, - &mut offset, - recurrent_bytes, - self.segment_bytes as u64, - SegmentRepresentation::Raw, - ); - } else { - append_fixed_cuts( - &mut cuts, - &mut offset, - wire.len() as u64, - self.segment_bytes as u64, - SegmentRepresentation::Raw, - ); - } - cuts - } - }; - let segment_slices = cuts + let cuts = spill_segments::SpillSegmentPlan { + segment_bytes: self.segment_bytes as u64, + kv_bytes, + recurrent_bytes, + native_kv: native_kv_passthrough, + cachegen: cachegen.as_ref(), + } + .cuts(geometry); + let segment_views = cuts .iter() - .map(|cut| { - let start = usize::try_from(cut.offset).context("segment offset exceeds usize")?; - let end = start - .checked_add(usize::try_from(cut.len).context("segment length exceeds usize")?) - .context("segment range overflows")?; - Ok(&wire[start..end]) - }) + .map(|cut| wire.segment(cut.offset, cut.len, self.segment_bytes.max(1))) .collect::>>()?; + let segment_slices = segment_views + .iter() + .map(std::ops::Deref::deref) + .collect::>(); manifest.segments = cuts .iter() .zip(&segment_slices) diff --git a/skippy/crates/skippy-cache/src/tier/spill_payload.rs b/skippy/crates/skippy-cache/src/tier/spill_payload.rs new file mode 100644 index 0000000000..620735f204 --- /dev/null +++ b/skippy/crates/skippy-cache/src/tier/spill_payload.rs @@ -0,0 +1,195 @@ +//! Borrow cold spill components without constructing a second complete snapshot. +use std::borrow::Cow; + +use anyhow::{Context, Result, bail, ensure}; + +use super::CacheGenKvPayload; +use crate::payload::{ExactStatePayload, ExactStatePayloadKind}; + +pub(super) struct SpillPayload<'a> { + kv: Cow<'a, [u8]>, + recurrent: Cow<'a, [u8]>, + total_bytes: usize, + pub(super) decoded_kv_bytes: u64, +} + +impl<'a> SpillPayload<'a> { + pub(super) fn new( + payload: &'a ExactStatePayload, + cachegen: Option<&mut CacheGenKvPayload>, + descriptor: Option<&str>, + ) -> Result { + ensure!( + payload.byte_len() > 0, + "refusing to spill an empty exact-state payload: no state component was exported" + ); + let (kv, recurrent) = match payload.kind() { + ExactStatePayloadKind::FullState => { + (payload.full_state_bytes_timed()?.0, Cow::Borrowed(&[][..])) + } + ExactStatePayloadKind::RecurrentOnly => { + (Cow::Borrowed(&[][..]), payload.recurrent_state_bytes()?) + } + ExactStatePayloadKind::KvRecurrent => { + let kv = payload.kv_bytes()?.unwrap_or(Cow::Borrowed(&[])); + ensure!( + !kv.is_empty(), + "refusing to spill kv-recurrent state without a KV component" + ); + (kv, payload.recurrent_state_bytes()?) + } + }; + let decoded_kv_bytes = kv.len() as u64; + let kv = if let Some(cachegen) = cachegen { + validate_cachegen(payload.kind(), cachegen, decoded_kv_bytes, descriptor)?; + drop(kv); + Cow::Owned(std::mem::take(&mut cachegen.archive)) + } else { + kv + }; + let total_bytes = kv + .len() + .checked_add(recurrent.len()) + .context("spill payload length overflows usize")?; + Ok(Self { + kv, + recurrent, + total_bytes, + decoded_kv_bytes, + }) + } + + pub(super) fn len(&self) -> usize { + self.total_bytes + } + + pub(super) fn kv_bytes(&self) -> u64 { + self.kv.len() as u64 + } + + pub(super) fn recurrent_bytes(&self) -> u64 { + self.recurrent.len() as u64 + } + + pub(super) fn digest(&self) -> String { + let mut hasher = blake3::Hasher::new(); + hasher.update(&self.kv); + hasher.update(&self.recurrent); + hasher.finalize().to_hex().to_string() + } + + /// Ordinary segments borrow one immutable component. Only a cut spanning + /// their boundary needs scratch storage, bounded by the configured segment. + pub(super) fn segment( + &self, + offset: u64, + bytes: u64, + max_scratch_bytes: usize, + ) -> Result> { + let start = usize::try_from(offset).context("segment offset exceeds usize")?; + let len = usize::try_from(bytes).context("segment length exceeds usize")?; + let end = start.checked_add(len).context("segment range overflows")?; + ensure!(end <= self.total_bytes, "segment exceeds spill payload"); + if end <= self.kv.len() { + return Ok(Cow::Borrowed(&self.kv[start..end])); + } + if start >= self.kv.len() { + return Ok(Cow::Borrowed( + &self.recurrent[start - self.kv.len()..end - self.kv.len()], + )); + } + ensure!( + len <= max_scratch_bytes, + "cross-component segment exceeds the spill scratch budget" + ); + let mut segment = Vec::with_capacity(len); + segment.extend_from_slice(&self.kv[start..]); + segment.extend_from_slice(&self.recurrent[..end - self.kv.len()]); + Ok(Cow::Owned(segment)) + } +} + +fn validate_cachegen( + kind: ExactStatePayloadKind, + archive: &CacheGenKvPayload, + decoded_bytes: u64, + descriptor: Option<&str>, +) -> Result<()> { + if kind != ExactStatePayloadKind::KvRecurrent + || archive.archive.is_empty() + || archive.decoded_len != decoded_bytes + || archive.calibration_digest.is_empty() + || descriptor.is_none_or(str::is_empty) + { + bail!("invalid CacheGen spill: archive, descriptor, and decoded KV length are required"); + } + let decoded_len = + usize::try_from(archive.decoded_len).context("CacheGen decoded KV length exceeds usize")?; + crate::cachegen::archive::validate_archive(&archive.archive, decoded_len) + .context("invalid CacheGen archive supplied for L3 spill")?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::l3::segment_digest; + + #[test] + fn component_stream_digest_matches_concatenation_for_every_boundary() { + let bytes: Vec = (0..8195).map(|n| (n % 251) as u8).collect(); + for split in [0, 1, 63, 64, 1023, 1024, 4096, 8194, 8195] { + let view = SpillPayload { + kv: Cow::Borrowed(&bytes[..split]), + recurrent: Cow::Borrowed(&bytes[split..]), + total_bytes: bytes.len(), + decoded_kv_bytes: split as u64, + }; + assert_eq!(view.digest(), segment_digest(&bytes)); + } + } + + #[test] + fn native_components_and_boundary_aligned_segments_borrow_original_storage() { + let payload = ExactStatePayload::kv_recurrent(vec![1; 4096], vec![2; 128]); + let view = SpillPayload::new(&payload, None, None).unwrap(); + assert!(matches!(view.kv, Cow::Borrowed(_))); + assert!(matches!(view.recurrent, Cow::Borrowed(_))); + for (offset, bytes) in [(0, 2048), (2048, 2048), (4096, 128)] { + assert!(matches!( + view.segment(offset, bytes, 2048).unwrap(), + Cow::Borrowed(_) + )); + } + let kv = payload.kv_bytes().unwrap().unwrap(); + assert_eq!(view.segment(0, 4096, 2048).unwrap().as_ptr(), kv.as_ptr()); + } + + #[test] + fn cross_component_cut_materializes_only_the_bounded_segment() { + let payload = ExactStatePayload::kv_recurrent(vec![1, 2, 3], vec![4, 5, 6]); + let view = SpillPayload::new(&payload, None, None).unwrap(); + let segment = view.segment(2, 3, 3).unwrap(); + assert!(matches!(segment, Cow::Owned(_))); + assert_eq!(segment.as_ref(), &[3, 4, 5]); + assert!(view.segment(2, 3, 2).is_err()); + assert!(view.segment(5, 2, 10).is_err()); + assert!(view.segment(u64::MAX, 2, 10).is_err()); + } + + #[test] + fn single_component_payloads_and_empty_boundary_segments_do_not_copy() { + for payload in [ + ExactStatePayload::full_state(vec![7, 8, 9]), + ExactStatePayload::recurrent_only(vec![7, 8, 9]), + ExactStatePayload::kv_recurrent(vec![7, 8, 9], Vec::new()), + ] { + let view = SpillPayload::new(&payload, None, None).unwrap(); + assert_eq!(view.digest(), segment_digest(&[7, 8, 9])); + assert_eq!(view.len(), 3); + assert!(matches!(view.segment(0, 3, 1).unwrap(), Cow::Borrowed(_))); + assert!(matches!(view.segment(3, 0, 1).unwrap(), Cow::Borrowed(_))); + } + assert!(SpillPayload::new(&ExactStatePayload::full_state(Vec::new()), None, None).is_err()); + } +} diff --git a/skippy/crates/skippy-cache/src/tier/spill_segments.rs b/skippy/crates/skippy-cache/src/tier/spill_segments.rs new file mode 100644 index 0000000000..040aa3aa8b --- /dev/null +++ b/skippy/crates/skippy-cache/src/tier/spill_segments.rs @@ -0,0 +1,185 @@ +//! Preserve component-aware disk segment boundaries without concatenating payloads. +use super::CacheGenKvPayload; +use crate::l3::{PayloadGeometry, SegmentCodecIdentity}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum SegmentRepresentation { + Raw, + NativeKvPage, + CacheGenKv { + decoded_len: u64, + calibration_digest: String, + }, +} + +impl SegmentRepresentation { + pub(super) fn identity(&self, encoded_len: u64) -> SegmentCodecIdentity { + match self { + Self::Raw => SegmentCodecIdentity::raw(encoded_len), + Self::NativeKvPage => SegmentCodecIdentity::native_kv_page(encoded_len), + Self::CacheGenKv { + decoded_len, + calibration_digest, + } => SegmentCodecIdentity::cachegen_archive(*decoded_len, calibration_digest.clone()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct SegmentCut { + pub(super) offset: u64, + pub(super) len: u64, + pub(super) label: String, + pub(super) representation: SegmentRepresentation, +} + +fn append_fixed_cuts( + cuts: &mut Vec, + offset: &mut u64, + bytes: u64, + segment_bytes: u64, + representation: SegmentRepresentation, +) { + let mut remaining = bytes; + while remaining > 0 { + let len = segment_bytes.max(1).min(remaining); + cuts.push(SegmentCut { + offset: *offset, + len, + label: String::new(), + representation: representation.clone(), + }); + *offset = offset.saturating_add(len); + remaining -= len; + } +} + +pub(super) struct SpillSegmentPlan<'a> { + pub(super) segment_bytes: u64, + pub(super) kv_bytes: u64, + pub(super) recurrent_bytes: u64, + pub(super) native_kv: bool, + pub(super) cachegen: Option<&'a CacheGenKvPayload>, +} + +impl SpillSegmentPlan<'_> { + pub(super) fn cuts(&self, geometry: Option<&PayloadGeometry>) -> Vec { + match geometry { + Some(geometry) => geometry + .plan(self.segment_bytes) + .into_iter() + .map(|(offset, len, label)| SegmentCut { + offset, + len, + representation: if self.native_kv && offset < self.kv_bytes { + SegmentRepresentation::NativeKvPage + } else { + SegmentRepresentation::Raw + }, + label, + }) + .collect(), + None => { + let mut cuts = Vec::new(); + let mut offset = 0u64; + if let Some(cachegen) = self.cachegen { + cuts.push(SegmentCut { + offset: 0, + len: self.kv_bytes, + representation: SegmentRepresentation::CacheGenKv { + decoded_len: cachegen.decoded_len, + calibration_digest: cachegen.calibration_digest.clone(), + }, + label: "cachegen-kv-archive".to_string(), + }); + offset = self.kv_bytes; + append_fixed_cuts( + &mut cuts, + &mut offset, + self.recurrent_bytes, + self.segment_bytes, + SegmentRepresentation::Raw, + ); + } else if self.native_kv { + append_fixed_cuts( + &mut cuts, + &mut offset, + self.kv_bytes, + self.segment_bytes, + SegmentRepresentation::NativeKvPage, + ); + append_fixed_cuts( + &mut cuts, + &mut offset, + self.recurrent_bytes, + self.segment_bytes, + SegmentRepresentation::Raw, + ); + } else { + append_fixed_cuts( + &mut cuts, + &mut offset, + self.kv_bytes.saturating_add(self.recurrent_bytes), + self.segment_bytes, + SegmentRepresentation::Raw, + ); + } + cuts + } + } + } +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use super::*; + use crate::payload::ExactStatePayload; + use crate::tier::spill_payload::SpillPayload; + + #[test] + fn raw_segments_cross_component_boundary_with_only_one_bounded_copy() { + let payload = ExactStatePayload::kv_recurrent(vec![1, 2, 3], vec![4, 5, 6]); + let view = SpillPayload::new(&payload, None, None).unwrap(); + let cuts = SpillSegmentPlan { + segment_bytes: 4, + kv_bytes: 3, + recurrent_bytes: 3, + native_kv: false, + cachegen: None, + } + .cuts(None); + let segments = cuts + .iter() + .map(|cut| view.segment(cut.offset, cut.len, 4).unwrap()) + .collect::>(); + assert_eq!(segments[0].as_ref(), &[1, 2, 3, 4]); + assert_eq!(segments[1].as_ref(), &[5, 6]); + assert!(matches!(segments[0], Cow::Owned(_))); + assert!(matches!(segments[1], Cow::Borrowed(_))); + } + + #[test] + fn native_kv_cut_boundary_never_materializes_a_composite_segment() { + let payload = ExactStatePayload::kv_recurrent(vec![1, 2, 3], vec![4, 5, 6]); + let view = SpillPayload::new(&payload, None, None).unwrap(); + let cuts = SpillSegmentPlan { + segment_bytes: 4, + kv_bytes: 3, + recurrent_bytes: 3, + native_kv: true, + cachegen: None, + } + .cuts(None); + assert_eq!(cuts.len(), 2); + assert_eq!(cuts[0].representation, SegmentRepresentation::NativeKvPage); + assert_eq!(cuts[1].representation, SegmentRepresentation::Raw); + for cut in cuts { + assert!(matches!( + view.segment(cut.offset, cut.len, 4).unwrap(), + Cow::Borrowed(_) + )); + } + } +} diff --git a/skippy/crates/skippy-cli/src/conversion.rs b/skippy/crates/skippy-cli/src/conversion.rs index a0f25d32dd..521a16923e 100644 --- a/skippy/crates/skippy-cli/src/conversion.rs +++ b/skippy/crates/skippy-cli/src/conversion.rs @@ -268,8 +268,7 @@ pub fn local_openai_options( args.kv_cache_disk_dir.clone(), args.kv_cache_min_free.as_deref(), )?; - args.settings - .validate_cache_dependencies(&config, disk_cache.is_some())?; + args.settings.validate_cache_dependencies(&config)?; Ok(skippy_api::serving::LocalOpenAiOptions { tuning, config, diff --git a/skippy/crates/skippy-cli/src/serve.rs b/skippy/crates/skippy-cli/src/serve.rs index d1c84f34b0..a2a7f963b6 100644 --- a/skippy/crates/skippy-cli/src/serve.rs +++ b/skippy/crates/skippy-cli/src/serve.rs @@ -198,7 +198,7 @@ async fn serve_binary_stage(mut args: ServeCommandArgs) -> Result<()> { let mut options = conversion::binary_stage_options(args.stage)?; args.public .settings - .validate_cache_dependencies(&options.config, disk_cache.is_some())?; + .validate_cache_dependencies(&options.config)?; if args.print_effective_config { let frontend = options.openai.as_ref().map(|stage| { let mut frontend = skippy_api::serving::InferenceOptions::embedded_stage_defaults( diff --git a/skippy/crates/skippy-cli/src/serve_settings/catalog.rs b/skippy/crates/skippy-cli/src/serve_settings/catalog.rs index f64d772d70..d88f450a40 100644 --- a/skippy/crates/skippy-cli/src/serve_settings/catalog.rs +++ b/skippy/crates/skippy-cli/src/serve_settings/catalog.rs @@ -215,7 +215,7 @@ pub const OPTIONS: &[OptionSpec] = &[ "cache", "kv_cache.l2_max_bytes", Kind::Bytes, - "Host-RAM tier: off or IEC size; requires disk caching", + "Resident checkpoint RAM budget: off for default or a fixed IEC size; independent of disk", ), option( "prefix-cache-max-entries", diff --git a/skippy/crates/skippy-cli/src/serve_settings/resolution.rs b/skippy/crates/skippy-cli/src/serve_settings/resolution.rs index 689089de92..0c29466ba2 100644 --- a/skippy/crates/skippy-cli/src/serve_settings/resolution.rs +++ b/skippy/crates/skippy-cli/src/serve_settings/resolution.rs @@ -60,12 +60,8 @@ impl ServeSettings { } } - pub fn validate_cache_dependencies(&self, config: &StageConfig, disk: bool) -> Result<()> { + pub fn validate_cache_dependencies(&self, config: &StageConfig) -> Result<()> { if let Some(cache) = &config.kv_cache { - anyhow::ensure!( - cache.l2_max_bytes == 0 || disk, - "--prefix-cache-ram requires an enabled --kv-cache-disk tier" - ); anyhow::ensure!( cache.mode != StageKvCacheMode::Disabled || cache.l2_max_bytes == 0, "RAM caching requires enabled prefix caching" diff --git a/skippy/crates/skippy-cli/src/serve_settings/tests.rs b/skippy/crates/skippy-cli/src/serve_settings/tests.rs index db1b8b5d17..09c7cab20b 100644 --- a/skippy/crates/skippy-cli/src/serve_settings/tests.rs +++ b/skippy/crates/skippy-cli/src/serve_settings/tests.rs @@ -849,11 +849,17 @@ fn invalid_controls_fail_before_loading_models() { .unwrap_err(); assert!(error.to_string().contains(message), "{error}"); } +} + +#[test] +fn checkpoint_ram_budget_does_not_require_disk() { let Command::Serve(args) = parse_test(&[ "skippy", "serve", "--model", "missing.gguf", + "--prefix-cache", + "on", "--prefix-cache-ram", "1GiB", ]) @@ -864,13 +870,20 @@ fn invalid_controls_fail_before_loading_models() { }; let mut stage: StageConfig = serde_json::from_value(skippy_config::example_config()).unwrap(); args.public.settings.apply_stage(&mut stage).unwrap(); + args.public + .settings + .validate_cache_dependencies(&stage) + .unwrap(); + assert_eq!( + stage.kv_cache.as_ref().unwrap().l2_max_bytes, + 1024 * 1024 * 1024 + ); + stage.kv_cache.as_mut().unwrap().mode = skippy_protocol::StageKvCacheMode::Disabled; assert!( args.public .settings - .validate_cache_dependencies(&stage, false) - .unwrap_err() - .to_string() - .contains("requires") + .validate_cache_dependencies(&stage) + .is_err() ); } diff --git a/skippy/crates/skippy-ffi/src/dynamic.rs b/skippy/crates/skippy-ffi/src/dynamic.rs index da4de7ad54..31251e6dbc 100644 --- a/skippy/crates/skippy-ffi/src/dynamic.rs +++ b/skippy/crates/skippy-ffi/src/dynamic.rs @@ -266,6 +266,9 @@ dynamic_symbols! { skippy_model_memory_cache_capabilities(model: *const Model) -> u32; skippy_export_recurrent_state(session: *mut Session, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_import_recurrent_state(session: *mut Session, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; + skippy_session_export_resident_kv_page(session: *mut Session, cache_seq_id: i32, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; + skippy_session_export_resident_recurrent_state(session: *mut Session, cache_seq_id: i32, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; + skippy_session_resident_prefix_bytes(session: *mut Session, cache_seq_id: i32, out_bytes: *mut u64, out_error: *mut *mut Error) -> Status; skippy_session_save_prefix(session: *mut Session, cache_seq_id: i32, token_count: u64, out_error: *mut *mut Error) -> Status; skippy_session_restore_prefix(session: *mut Session, cache_seq_id: i32, token_ids: *const i32, token_count: usize, out_error: *mut *mut Error) -> Status; skippy_session_memory_used_cells(session: *mut Session, out_used_cells: *mut u64, out_error: *mut *mut Error) -> Status; diff --git a/skippy/crates/skippy-ffi/src/lib.rs b/skippy/crates/skippy-ffi/src/lib.rs index 93095ea979..f95afe6682 100644 --- a/skippy/crates/skippy-ffi/src/lib.rs +++ b/skippy/crates/skippy-ffi/src/lib.rs @@ -199,9 +199,11 @@ pub use dynamic::{ skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, skippy_session_create, skippy_session_create_from_resident_prefix, skippy_session_drop_sequence, skippy_session_embed, skippy_session_encode_prompt, - skippy_session_end_external_decode, skippy_session_free, skippy_session_last_token_signal, - skippy_session_llama_context, skippy_session_memory_used_cells, skippy_session_position, - skippy_session_rerank, skippy_session_reset, skippy_session_restore_prefix, + skippy_session_end_external_decode, skippy_session_export_resident_kv_page, + skippy_session_export_resident_recurrent_state, skippy_session_free, + skippy_session_last_token_signal, skippy_session_llama_context, + skippy_session_memory_used_cells, skippy_session_position, skippy_session_rerank, + skippy_session_reset, skippy_session_resident_prefix_bytes, skippy_session_restore_prefix, skippy_session_restore_token_history, skippy_session_sample_current, skippy_session_save_prefix, skippy_session_sequence_id, skippy_session_set_position, skippy_session_signal_window, skippy_session_take_token_logprobs, diff --git a/skippy/crates/skippy-protocol/src/config.rs b/skippy/crates/skippy-protocol/src/config.rs index 7e83c791a4..55098cfe66 100644 --- a/skippy/crates/skippy-protocol/src/config.rs +++ b/skippy/crates/skippy-protocol/src/config.rs @@ -545,8 +545,10 @@ pub struct StageKvCacheConfig { pub max_entries: usize, #[serde(default)] pub max_bytes: u64, - /// Hard byte budget for the opt-in host-RAM L2 exact-state tier. - /// Zero keeps L2 disabled. + /// Host-RAM byte budget. Native resident caching uses this for retained + /// checkpoint and token metadata, independently of disk; zero selects its + /// bounded default. Serialized runtimes use an opt-in L2 mirror, where zero + /// disables that mirror. #[serde(default)] pub l2_max_bytes: u64, /// Exact-state retention ceiling; None derives eight times max_bytes. diff --git a/skippy/crates/skippy-runtime/src/lib.rs b/skippy/crates/skippy-runtime/src/lib.rs index 55fdcc079b..d85901f94f 100644 --- a/skippy/crates/skippy-runtime/src/lib.rs +++ b/skippy/crates/skippy-runtime/src/lib.rs @@ -22,6 +22,7 @@ mod native_test_evidence; mod ngram; pub mod package; mod path_cstring; +mod resident_prefix; mod runtime_event_reporter; mod runtime_events; mod session; diff --git a/skippy/crates/skippy-runtime/src/resident_prefix.rs b/skippy/crates/skippy-runtime/src/resident_prefix.rs new file mode 100644 index 0000000000..731e93ce76 --- /dev/null +++ b/skippy/crates/skippy-runtime/src/resident_prefix.rs @@ -0,0 +1,134 @@ +//! Export cache-owned prefixes only at explicit cold/offload boundaries. +use crate::error::{ensure_ok, free_error}; +use crate::{RuntimeKvPage, RuntimeKvPageDesc, Status, session::StageSession}; +use anyhow::{Result, ensure}; +use std::ptr; + +impl StageSession { + pub fn resident_kv_page_desc( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: u64, + ) -> Result { + let mut desc = skippy_ffi::KvPageDesc::default(); + let mut bytes = 0; + let mut error = ptr::null_mut(); + // SAFETY: The live session and all output pointers remain valid for the call. + let status = unsafe { + skippy_ffi::skippy_session_export_resident_kv_page( + self.raw, + sequence, + layers.0, + layers.1, + 0, + tokens, + &mut desc, + ptr::null_mut(), + 0, + &mut bytes, + &mut error, + ) + }; + check_export_size(status, error)?; + ensure!( + desc.payload_bytes == bytes as u64, + "resident KV export size mismatch" + ); + Ok(desc.into()) + } + + pub fn export_resident_kv_page( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: u64, + bytes: usize, + ) -> Result { + let mut desc = skippy_ffi::KvPageDesc::default(); + let mut payload = vec![0; bytes]; + let mut written = 0; + let mut error = ptr::null_mut(); + // SAFETY: The session is live and the output allocation has the advertised capacity. + let status = unsafe { + skippy_ffi::skippy_session_export_resident_kv_page( + self.raw, + sequence, + layers.0, + layers.1, + 0, + tokens, + &mut desc, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + ) + }; + ensure_ok(status, error)?; + ensure!( + written <= payload.len(), + "resident KV export exceeded reserved bytes" + ); + payload.truncate(written); + Ok(RuntimeKvPage { + desc: desc.into(), + payload, + }) + } + + pub fn resident_recurrent_state_bytes(&mut self, sequence: i32) -> Result { + let mut bytes = 0; + let mut error = ptr::null_mut(); + // SAFETY: The live session and byte-count/error outputs are valid. + let status = unsafe { + skippy_ffi::skippy_session_export_resident_recurrent_state( + self.raw, + sequence, + ptr::null_mut(), + 0, + &mut bytes, + &mut error, + ) + }; + check_export_size(status, error)?; + Ok(bytes) + } + + pub fn export_resident_recurrent_state( + &mut self, + sequence: i32, + bytes: usize, + ) -> Result> { + let mut payload = vec![0; bytes]; + let mut written = 0; + let mut error = ptr::null_mut(); + // SAFETY: The session is live and output storage matches the reserved capacity. + let status = unsafe { + skippy_ffi::skippy_session_export_resident_recurrent_state( + self.raw, + sequence, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + ) + }; + ensure_ok(status, error)?; + ensure!( + written <= payload.len(), + "resident recurrent export exceeded reserved bytes" + ); + payload.truncate(written); + Ok(payload) + } +} + +fn check_export_size(status: Status, error: *mut skippy_ffi::Error) -> Result<()> { + if status == Status::BufferTooSmall || status == Status::Ok { + free_error(error); + Ok(()) + } else { + ensure_ok(status, error) + } +} diff --git a/skippy/crates/skippy-runtime/src/session.rs b/skippy/crates/skippy-runtime/src/session.rs index d6aee0e529..090845233f 100644 --- a/skippy/crates/skippy-runtime/src/session.rs +++ b/skippy/crates/skippy-runtime/src/session.rs @@ -304,6 +304,23 @@ impl StageSession { Ok(()) } + /// Host bytes owned by one native prefix, excluding shared attention cells. + pub fn resident_prefix_bytes(&mut self, cache_seq_id: i32) -> Result { + let mut bytes = 0; + let mut error = ptr::null_mut(); + // SAFETY: The session is live and both output pointers are valid for this call. + let status = unsafe { + skippy_ffi::skippy_session_resident_prefix_bytes( + self.raw, + cache_seq_id, + &mut bytes, + &mut error, + ) + }; + ensure_ok(status, error)?; + Ok(bytes) + } + pub fn save_prefix(&mut self, cache_seq_id: i32, token_count: u64) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { diff --git a/skippy/crates/skippy-runtime/src/types.rs b/skippy/crates/skippy-runtime/src/types.rs index fd358e34ee..668da9e5cb 100644 --- a/skippy/crates/skippy-runtime/src/types.rs +++ b/skippy/crates/skippy-runtime/src/types.rs @@ -44,6 +44,10 @@ pub enum ModelStateKind { #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct MemoryCacheCapabilities { pub resident: bool, + /// Resident state is an indivisible recurrent checkpoint, not a sliceable KV alias. + pub resident_checkpoint: bool, + /// Native resident prefixes contain attention cells as well as any checkpoint. + pub resident_attention: bool, pub kv_recurrent: bool, pub full_state: bool, } @@ -52,6 +56,8 @@ impl MemoryCacheCapabilities { pub(crate) fn from_native_bits(bits: u32) -> Self { Self { resident: bits & 1 != 0, + resident_checkpoint: bits & 8 != 0, + resident_attention: bits & 16 != 0, kv_recurrent: bits & 2 != 0, full_state: bits & 4 != 0, } diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs index f4ce45f44c..662fd4758a 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs @@ -259,6 +259,8 @@ mod tests { &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, resident: true, kv_recurrent: true, full_state: true, @@ -271,7 +273,8 @@ mod tests { let (_, message) = exact_prefill_fixture(970); assert!(kv.records_resident_prefixes()); - assert!(kv.payload_is_exact_state()); + assert!(!kv.payload_is_exact_state()); + assert!(kv.exact_state_payload().is_some()); assert!(!kv.exact_state_record_token_count_allowed(970, 970)); assert!(exact_prefill_record_allowed(&kv, &message, 970)); } diff --git a/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs b/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs index 7f64b32eba..d330b04c41 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs @@ -161,7 +161,7 @@ pub(super) fn handle_binary_restore_prefill_decode_control( if let Some(metadata) = scheduler_message.chat_sampling_metadata.as_deref() { let sampling = runtime_sampling_config( scheduler_message.sampling.as_ref(), - runtime.kv_pool_tokens(), + runtime.context_tokens_per_lane(), ); runtime .configure_chat_sampling( diff --git a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs index 2aa6f203dd..39b3b281be 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs @@ -785,8 +785,10 @@ fn execute_binary_stage_message( Ok((message.state.current_token, Vec::new(), output, None)) } WireMessageKind::PrefillFinalEmbd if options.sample_final_prefill => { - let sampling = - runtime_sampling_config(message.sampling.as_ref(), runtime.kv_pool_tokens()); + let sampling = runtime_sampling_config( + message.sampling.as_ref(), + runtime.context_tokens_per_lane(), + ); let (predicted, output) = runtime.prefill_final_frame_sampled( session_id, token_ids, @@ -814,8 +816,10 @@ fn execute_binary_stage_message( .first() .copied() .unwrap_or(message.state.current_token); - let sampling = - runtime_sampling_config(message.sampling.as_ref(), runtime.kv_pool_tokens()); + let sampling = runtime_sampling_config( + message.sampling.as_ref(), + runtime.context_tokens_per_lane(), + ); let draft_tokens = native_mtp_draft_tokens(message, options); if !options.native_mtp_enabled || draft_tokens == 0 || dflash_drafts { let (predicted, output) = runtime.decode_frame_sampled( diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index a2bba6ab41..ed2ebe25a4 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -31,7 +31,8 @@ use skippy_runtime::SamplingConfig; // The real-model tests below are deliberately ignored by default. The // fixture contract is explicit: run them with both model-path variables set; -// optionally set SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID to override the model id. +// optionally set SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID to override the model id +// and SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS=99 to validate the GPU backend. // For example: // // SKIPPY_RECURRENT_CACHE_TEST_MODEL=/path/model.gguf \ @@ -162,6 +163,8 @@ fn wait_for_receipts(sink: &RecordingReceiptSink, expected: usize) { panic!("timed out waiting for {expected} generation receipts"); } +const RECURRENT_TEST_CHECKPOINT_RAM_BYTES: u64 = 8 * 1024 * 1024 * 1024; + fn recurrent_test_backend( run_id: &str, backend_model_id: &str, @@ -170,6 +173,7 @@ fn recurrent_test_backend( default_max_tokens: u32, token_budget: usize, ) -> Result<(StageOpenAiBackend, SpeculativeDecodeConfig)> { + skippy_runtime::test_support::require_native_runtime(); let model_path = std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_MODEL").ok_or_else(|| { anyhow::anyhow!("SKIPPY_RECURRENT_CACHE_TEST_MODEL is required for this ignored test") })?; @@ -206,7 +210,12 @@ fn recurrent_test_backend( lane_count: 1, n_batch: Some(batch_size), n_ubatch: Some(batch_size), - n_gpu_layers: 0, + n_gpu_layers: std::env::var("SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS") + .ok() + .map(|value| value.parse::()) + .transpose() + .map_err(|error| anyhow::anyhow!("invalid recurrent cache GPU layer count: {error}"))? + .unwrap_or(0), mmap: Some(true), mlock: false, repack: false, @@ -231,7 +240,7 @@ fn recurrent_test_backend( mode: StageKvCacheMode::LookupRecord, max_entries: 8, max_bytes: 0, - l2_max_bytes: 0, + l2_max_bytes: RECURRENT_TEST_CHECKPOINT_RAM_BYTES, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -246,10 +255,27 @@ fn recurrent_test_backend( }; let runtime = load_runtime(&config)? .ok_or_else(|| anyhow::anyhow!("recurrent cache test runtime was not loaded"))?; - let kv = - KvStageIntegration::from_test_state(&config, skippy_runtime::ModelStateKind::Recurrent)? - .map(Arc::new) - .ok_or_else(|| anyhow::anyhow!("recurrent cache test did not enable KV integration"))?; + let kv = KvStageIntegration::from_loaded_model( + &config, + crate::runtime_state::loaded_model_state_kind(Some(&runtime)), + crate::runtime_state::loaded_memory_cache_capabilities(Some(&runtime)), + None, + )? + .map(Arc::new) + .ok_or_else(|| anyhow::anyhow!("recurrent cache test did not enable KV integration"))?; + assert!( + kv.records_resident_prefixes(), + "fixture must exercise native prefix ownership" + ); + assert!( + kv.resident_requires_checkpoint(), + "fixture requires recurrent native memory" + ); + assert_eq!( + kv.resident_checkpoint_max_bytes, + RECURRENT_TEST_CHECKPOINT_RAM_BYTES + ); + assert_eq!(kv.resident_config.max_entries, 8); let telemetry = Telemetry::new(None, 1, config.clone(), TelemetryLevel::Off); let speculative = SpeculativeDecodeConfig::default(); let iteration_scheduler = diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index 667567c192..d02209dbc0 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -1138,7 +1138,10 @@ impl StageOpenAiBackend { prefill_tokens: &[i32], restored_prefill_tokens: usize, ) -> Option { - let kv = self.kv.as_ref().filter(|kv| kv.payload_is_exact_state())?; + let kv = self + .kv + .as_ref() + .filter(|kv| kv.retains_recurrent_checkpoints())?; let base = self.local_kv_message_base(session_id, request.ids); let shared_checkpoint = kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index 5b2133c5b7..b1c8d766ec 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -38,7 +38,7 @@ impl StageOpenAiBackend { let Some(kv) = self.kv.as_ref() else { return false; }; - if !kv.payload_is_exact_state() { + if !kv.payload_is_exact_state() && !kv.records_resident_prefixes() { return false; } let Some(checkpoint_tokens) = @@ -153,7 +153,7 @@ impl StageOpenAiBackend { let Some(kv) = self.kv.as_ref() else { return false; }; - if !kv.payload_is_exact_state() { + if !kv.payload_is_exact_state() && !kv.records_resident_prefixes() { return false; } let Ok(checkpoint_token_count) = u64::try_from(checkpoint_tokens.len()) else { @@ -230,6 +230,30 @@ impl StageOpenAiBackend { let base = self.local_kv_message_base(session_id, ids); let identity = kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens); + if kv.records_resident_prefixes() { + let recorded = kv + .record_resident_prefix(runtime, session_id, &identity, checkpoint_tokens) + .is_ok_and(|record| record.is_some()); + #[cfg(test)] + { + if recorded && decision_prefix == "post_decode_checkpoint" { + super::capture_trace::POST_DECODE_RECORDED + .fetch_add(1, std::sync::atomic::Ordering::AcqRel); + } + super::capture_trace::log_capture_decision( + decision_prefix, + if recorded { + "native_prefix_recorded" + } else { + "native_prefix_skipped" + }, + checkpoint_token_count, + Some(runtime_token_count), + Some(&identity.namespace), + ); + } + return recorded; + } #[cfg(test)] let decision_namespace = identity.namespace.clone(); let admission = if decision_prefix == "post_decode_checkpoint" { diff --git a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs index 9346f779f5..943c96627e 100644 --- a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -187,7 +187,10 @@ impl StageOpenAiBackend { prefill_tokens: &[i32], restored_prefill_tokens: usize, ) -> Option { - let kv = self.kv.as_ref().filter(|kv| kv.payload_is_exact_state())?; + let kv = self + .kv + .as_ref() + .filter(|kv| kv.retains_recurrent_checkpoints())?; let shared_boundary = kv .exact_shared_checkpoint_token_count(prefill_tokens.len() as u64) .and_then(|token_count| usize::try_from(token_count).ok()); @@ -560,7 +563,7 @@ impl StageOpenAiBackend { .collect::>>() }, )?; - let exact_record_queued = kv.payload_is_exact_state() + let exact_record_queued = kv.retains_recurrent_checkpoints() && self.enqueue_exact_state_record_at_tokens( session_id, ids, @@ -623,7 +626,10 @@ impl StageOpenAiBackend { let Some(kv) = self.kv.as_ref() else { return Ok(false); }; - if checkpoint_tokens.is_empty() || !kv.payload_is_exact_state() || !kv.should_record() { + if checkpoint_tokens.is_empty() + || !kv.retains_recurrent_checkpoints() + || !kv.should_record() + { return Ok(false); } let scheduler_backend = self.clone(); diff --git a/skippy/crates/skippy-serving/src/frontend/prompting.rs b/skippy/crates/skippy-serving/src/frontend/prompting.rs index 0303d57c11..199ff69f93 100644 --- a/skippy/crates/skippy-serving/src/frontend/prompting.rs +++ b/skippy/crates/skippy-serving/src/frontend/prompting.rs @@ -11,7 +11,6 @@ use crate::frontend::generation::run_blocking_generation_worker; use crate::frontend::generation::tool_calls_requested; use crate::frontend::tool_emulation; use crate::frontend::util::openai_backend_error; -use crate::kv_integration::StagePrefixCachePayload; use crate::runtime_state::panic_recovery::lock_runtime; use serde_json::Value; use skippy_inference_api::GenerationHookSignals; @@ -93,7 +92,7 @@ impl StageOpenAiBackend { let recurrent_cache_prefix_text = if self .kv .as_ref() - .is_some_and(|kv| kv.payload == StagePrefixCachePayload::KvRecurrent) + .is_some_and(|kv| kv.retains_recurrent_checkpoints()) && emulated.media.is_empty() && options.add_assistant { @@ -116,7 +115,7 @@ impl StageOpenAiBackend { let recurrent_cache_prefix_text = if self .kv .as_ref() - .is_some_and(|kv| kv.payload == StagePrefixCachePayload::KvRecurrent) + .is_some_and(|kv| kv.retains_recurrent_checkpoints()) && native.media.is_empty() && options.add_assistant { diff --git a/skippy/crates/skippy-serving/src/frontend/tests/prefix_cache_lifecycle.rs b/skippy/crates/skippy-serving/src/frontend/tests/prefix_cache_lifecycle.rs index f9e5a1e06d..515eb4543f 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/prefix_cache_lifecycle.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/prefix_cache_lifecycle.rs @@ -115,6 +115,8 @@ fn real_initialization_notifies_started_then_completed() { &config, Some(skippy_runtime::ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, resident: true, kv_recurrent: true, full_state: true, @@ -151,6 +153,8 @@ fn disabled_kv_config_never_notifies_init_at_all() { &config, Some(skippy_runtime::ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, resident: true, kv_recurrent: true, full_state: true, diff --git a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs index 195b1d9cb6..ab85d3b7f2 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -22,8 +22,8 @@ impl KvStageIntegration { let matched_tokens = identities .iter() .filter_map(|identity| match self.payload { - StagePrefixCachePayload::ResidentKv => radix - .peek_resident(&identity.namespace, &identity.token_ids) + StagePrefixCachePayload::ResidentKv => self + .peek_native_prefix(&radix, &identity.namespace, &identity.token_ids) .map(|hit| hit.matched_tokens), StagePrefixCachePayload::KvRecurrent | StagePrefixCachePayload::FullState => radix .peek_recurrent(&identity.namespace, &identity.token_ids) @@ -152,3 +152,101 @@ mod tests { holder.join().unwrap(); } } + +#[cfg(test)] +mod checkpoint_matching_tests { + use super::*; + use crate::kv_integration::RadixResidentEntry; + use skippy_protocol::{MessageBase, StageKvCacheConfig, StageKvCacheMode}; + use skippy_runtime::MemoryCacheCapabilities; + + #[test] + fn scheduler_and_restore_probe_choose_the_same_complete_checkpoint() { + let config = StageConfig { + kv_cache: Some(StageKvCacheConfig { + mode: StageKvCacheMode::LookupRecord, + max_entries: 64, + max_bytes: 0, + l2_max_bytes: 128, + exact_max_bytes: None, + codec: Default::default(), + min_tokens: 1, + shared_prefix_stride_tokens: 128, + shared_prefix_record_limit: 2, + }), + ..StageConfig::default() + }; + // An arbitrary state-kind label cannot override the loaded memory contract. + let integration = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(skippy_runtime::ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_checkpoint: true, + resident_attention: true, + kv_recurrent: true, + full_state: true, + }), + None, + None, + ) + .unwrap() + .unwrap(); + assert!( + !integration.native_components_are_complete(32, 0, true), + "KV-only cannot restore hybrid state" + ); + assert!( + !integration.native_components_are_complete(0, 32, true), + "hybrid state requires attention KV" + ); + assert!( + !integration.native_components_are_complete(32, 32, false), + "attention state requires a descriptor" + ); + assert!(integration.native_components_are_complete(32, 32, true)); + let base = MessageBase { + schema_version: skippy_protocol::SCHEMA_VERSION, + run_id: "run".into(), + request_id: "request".into(), + session_id: "session".into(), + stage_id: "stage".into(), + stage_index: 0, + topology_id: "topology".into(), + model_id: None, + tokenizer_id: None, + chat_template_id: None, + seq: None, + }; + let short = integration.prefill_identity(&config, &base, 0, &[1, 2]); + let longer = integration.prefill_identity(&config, &base, 0, &[1, 2, 3, 4]); + let query = integration.prefill_identity(&config, &base, 0, &[1, 2, 3, 8]); + { + let mut radix = integration.radix.lock().unwrap(); + for (identity, seq) in [(&short, 8), (&longer, 9)] { + radix + .insert_resident( + &identity.namespace, + &identity.token_ids, + 32, + RadixResidentEntry { + page_id: identity.page_id.clone(), + seq_id: seq, + token_count: identity.token_ids.len() as u64, + recompute_cost: 1, + }, + ) + .unwrap(); + } + } + assert_eq!( + integration + .probe_resident_prefix(&query) + .unwrap() + .token_count, + 2 + ); + let affinity = integration.peek_cache_affinity(&config, &[query]); + assert_eq!(affinity.matched_tokens(), 2); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/cache_payload.rs b/skippy/crates/skippy-serving/src/kv_integration/cache_payload.rs index 0ae21cf2b7..f9f671a685 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/cache_payload.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/cache_payload.rs @@ -17,14 +17,15 @@ pub(super) fn effective_cache_payload( } } -/// Durable tiers require an admitted byte exporter; resident handles cannot spill. +/// Resident prefixes materialize complete components only at cold offload boundaries. pub(super) fn durable_cache_payload( admitted: MemoryCacheCapabilities, ) -> Option { - effective_cache_payload(MemoryCacheCapabilities { - resident: false, - ..admitted - }) + if admitted.resident { + Some(StagePrefixCachePayload::KvRecurrent) + } else { + effective_cache_payload(admitted) + } } #[cfg(test)] @@ -58,13 +59,15 @@ mod tests { ] { assert_eq!( effective_cache_payload(MemoryCacheCapabilities { + resident_attention: resident, + resident_checkpoint: false, resident, kv_recurrent, full_state, }), expected, ); - let durable = if kv_recurrent { + let durable = if resident || kv_recurrent { Some(StagePrefixCachePayload::KvRecurrent) } else if full_state { Some(StagePrefixCachePayload::FullState) @@ -73,6 +76,8 @@ mod tests { }; assert_eq!( durable_cache_payload(MemoryCacheCapabilities { + resident_attention: resident, + resident_checkpoint: false, resident, kv_recurrent, full_state, diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index a82b1d0992..7854d4203a 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -21,8 +21,9 @@ use super::{ use super::cache_payload::{durable_cache_payload, effective_cache_payload}; -mod durable_spill; +pub(super) mod durable_spill; mod exact_state_limits; +mod resident_policy; use durable_spill::{ DurableRecordTarget, PendingDurableSpill, spill_exact_record_to_l3, start_durable_spill_worker, }; @@ -131,9 +132,9 @@ impl KvStageIntegration { return Ok(None); }; let payload_selection_reason = "loaded_graph_and_memory"; - let dense_without_recurrent = admitted.resident; + let dense_without_recurrent = admitted.resident && !admitted.resident_checkpoint; let l3_manager = manager()?; - if cache_config.l2_max_bytes > 0 && l3_manager.is_none() { + if !admitted.resident && cache_config.l2_max_bytes > 0 && l3_manager.is_none() { let _ = skippy_events::diagnostics::emit( skippy_events::diagnostics::ServingDiagnostic::Warning { message: "Skippy L2 host-RAM cache disabled for this model stage".to_string(), @@ -153,7 +154,7 @@ impl KvStageIntegration { .transpose()?; let l2 = l3 .as_ref() - .filter(|_| cache_config.l2_max_bytes > 0) + .filter(|_| !admitted.resident && cache_config.l2_max_bytes > 0) .and(durable_payload) .map(|payload| { super::l2_serving::StageL2::new( @@ -164,14 +165,21 @@ impl KvStageIntegration { }); // Complete exporters are admitted by the native graph and memory; state // kind only limits retention for larger recurrent snapshots. - if matches!( - model_state_kind, - Some(ModelStateKind::Recurrent | ModelStateKind::Hybrid) - ) { + if !admitted.resident + && matches!( + model_state_kind, + Some(ModelStateKind::Recurrent | ModelStateKind::Hybrid) + ) + { cache_config.max_entries = cache_config.max_entries.min(RECURRENT_CACHE_MAX_ENTRIES); } let mut checkpoint_policy = SparseCheckpointPolicy::from_cache(&cache_config); - let resident_config = ResidentCacheConfig::from_stage(config, &cache_config); + let resident_checkpoint_max_bytes = resident_policy::checkpoint_budget(&cache_config); + let activation_config = ResidentCacheConfig::from_stage(config, &cache_config); + let mut resident_config = activation_config; + if admitted.resident { + resident_config.max_bytes = resident_checkpoint_max_bytes; + } if resident_config.max_entries == 0 { return Ok(None); } @@ -327,6 +335,7 @@ impl KvStageIntegration { exact_state_record_tx, exact_state_record_task, durable_spill_task, + durable_spill_tx, )); Ok(Some(Self { mode, @@ -344,7 +353,7 @@ impl KvStageIntegration { resident_sequences: Arc::new(Mutex::new(ResidentSequencePool::new( resident_config.reserved_seq_count, ))), - activations: Arc::new(Mutex::new(ResidentActivationCache::new(resident_config))), + activations: Arc::new(Mutex::new(ResidentActivationCache::new(activation_config))), radix, exact_blobs, exact_max_entries, @@ -380,6 +389,7 @@ impl KvStageIntegration { cachegen_serving_enabled: worker_cachegen, inflight_fills, dense_without_recurrent, + resident_checkpoint_max_bytes, })) } @@ -392,6 +402,8 @@ impl KvStageIntegration { config, Some(model_state_kind), Some(skippy_runtime::MemoryCacheCapabilities { + resident_checkpoint: false, + resident_attention: model_state_kind == ModelStateKind::Dense, resident: model_state_kind == ModelStateKind::Dense, kv_recurrent: true, full_state: true, @@ -784,6 +796,7 @@ fn store_exact_radix_record_with_codec( // a full disk from flooding the log. let durable_spill = write_through_l3.then_some(PendingDurableSpill { page_id, + native_raw: false, payload, extra, namespace, @@ -965,10 +978,11 @@ fn parse_cache_mode(value: &str) -> Option { #[cfg(test)] mod tests { use super::*; - use skippy_protocol::{FlashAttentionType, LoadMode, StageDevice}; + use skippy_protocol::{FlashAttentionType, LoadMode}; mod cache_admission; mod durable_spill; + mod runtime_admission; fn limits(soft_bytes: u64, hard_bytes: u64) -> ExactStateByteLimits { ExactStateByteLimits { @@ -1171,44 +1185,6 @@ mod tests { let _ = std::fs::remove_dir_all(root); } - #[test] - fn cachegen_selector_enables_only_qualified_metal_layouts() { - let mut config = test_config("future/model"); - config.selected_device = Some(StageDevice { - backend_device: "MTL0".to_string(), - stable_id: None, - index: Some(0), - vram_bytes: None, - }); - config.cache_type_k = "f32".to_string(); - config.cache_type_v = "f16".to_string(); - assert!(cachegen_serving_enabled( - &config, - StageKvCacheCodec::CacheGen - )); - - config.cache_type_k = "f16".to_string(); - assert!(!cachegen_serving_enabled( - &config, - StageKvCacheCodec::CacheGen - )); - config.cache_type_k = "f32".to_string(); - config.selected_device.as_mut().unwrap().backend_device = "CUDA0".to_string(); - assert!(!cachegen_serving_enabled( - &config, - StageKvCacheCodec::CacheGen - )); - config.selected_device = None; - assert!(!cachegen_serving_enabled( - &config, - StageKvCacheCodec::CacheGen - )); - assert!(!cachegen_serving_enabled( - &config, - StageKvCacheCodec::Native - )); - } - #[test] fn exact_payloads_live_on_radix_nodes_and_release_deduped_blocks_on_eviction() { let radix = Mutex::new(UnifiedRadixCache::new()); @@ -1584,194 +1560,6 @@ mod tests { assert!(radix.lookup_recurrent("model", &[1, 2]).is_some()); } - #[test] - fn either_cache_kill_switch_disables_the_cache() { - assert!(!cache_disabled_by_env(None, None)); - assert!(!cache_disabled_by_env(Some("on"), None)); - assert!(cache_disabled_by_env(Some("off"), None)); - assert!(cache_disabled_by_env(None, Some("off"))); - assert!(cache_disabled_by_env(Some("on"), Some("off"))); - assert!(cache_disabled_by_env(Some("off"), Some("on"))); - } - - #[test] - fn injected_manager_is_shared_across_placement_equivalent_stages() { - let root = std::env::temp_dir() - .join("skippy-server-l3-manager-tests") - .join(format!("shared-stages-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); - let first = enabled_auto_config("future/model"); - let second = StageConfig { - stage_id: "replica-stage".to_string(), - stage_index: 7, - topology_id: "other-topology".to_string(), - run_id: "other-run".to_string(), - ..first.clone() - }; - - let first = KvStageIntegration::from_loaded_model_with_l3_manager( - &first, - Some(ModelStateKind::Dense), - Some(skippy_runtime::MemoryCacheCapabilities { - resident: true, - kv_recurrent: true, - full_state: true, - }), - Some(manager.clone()), - None, - ) - .unwrap() - .unwrap(); - let second = KvStageIntegration::from_loaded_model_with_l3_manager( - &second, - Some(ModelStateKind::Dense), - Some(skippy_runtime::MemoryCacheCapabilities { - resident: true, - kv_recurrent: true, - full_state: true, - }), - Some(manager), - None, - ) - .unwrap() - .unwrap(); - let first_l3 = first.l3.as_ref().unwrap(); - let second_l3 = second.l3.as_ref().unwrap(); - - assert!(first_l3.manager().shares_root_with(second_l3.manager())); - assert_eq!(first_l3.state_identity(), second_l3.state_identity()); - assert_eq!(first_l3.model_identity(), second_l3.model_identity()); - assert!(Arc::ptr_eq(&first.inflight_fills, &second.inflight_fills)); - assert!(Arc::ptr_eq( - &first.inflight_records, - &second.inflight_records - )); - assert!(first.try_begin_record("shared-page")); - assert!( - !second.try_begin_record("shared-page"), - "placement replicas performed duplicate record work" - ); - first.finish_record("shared-page"); - assert!(second.try_begin_record("shared-page")); - second.finish_record("shared-page"); - } - - #[test] - fn dense_disk_cache_preserves_resident_fast_path_and_exports_exact_state() { - let root = std::env::temp_dir() - .join("skippy-server-l3-manager-tests") - .join(format!("dense-export-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); - let config = enabled_auto_config("future/model"); - - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - Some(ModelStateKind::Dense), - Some(skippy_runtime::MemoryCacheCapabilities { - resident: true, - kv_recurrent: true, - full_state: true, - }), - Some(manager), - None, - ) - .unwrap() - .expect("dense disk cache should remain enabled"); - - assert_eq!(kv.payload, StagePrefixCachePayload::ResidentKv); - assert_eq!( - kv.durable_payload, - Some(StagePrefixCachePayload::KvRecurrent) - ); - assert_eq!( - kv.exact_state_payload(), - Some(StagePrefixCachePayload::KvRecurrent) - ); - assert!(kv.l3.is_some()); - - let mut invalid = kv; - invalid.payload = StagePrefixCachePayload::Disabled; - invalid.durable_payload = Some(StagePrefixCachePayload::ResidentKv); - assert_eq!(invalid.exact_state_payload(), None); - } - - #[test] - fn cache_ram_budget_enables_stage_l2_with_disk_authority() { - let mut config = enabled_auto_config("future/model"); - config - .kv_cache - .as_mut() - .expect("enabled cache config") - .l2_max_bytes = 64 * 1024 * 1024; - let root = tempfile::tempdir().unwrap(); - let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 30, 0)).unwrap(); - - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - Some(ModelStateKind::Dense), - Some(skippy_runtime::MemoryCacheCapabilities { - resident: true, - kv_recurrent: true, - full_state: true, - }), - Some(manager), - None, - ) - .unwrap() - .expect("prefix cache should remain enabled"); - - assert!(kv.l2.is_some()); - assert!(kv.l3.is_some()); - let attrs = kv.attrs().into_iter().collect::>(); - assert_eq!(attrs["skippy.kv.l2.enabled"], serde_json::json!(true)); - assert_eq!( - attrs["skippy.kv.l2.budget_bytes"], - serde_json::json!(64 * 1024 * 1024u64) - ); - } - - #[test] - fn cache_ram_budget_does_not_create_an_authority_free_l2() { - let mut config = enabled_auto_config("future/model"); - config - .kv_cache - .as_mut() - .expect("enabled cache config") - .l2_max_bytes = 64 * 1024 * 1024; - - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - Some(ModelStateKind::Dense), - Some(skippy_runtime::MemoryCacheCapabilities { - resident: true, - kv_recurrent: true, - full_state: true, - }), - None, - None, - ) - .unwrap() - .expect("L1 prefix cache should remain enabled"); - - assert!(kv.l2.is_none()); - assert!(kv.l3.is_none()); - } - - #[test] - fn parses_cache_mode_aliases() { - assert_eq!( - parse_cache_mode("lookup_record"), - Some(StageKvCacheMode::LookupRecord) - ); - assert_eq!( - parse_cache_mode("exact"), - Some(StageKvCacheMode::LookupRecord) - ); - assert_eq!(parse_cache_mode("off"), Some(StageKvCacheMode::Disabled)); - } - fn test_config(model_id: &str) -> StageConfig { StageConfig { run_id: "test-run".to_string(), diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs index bf1f22448a..371795768e 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs @@ -1,25 +1,26 @@ use super::*; #[derive(Clone, Copy)] -pub(super) struct DurableRecordTarget<'a> { - pub(super) l3: Option<&'a L3Tier>, - pub(super) cachegen_enabled: bool, +pub(in crate::kv_integration) struct DurableRecordTarget<'a> { + pub(in crate::kv_integration) l3: Option<&'a L3Tier>, + pub(in crate::kv_integration) cachegen_enabled: bool, #[cfg(test)] - pub(super) before_l3_spill: Option<&'a dyn Fn()>, + pub(in crate::kv_integration) before_l3_spill: Option<&'a dyn Fn()>, } /// Exact-state payload handed from the serving worker to durable storage. #[derive(Debug)] -pub(super) struct PendingDurableSpill { - pub(super) page_id: String, - pub(super) payload: skippy_cache::ExactStatePayload, - pub(super) extra: super::super::ExactStateExtra, - pub(super) namespace: String, - pub(super) token_ids: Vec, - pub(super) l3_cost: Option, +pub(in crate::kv_integration) struct PendingDurableSpill { + pub(in crate::kv_integration) page_id: String, + pub(in crate::kv_integration) payload: skippy_cache::ExactStatePayload, + pub(in crate::kv_integration) extra: super::super::ExactStateExtra, + pub(in crate::kv_integration) namespace: String, + pub(in crate::kv_integration) token_ids: Vec, + pub(in crate::kv_integration) native_raw: bool, + pub(in crate::kv_integration) l3_cost: Option, } -struct DurableSpillReservation { +pub(in crate::kv_integration) struct DurableSpillReservation { bytes: u64, held_bytes: Arc, } @@ -34,10 +35,11 @@ impl Drop for DurableSpillReservation { struct QueuedDurableSpill { pending: PendingDurableSpill, _reservation: DurableSpillReservation, + _native_claim: Option, } -#[derive(Clone)] -pub(super) struct DurableSpillSender { +#[derive(Debug, Clone)] +pub(in crate::kv_integration) struct DurableSpillSender { tx: std::sync::mpsc::SyncSender, held_bytes: Arc, byte_cap: u64, @@ -52,12 +54,58 @@ impl DurableSpillSender { } } + /// Reserve bounded host bytes before materializing a native cold prefix. + /// Unlike the legacy recorder, native offload never admits an oversized exception. + pub(in crate::kv_integration) fn try_reserve( + &self, + bytes: u64, + ) -> Option { + let mut held = self.held_bytes.load(std::sync::atomic::Ordering::Acquire); + loop { + if bytes > self.byte_cap.saturating_sub(held) { + return None; + } + match self.held_bytes.compare_exchange_weak( + held, + held + bytes, + std::sync::atomic::Ordering::AcqRel, + std::sync::atomic::Ordering::Acquire, + ) { + Ok(_) => { + return Some(DurableSpillReservation { + bytes, + held_bytes: Arc::clone(&self.held_bytes), + }); + } + Err(actual) => held = actual, + } + } + } + + pub(in crate::kv_integration) fn send_reserved( + &self, + pending: PendingDurableSpill, + reservation: DurableSpillReservation, + claim: super::super::resident_offload::NativeOffloadClaim, + ) -> bool { + if pending.payload.byte_len() > reservation.bytes { + return false; + } + self.tx + .try_send(QueuedDurableSpill { + pending, + _reservation: reservation, + _native_claim: Some(claim), + }) + .is_ok() + } + /// Queue one spill without ever blocking the serving worker. /// /// The reservation remains live while the spill is queued and while the /// durable worker is writing it. A single oversized spill is admitted only /// when no other spill bytes are outstanding, matching record admission. - pub(super) fn try_send(&self, pending: PendingDurableSpill) -> bool { + pub(in crate::kv_integration) fn try_send(&self, pending: PendingDurableSpill) -> bool { let bytes = pending.payload.byte_len(); let held = self .held_bytes @@ -69,6 +117,7 @@ impl DurableSpillSender { } let queued = QueuedDurableSpill { pending, + _native_claim: None, _reservation: DurableSpillReservation { bytes, held_bytes: Arc::clone(&self.held_bytes), @@ -84,7 +133,7 @@ type DurableSpillWorker = ( ); /// Starts the optional bounded worker that isolates durable I/O from L1 publication. -pub(super) fn start_durable_spill_worker( +pub(in crate::kv_integration) fn start_durable_spill_worker( l3: Option>, cachegen_enabled: bool, byte_cap: u64, @@ -104,6 +153,7 @@ pub(super) fn start_durable_spill_worker( let QueuedDurableSpill { pending, _reservation, + _native_claim, } = queued; #[cfg(test)] received.fetch_add(1, std::sync::atomic::Ordering::AcqRel); @@ -118,7 +168,7 @@ pub(super) fn start_durable_spill_worker( } /// Persists one exact-state payload without affecting its already-published L1 entry. -pub(super) fn spill_exact_record_to_l3( +pub(in crate::kv_integration) fn spill_exact_record_to_l3( l3: &L3Tier, cachegen_enabled: bool, pending: PendingDurableSpill, @@ -130,6 +180,7 @@ pub(super) fn spill_exact_record_to_l3( namespace, token_ids, l3_cost, + native_raw, } = pending; let kv_desc_json = extra .kv_desc @@ -139,7 +190,7 @@ pub(super) fn spill_exact_record_to_l3( .kv_desc .as_ref() .and_then(|desc| kv_page_geometry(desc, payload.byte_len())); - let cachegen_spill = if cachegen_enabled { + let cachegen_spill = if cachegen_enabled && !native_raw { match (extra.kv_desc.as_ref(), payload.kv_bytes().ok().flatten()) { (Some(desc), Some(kv)) if !kv.is_empty() && cachegen_descriptor_is_qualified(desc) => { match skippy_runtime::encode_cachegen_kv_page(desc, kv.as_ref()) { @@ -216,6 +267,7 @@ mod tests { namespace: "model".to_string(), token_ids: vec![1, 2], l3_cost: None, + native_raw: false, } } @@ -245,3 +297,23 @@ mod tests { assert!(sender.try_send(pending(8))); } } + +#[cfg(test)] +mod native_reservation_tests { + use super::*; + + #[test] + fn native_export_reservation_is_strict_and_released_without_materialization() { + let (tx, _rx) = std::sync::mpsc::sync_channel(2); + let sender = DurableSpillSender::new(tx, 10); + let held = sender.try_reserve(8).unwrap(); + assert!(sender.try_reserve(3).is_none()); + assert!(sender.try_reserve(11).is_none()); + drop(held); + assert!(sender.try_reserve(10).is_some()); + assert_eq!( + sender.held_bytes.load(std::sync::atomic::Ordering::Acquire), + 0 + ); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/resident_policy.rs b/skippy/crates/skippy-serving/src/kv_integration/config/resident_policy.rs new file mode 100644 index 0000000000..09245167bf --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/resident_policy.rs @@ -0,0 +1,42 @@ +//! Native radix prefixes own shared KV references and bounded recurrent host state. +use skippy_protocol::StageKvCacheConfig; + +/// Zero RAM mirrors means use the native checkpoint default, not disable prefix reuse. +/// Disabling the stage cache itself remains the explicit off switch. +const DEFAULT_CHECKPOINT_BYTES: u64 = 1024 * 1024 * 1024; + +pub(super) fn checkpoint_budget(cache: &StageKvCacheConfig) -> u64 { + if cache.l2_max_bytes > 0 { + cache.l2_max_bytes + } else { + DEFAULT_CHECKPOINT_BYTES + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checkpoint_ram_budget_is_independent_of_disk_and_attention_estimates() { + let cache = StageKvCacheConfig { + max_bytes: 32, + exact_max_bytes: Some(64), + l2_max_bytes: 256, + mode: skippy_protocol::StageKvCacheMode::LookupRecord, + max_entries: 64, + codec: Default::default(), + min_tokens: 64, + shared_prefix_stride_tokens: 128, + shared_prefix_record_limit: 2, + }; + assert_eq!(checkpoint_budget(&cache), 256); + assert_eq!( + checkpoint_budget(&StageKvCacheConfig { + l2_max_bytes: 0, + ..cache + }), + DEFAULT_CHECKPOINT_BYTES + ); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/cache_admission.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/cache_admission.rs index 917d670e55..fc7f44db09 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/tests/cache_admission.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/cache_admission.rs @@ -34,6 +34,8 @@ fn loaded_capabilities_select_complete_state_without_configuration_labels() { &config, Some(kind), Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: resident, + resident_checkpoint: false, resident, kv_recurrent, full_state: true, diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs new file mode 100644 index 0000000000..5e6691f462 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs @@ -0,0 +1,243 @@ +//! Loaded memory, cache policy, and durable-tier admission remain independent. +use super::*; +use skippy_protocol::StageDevice; + +#[test] +fn either_cache_kill_switch_disables_the_cache() { + assert!(!cache_disabled_by_env(None, None)); + assert!(!cache_disabled_by_env(Some("on"), None)); + assert!(cache_disabled_by_env(Some("off"), None)); + assert!(cache_disabled_by_env(None, Some("off"))); + assert!(cache_disabled_by_env(Some("on"), Some("off"))); + assert!(cache_disabled_by_env(Some("off"), Some("on"))); +} + +#[test] +fn injected_manager_is_shared_across_placement_equivalent_stages() { + let root = std::env::temp_dir() + .join("skippy-server-l3-manager-tests") + .join(format!("shared-stages-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); + let first = enabled_auto_config("future/model"); + let second = StageConfig { + stage_id: "replica-stage".to_string(), + stage_index: 7, + topology_id: "other-topology".to_string(), + run_id: "other-run".to_string(), + ..first.clone() + }; + + let first = KvStageIntegration::from_loaded_model_with_l3_manager( + &first, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: false, + resident_checkpoint: false, + resident: false, + kv_recurrent: true, + full_state: true, + }), + Some(manager.clone()), + None, + ) + .unwrap() + .unwrap(); + let second = KvStageIntegration::from_loaded_model_with_l3_manager( + &second, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: false, + resident_checkpoint: false, + resident: false, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .unwrap(); + let first_l3 = first.l3.as_ref().unwrap(); + let second_l3 = second.l3.as_ref().unwrap(); + + assert!(first_l3.manager().shares_root_with(second_l3.manager())); + assert_eq!(first_l3.state_identity(), second_l3.state_identity()); + assert_eq!(first_l3.model_identity(), second_l3.model_identity()); + assert!(Arc::ptr_eq(&first.inflight_fills, &second.inflight_fills)); + assert!(Arc::ptr_eq( + &first.inflight_records, + &second.inflight_records + )); + assert!(first.try_begin_record("shared-page")); + assert!( + !second.try_begin_record("shared-page"), + "placement replicas performed duplicate record work" + ); + first.finish_record("shared-page"); + assert!(second.try_begin_record("shared-page")); + second.finish_record("shared-page"); +} + +#[test] +fn native_resident_cache_does_not_materialize_a_duplicate_disk_payload() { + let root = std::env::temp_dir() + .join("skippy-server-l3-manager-tests") + .join(format!("dense-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); + let config = enabled_auto_config("future/model"); + + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, + resident: true, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .expect("dense disk cache should remain enabled"); + + assert_eq!(kv.payload, StagePrefixCachePayload::ResidentKv); + assert_eq!( + kv.durable_payload, + Some(StagePrefixCachePayload::KvRecurrent) + ); + assert_eq!( + kv.exact_state_payload(), + Some(StagePrefixCachePayload::KvRecurrent) + ); + assert!(!kv.payload_is_exact_state()); + assert!(kv.l3.is_some()); + + let mut invalid = kv; + invalid.payload = StagePrefixCachePayload::Disabled; + invalid.durable_payload = Some(StagePrefixCachePayload::ResidentKv); + assert_eq!(invalid.exact_state_payload(), None); +} + +#[test] +fn cache_ram_budget_enables_stage_l2_with_disk_authority() { + let mut config = enabled_auto_config("future/model"); + config + .kv_cache + .as_mut() + .expect("enabled cache config") + .l2_max_bytes = 64 * 1024 * 1024; + let root = tempfile::tempdir().unwrap(); + let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 30, 0)).unwrap(); + + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: false, + resident_checkpoint: false, + resident: false, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .expect("prefix cache should remain enabled"); + + assert!(kv.l2.is_some()); + assert!(kv.l3.is_some()); + let attrs = kv.attrs().into_iter().collect::>(); + assert_eq!(attrs["skippy.kv.l2.enabled"], serde_json::json!(true)); + assert_eq!( + attrs["skippy.kv.l2.budget_bytes"], + serde_json::json!(64 * 1024 * 1024u64) + ); +} + +#[test] +fn native_checkpoint_ram_budget_works_without_disk() { + let mut config = enabled_auto_config("future/model"); + config + .kv_cache + .as_mut() + .expect("enabled cache config") + .l2_max_bytes = 64 * 1024 * 1024; + + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Hybrid), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_checkpoint: true, + resident_attention: true, + resident: true, + kv_recurrent: true, + full_state: true, + }), + None, + None, + ) + .unwrap() + .expect("L1 prefix cache should remain enabled"); + + assert_eq!(kv.resident_checkpoint_max_bytes, 64 * 1024 * 1024); + assert!(kv.resident_requires_checkpoint()); + assert!(!kv.payload_is_exact_state()); + assert!(kv.l2.is_none()); + assert!(kv.l3.is_none()); +} + +#[test] +fn parses_cache_mode_aliases() { + assert_eq!( + parse_cache_mode("lookup_record"), + Some(StageKvCacheMode::LookupRecord) + ); + assert_eq!( + parse_cache_mode("exact"), + Some(StageKvCacheMode::LookupRecord) + ); + assert_eq!(parse_cache_mode("off"), Some(StageKvCacheMode::Disabled)); +} + +#[test] +fn cachegen_selector_enables_only_qualified_metal_layouts() { + let mut config = test_config("future/model"); + config.selected_device = Some(StageDevice { + backend_device: "MTL0".to_string(), + stable_id: None, + index: Some(0), + vram_bytes: None, + }); + config.cache_type_k = "f32".to_string(); + config.cache_type_v = "f16".to_string(); + assert!(cachegen_serving_enabled( + &config, + StageKvCacheCodec::CacheGen + )); + + config.cache_type_k = "f16".to_string(); + assert!(!cachegen_serving_enabled( + &config, + StageKvCacheCodec::CacheGen + )); + config.cache_type_k = "f32".to_string(); + config.selected_device.as_mut().unwrap().backend_device = "CUDA0".to_string(); + assert!(!cachegen_serving_enabled( + &config, + StageKvCacheCodec::CacheGen + )); + config.selected_device = None; + assert!(!cachegen_serving_enabled( + &config, + StageKvCacheCodec::CacheGen + )); + assert!(!cachegen_serving_enabled( + &config, + StageKvCacheCodec::Native + )); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index d54ec525eb..e31a70774e 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -21,10 +21,6 @@ fn l3_fill_claim_key(l3: &skippy_cache::L3Tier, location: &skippy_cache::L3Locat format!("{}:{}", l3.state_identity(), location.manifest_key) } -fn resident_prefix_is_preferred(matched_tokens: usize, exact_tokens: Option) -> bool { - exact_tokens.is_none_or(|exact_tokens| matched_tokens > exact_tokens) -} - fn preflight_l3_kv_location( location: &skippy_cache::L3Location, ) -> Result> { @@ -171,37 +167,6 @@ impl Drop for ExactStateAdmissionCredit { } impl KvStageIntegration { - fn available_exact_prefix_tokens( - &self, - identities: &[PrefillKvIdentity], - shared_durable_fallback: bool, - ) -> Option { - identities - .iter() - .filter_map(|identity| { - let warm = self - .radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .peek_recurrent(&identity.namespace, &identity.token_ids) - .map(|exact| exact.matched_tokens); - if warm.is_some() { - return warm; - } - let l3 = self.l3.as_ref()?; - let durable_token_ids = if shared_durable_fallback { - self.durable_exact_lookup_token_ids(&identity.token_ids) - } else { - &identity.token_ids - }; - l3.locate_longest(&identity.namespace, durable_token_ids, MAX_PREFIX_PROBES) - .ok() - .flatten() - .and_then(|location| usize::try_from(location.token_count).ok()) - }) - .max() - } - pub(crate) fn l3_benefit_cost( &self, cold_prefill_cost: Option, @@ -222,23 +187,14 @@ impl KvStageIntegration { if !self.should_lookup() || self.exact_state_payload().is_none() { return Ok(None); } - // Dense L3 uses serialized exact state only as the durable floor. - // Compare the available serving paths before either mutates the lane: - // prefer warm native resident KV only when it restores a longer prefix, - // while an equal-length warm or durable exact checkpoint retains priority. - if self.payload == StagePrefixCachePayload::ResidentKv { - let resident_tokens = identities + // Persistent storage is the cold floor. A usable native prefix always + // stays on its shared-memory path; a warm hit never reads full KV bytes. + if self.records_resident_prefixes() + && identities .iter() - .filter_map(|identity| self.probe_resident_prefix(identity)) - .map(|resident| resident.token_count) - .max(); - if let Some(resident_tokens) = resident_tokens { - let exact_tokens = - self.available_exact_prefix_tokens(identities, shared_durable_fallback); - if resident_prefix_is_preferred(resident_tokens, exact_tokens) { - return Ok(None); - } - } + .any(|identity| self.probe_resident_prefix(identity).is_some()) + { + return Ok(None); } for identity in identities { let lookup_started = Instant::now(); @@ -536,6 +492,9 @@ impl KvStageIntegration { l3_cost: Option, write_through_l3: bool, ) -> Result> { + if self.records_resident_prefixes() { + return Ok(None); + } let Some(exact_state_payload) = self.exact_state_payload() else { return Ok(None); }; @@ -841,6 +800,9 @@ impl KvStageIntegration { { return Ok(None); } + if !self.native_payload_is_complete(fill.payload.kind()) { + return Ok(None); + } let fill_ms = fill_started.elapsed().as_secs_f64() * 1000.0; let token_count = fill.token_count; let kv_desc: Option = native_kv_desc.or_else(|| { @@ -881,6 +843,13 @@ impl KvStageIntegration { .payload .recurrent_state_bytes() .context("reconstruct L3 recurrent payload")?; + if !self.native_components_are_complete( + kv.as_ref().map_or(0, |bytes| bytes.len() as u64), + recurrent.len() as u64, + kv_desc.is_some(), + ) { + return Ok(None); + } if recurrent.is_empty() && !self.dense_without_recurrent { return Ok(None); } @@ -911,6 +880,13 @@ impl KvStageIntegration { _ => None, }; + if self + .loaded_memory_cache + .is_some_and(|caps| caps.resident && caps.resident_attention) + && kv_page.is_none() + { + return Ok(None); + } if let Some((kv, desc)) = kv_page { let import_started = Instant::now(); if fill.cachegen_kv { @@ -956,7 +932,15 @@ impl KvStageIntegration { // Re-warm the RAM tier off the request path. A drop is fine: the // disk copy stays authoritative. The fill claim rides along so the // worker releases it only once the entry is radix-resident. - if fill.cachegen_kv { + if self.records_resident_prefixes() { + let tokens = &identity.token_ids[..token_count as usize]; + runtime.restore_token_history(session_id, tokens)?; + let mut prefix = identity.clone(); + prefix.token_ids = tokens.to_vec(); + prefix.identity.token_count = token_count; + let _ = self.record_resident_prefix(runtime, session_id, &prefix, tokens); + } + if fill.cachegen_kv || self.records_resident_prefixes() { return Ok(Some(ExactStateRestore { page_id: identity.page_id.clone(), token_count: token_count as usize, @@ -969,7 +953,11 @@ impl KvStageIntegration { lookup_ms, kv_import_ms, recurrent_import_ms, - source: "l3-cachegen", + source: if fill.cachegen_kv { + "l3-cachegen" + } else { + "l3" + }, fill_ms, rewarm_enqueued: false, })); @@ -1093,7 +1081,7 @@ impl From for StagePrefixCachePayload { match kind { skippy_cache::ExactStatePayloadKind::FullState => Self::FullState, skippy_cache::ExactStatePayloadKind::KvRecurrent => Self::KvRecurrent, - skippy_cache::ExactStatePayloadKind::RecurrentOnly => Self::Disabled, + skippy_cache::ExactStatePayloadKind::RecurrentOnly => Self::KvRecurrent, } } } @@ -1119,24 +1107,13 @@ mod tests { use skippy_cache::{L3Location, UnifiedRadixCache}; - use super::{ - is_native_kv_unavailable, preflight_l3_kv_location, resident_prefix_is_preferred, - try_touch_exact_state, - }; + use super::{is_native_kv_unavailable, preflight_l3_kv_location, try_touch_exact_state}; type TestRadix = UnifiedRadixCache< crate::kv_integration::RadixResidentEntry, crate::kv_integration::RadixExactEntry, >; - #[test] - fn longer_resident_prefixes_skip_exact_restore() { - assert!(resident_prefix_is_preferred(4_000, None)); - assert!(resident_prefix_is_preferred(4_001, Some(4_000))); - assert!(!resident_prefix_is_preferred(4_000, Some(4_000))); - assert!(!resident_prefix_is_preferred(200, Some(4_000))); - } - #[test] fn empty_kv_layer_range_is_an_unavailable_optional_kv_component() { let error = anyhow::anyhow!("RuntimeError: no KV cache layers selected by layer range"); diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index b756d66a2a..9119719e3b 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -33,7 +33,10 @@ mod identity; mod l2_serving; pub mod lifecycle; mod output_tokens; +mod record_worker; mod records; +mod resident_offload; +use record_worker::ExactStateRecordWorker; mod resident_prefix; pub use lifecycle::{KvLifecycleEvent, KvLifecycleObserver}; @@ -243,6 +246,7 @@ pub struct KvStageIntegration { /// the position directly instead of importing one. Never true for a /// recurrent family, where an empty snapshot is corruption. pub(crate) dense_without_recurrent: bool, + pub(crate) resident_checkpoint_max_bytes: u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -291,55 +295,6 @@ pub(crate) struct PendingExactStateRecord { pub(crate) admission_credit: crate::kv_integration::exact_state::ExactStateAdmissionCredit, } -#[derive(Debug)] -pub(crate) struct ExactStateRecordWorker { - sender: Mutex>>, - tasks: Mutex>>, -} - -impl ExactStateRecordWorker { - pub(crate) fn new( - sender: SyncSender, - record_task: JoinHandle<()>, - durable_task: Option>, - ) -> Self { - let mut tasks = vec![record_task]; - tasks.extend(durable_task); - Self { - sender: Mutex::new(Some(sender)), - tasks: Mutex::new(tasks), - } - } - - fn with_sender( - &self, - use_sender: impl FnOnce(Option<&SyncSender>) -> T, - ) -> T { - let sender = self - .sender - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - use_sender(sender.as_ref()) - } -} - -impl Drop for ExactStateRecordWorker { - fn drop(&mut self) { - self.sender - .get_mut() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .take(); - for task in self - .tasks - .get_mut() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .drain(..) - { - let _ = task.join(); - } - } -} - #[derive(Debug, Clone)] pub(crate) struct RadixResidentEntry { pub(crate) page_id: String, @@ -675,7 +630,7 @@ impl KvStageIntegration { } pub(crate) fn payload_is_exact_state(&self) -> bool { - self.exact_state_payload().is_some() + self.payload.is_exact_state() } /// Whether the serving tier retains native resident prefixes independently @@ -869,6 +824,17 @@ impl KvStageIntegration { /// checks actual retention after the recorder drains. #[cfg(test)] pub(crate) fn retained_exact_identity(&self, namespace: &str, token_ids: &[i32]) -> bool { + if self.records_resident_prefixes() { + let radix = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + return self + .peek_native_prefix(&radix, namespace, token_ids) + .is_some_and(|matched| { + matched.matched_tokens == token_ids.len() && matched.stored_tokens == token_ids + }); + } match self .radix .lock() @@ -891,6 +857,15 @@ impl KvStageIntegration { namespace: &str, query_tokens: &[i32], ) -> Option { + if self.records_resident_prefixes() { + let radix = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + return self + .peek_native_prefix(&radix, namespace, query_tokens) + .map(|matched| matched.matched_tokens); + } self.radix .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) @@ -1477,7 +1452,7 @@ mod exact_state_record_queue_tests { worker_completed.fetch_add(1, Ordering::Release); } }); - let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None)); + let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None, None)); let (total, best_effort) = budget(); worker.with_sender(|sender| { sender diff --git a/skippy/crates/skippy-serving/src/kv_integration/record_worker.rs b/skippy/crates/skippy-serving/src/kv_integration/record_worker.rs new file mode 100644 index 0000000000..ee175c9d40 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/record_worker.rs @@ -0,0 +1,58 @@ +//! Recorder and durable-spill channel ownership; close both before joining workers. +use super::*; + +#[derive(Debug)] +pub(crate) struct ExactStateRecordWorker { + sender: Mutex>>, + tasks: Mutex>>, + pub(super) durable_sender: Mutex>, +} + +impl ExactStateRecordWorker { + pub(super) fn new( + sender: SyncSender, + record_task: JoinHandle<()>, + durable_task: Option>, + durable_sender: Option, + ) -> Self { + let mut tasks = vec![record_task]; + tasks.extend(durable_task); + Self { + sender: Mutex::new(Some(sender)), + tasks: Mutex::new(tasks), + durable_sender: Mutex::new(durable_sender), + } + } + + pub(super) fn with_sender( + &self, + use_sender: impl FnOnce(Option<&SyncSender>) -> T, + ) -> T { + let sender = self + .sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + use_sender(sender.as_ref()) + } +} + +impl Drop for ExactStateRecordWorker { + fn drop(&mut self) { + self.sender + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.durable_sender + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + for task in self + .tasks + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .drain(..) + { + let _ = task.join(); + } + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs new file mode 100644 index 0000000000..634d44c20f --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -0,0 +1,211 @@ +//! Materialize a native prefix only when releasing it to the persistent tier. +use super::*; +use crate::runtime_state::RuntimeState; +use config::durable_spill::PendingDurableSpill; + +#[derive(Debug)] +pub(super) struct NativeOffloadClaim { + claims: Arc>>, + key: String, +} + +impl NativeOffloadClaim { + fn acquire( + claims: &Arc>>, + namespace: &str, + tokens: &[i32], + ) -> Option { + let key = format!( + "native-offload:{}", + skippy_cache::l3_prefix_key(namespace, tokens) + ); + if !claims + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(key.clone()) + { + return None; + } + Some(Self { + claims: Arc::clone(claims), + key, + }) + } +} + +impl Drop for NativeOffloadClaim { + fn drop(&mut self) { + self.claims + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&self.key); + } +} + +impl KvStageIntegration { + pub(super) fn native_payload_is_complete( + &self, + kind: skippy_cache::ExactStatePayloadKind, + ) -> bool { + if !self.records_resident_prefixes() { + return kind != skippy_cache::ExactStatePayloadKind::RecurrentOnly; + } + self.loaded_memory_cache.is_some_and(|caps| { + if caps.resident_attention { + kind == skippy_cache::ExactStatePayloadKind::KvRecurrent + } else { + caps.resident_checkpoint + && kind == skippy_cache::ExactStatePayloadKind::RecurrentOnly + } + }) + } + + pub(super) fn native_components_are_complete( + &self, + kv_bytes: u64, + recurrent_bytes: u64, + has_descriptor: bool, + ) -> bool { + self.loaded_memory_cache.is_none_or(|caps| { + !caps.resident + || ((!caps.resident_attention || (kv_bytes > 0 && has_descriptor)) + && (!caps.resident_checkpoint || recurrent_bytes > 0)) + }) + } + + pub(super) fn release_native_prefix( + &self, + runtime: &mut RuntimeState, + session: &str, + victim: &skippy_cache::RadixEvictionCandidate, + ) -> Result<()> { + // Disk admission/export is optional. Failure must not prevent reclaiming + // native cells needed by an active request. + if let Err(error) = self.offload_native_prefix(runtime, session, victim) { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::AcqRel) { + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: + "Native prefix cold offload failed; continuing with cache eviction" + .into(), + context: Some(format!("reason={error:#}")), + }, + ); + } + } + runtime.drop_resident_prefix_sequence(session, victim.value.seq_id) + } + + fn offload_native_prefix( + &self, + runtime: &mut RuntimeState, + session: &str, + victim: &skippy_cache::RadixEvictionCandidate, + ) -> Result { + let sender = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let Some(sender) = sender else { + return Ok(false); + }; + let Some(capabilities) = self.loaded_memory_cache else { + return Ok(false); + }; + let Some(l3) = self.l3.as_ref() else { + return Ok(false); + }; + if l3 + .locate_longest(&victim.namespace, &victim.tokens, 1)? + .is_some_and(|entry| entry.token_count == victim.tokens.len() as u64) + { + return Ok(false); + } + let Some(claim) = + NativeOffloadClaim::acquire(&self.inflight_records, &victim.namespace, &victim.tokens) + else { + return Ok(false); + }; + let sequence = victim.value.seq_id; + let tokens = victim.tokens.len() as u64; + let desc = if capabilities.resident_attention { + Some(runtime.resident_kv_page_desc(session, sequence, tokens)?) + } else { + None + }; + let recurrent_bytes = if capabilities.resident_checkpoint { + runtime.resident_recurrent_state_bytes(session, sequence)? + } else { + 0 + }; + let kv_bytes = desc.as_ref().map_or(0, |desc| desc.payload_bytes); + let bytes = kv_bytes + .checked_add(recurrent_bytes as u64) + .ok_or_else(|| anyhow::anyhow!("native offload size overflow"))?; + if bytes == 0 { + return Ok(false); + } + let Some(reservation) = sender.try_reserve(bytes) else { + return Ok(false); + }; + let kv = if let Some(desc) = &desc { + runtime + .export_resident_kv_page( + session, + sequence, + tokens, + usize::try_from(desc.payload_bytes)?, + )? + .payload + } else { + Vec::new() + }; + let recurrent = if recurrent_bytes > 0 { + runtime.export_resident_recurrent_state(session, sequence, recurrent_bytes)? + } else { + Vec::new() + }; + let payload = if capabilities.resident_attention { + ExactStatePayload::kv_recurrent(kv, recurrent) + } else { + anyhow::ensure!( + capabilities.resident_checkpoint && !recurrent.is_empty(), + "resident prefix has no complete export component" + ); + ExactStatePayload::recurrent_only(recurrent) + }; + Ok(sender.send_reserved( + PendingDurableSpill { + page_id: victim.value.page_id.clone(), + payload, + extra: ExactStateExtra { kv_desc: desc }, + namespace: victim.namespace.clone(), + token_ids: victim.tokens.clone(), + l3_cost: None, + native_raw: true, + }, + reservation, + claim, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_offload_claim_is_token_keyed_and_released_on_every_drop() { + let claims = Arc::new(Mutex::new(BTreeSet::new())); + let claim = NativeOffloadClaim::acquire(&claims, "model", &[1, 2]).unwrap(); + assert!(NativeOffloadClaim::acquire(&claims, "model", &[1, 2]).is_none()); + assert!(NativeOffloadClaim::acquire(&claims, "model", &[1, 3]).is_some()); + assert!(NativeOffloadClaim::acquire(&claims, "other", &[1, 2]).is_some()); + drop(claim); + assert!(NativeOffloadClaim::acquire(&claims, "model", &[1, 2]).is_some()); + assert!(claims.lock().unwrap().is_empty()); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs index 3d104c5a55..b79c8bf69e 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -1,3 +1,8 @@ +mod recording; +mod selection; +#[cfg(test)] +use recording::resident_index_over_capacity; + use anyhow::{Context, Result}; use skippy_scheduler::{ CapacityDemand, ComponentCapacitySnapshot, EvictableCacheEntry, plan_component_capacity, @@ -279,10 +284,10 @@ impl KvStageIntegration { }; #[cfg(test)] if !runtime.is_modelless_for_test() { - runtime.drop_resident_prefix_sequence(session_id, victim.value.seq_id)?; + self.release_native_prefix(runtime, session_id, victim)?; } #[cfg(not(test))] - runtime.drop_resident_prefix_sequence(session_id, victim.value.seq_id)?; + self.release_native_prefix(runtime, session_id, victim)?; let removed = radix .evict_resident_candidate(&victim.namespace, &victim.tokens) .with_context(|| { @@ -345,7 +350,9 @@ impl KvStageIntegration { .radix .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - let Some(radix_hit) = radix.peek_resident(&identity.namespace, &identity.token_ids) else { + let Some(radix_hit) = + self.peek_native_prefix(&radix, &identity.namespace, &identity.token_ids) + else { self.notify_kv_lifecycle(KvLifecycleEvent::CacheLookupMiss); return None; }; @@ -394,11 +401,15 @@ impl KvStageIntegration { .radix .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - let eligible = radix - .peek_resident(&identity.namespace, &identity.token_ids) + let eligible = self + .peek_native_prefix(&radix, &identity.namespace, &identity.token_ids) .is_some_and(|hit| self.meets_shared_prefix_min_tokens(hit.matched_tokens)); if eligible { - radix.acquire_resident(&identity.namespace, &identity.token_ids) + if self.resident_requires_checkpoint() { + radix.acquire_resident_checkpoint(&identity.namespace, &identity.token_ids) + } else { + radix.acquire_resident(&identity.namespace, &identity.token_ids) + } } else { None } @@ -461,8 +472,8 @@ impl KvStageIntegration { let mut evicted_entries = 0usize; let mut evicted_tokens = 0u64; while evicted_tokens < target_tokens { - let Some(removed) = evict_one_resident(&mut radix, &mut sequences, |seq_id| { - runtime.drop_resident_prefix_sequence(session_id, seq_id) + let Some(removed) = evict_one_resident(&mut radix, &mut sequences, |victim| { + self.release_native_prefix(runtime, session_id, victim) })? else { break; @@ -520,152 +531,12 @@ impl KvStageIntegration { evicted_tokens: decision.evicted_tokens, }) } - - pub fn record_resident_prefix( - &self, - runtime: &mut RuntimeState, - session_id: &str, - identity: &PrefillKvIdentity, - token_ids: &[i32], - ) -> Result> { - if !self.should_record() || self.payload != StagePrefixCachePayload::ResidentKv { - return Ok(None); - } - let requested_tokens = identity - .identity - .token_count - .try_into() - .unwrap_or(usize::MAX) - .min(token_ids.len()); - if requested_tokens == 0 || (requested_tokens as u64) < self.checkpoint_policy.min_tokens { - return Ok(None); - } - let layer_count = identity - .identity - .layer_end - .saturating_sub(identity.identity.layer_start) - .max(1); - let token_count = - recordable_token_count(self.resident_config, requested_tokens, layer_count); - if token_count == 0 || (token_count as u64) < self.checkpoint_policy.min_tokens { - return Ok(None); - } - let estimated_bytes = resident_estimated_bytes(token_count as u64, layer_count); - let mut evicted_entries = 0usize; - let mut evicted_tokens = 0u64; - let seq_id = { - let mut radix = self - .radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let mut sequences = lock_resident_sequences(&self.resident_sequences); - if let Some(existing) = - radix.resident_exact(&identity.namespace, &identity.token_ids[..token_count]) - { - let stats = radix.stats(); - self.verify_resident_ownership(stats.resident_entries, sequences.stats().0)?; - return Ok(Some(ResidentPrefixRecord { - page_id: existing.value.page_id, - token_count, - seq_id: existing.value.seq_id, - stored: false, - evicted_entries: 0, - evicted_tokens: 0, - entries: stats.resident_entries, - resident_tokens: stats.resident_tokens, - })); - } - - loop { - let stats = radix.stats(); - // `resident_tokens` is a logical sum of every radix checkpoint - // depth. Native sequence snapshots share the underlying KV - // cells, so using that sum as physical occupancy evicts family - // prefixes even when the unified pool still has room. Physical - // capacity is enforced before restore/prefill by - // `admit_resident_capacity`; recording an alias adds no cells. - if !resident_index_over_capacity(self.resident_config, stats, estimated_bytes) { - break; - } - let Some(removed) = evict_one_resident(&mut radix, &mut sequences, |seq_id| { - runtime.drop_resident_prefix_sequence(session_id, seq_id) - })? - else { - return Ok(None); - }; - evicted_entries = evicted_entries.saturating_add(1); - evicted_tokens = evicted_tokens.saturating_add(removed.value.token_count); - } - - sequences.allocate()? - }; - if let Err(error) = runtime.save_resident_prefix(session_id, seq_id, token_count as u64) { - let mut sequences = lock_resident_sequences(&self.resident_sequences); - if let Err(release_error) = sequences.release(seq_id) { - sequences.force_quarantine(seq_id); - return Err(error).with_context(|| { - format!( - "quarantined resident sequence {seq_id} after native save and release failed: {release_error:#}" - ) - }); - } - return Err(error); - } - let mut radix = self - .radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let mut sequences = lock_resident_sequences(&self.resident_sequences); - let inserted = insert_saved_resident( - &mut radix, - &mut sequences, - identity.namespace.clone(), - &identity.token_ids[..token_count], - estimated_bytes, - RadixResidentEntry { - page_id: identity.page_id.clone(), - seq_id, - token_count: token_count as u64, - recompute_cost: (token_count as u64).saturating_mul(u64::from(layer_count)), - }, - |seq_id| runtime.drop_resident_prefix_sequence(session_id, seq_id), - )?; - if !inserted { - let existing = radix - .resident_exact(&identity.namespace, &identity.token_ids[..token_count]) - .context("occupied resident radix entry disappeared after rejected insert")?; - let stats = radix.stats(); - self.verify_resident_ownership(stats.resident_entries, sequences.stats().0)?; - return Ok(Some(ResidentPrefixRecord { - page_id: existing.value.page_id, - token_count, - seq_id: existing.value.seq_id, - stored: false, - evicted_entries, - evicted_tokens, - entries: stats.resident_entries, - resident_tokens: stats.resident_tokens, - })); - } - let stats = radix.stats(); - self.verify_resident_ownership(stats.resident_entries, sequences.stats().0)?; - Ok(Some(ResidentPrefixRecord { - page_id: identity.page_id.clone(), - token_count, - seq_id, - stored: true, - evicted_entries, - evicted_tokens, - entries: stats.resident_entries, - resident_tokens: stats.resident_tokens, - })) - } } fn evict_one_resident( radix: &mut skippy_cache::UnifiedRadixCache, sequences: &mut ResidentSequencePool, - mut drop_native: impl FnMut(i32) -> Result<()>, + mut drop_native: impl FnMut(&skippy_cache::RadixEvictionCandidate) -> Result<()>, ) -> Result>> { let candidates = radix.resident_eviction_candidates(); if candidates.is_empty() { @@ -704,7 +575,7 @@ fn evict_one_resident( .iter() .find(|candidate| candidate.value.seq_id.to_string() == *victim_id) .context("resident capacity planner selected missing victim")?; - drop_native(victim.value.seq_id)?; + drop_native(victim)?; let removed = radix .evict_resident_candidate(&victim.namespace, &victim.tokens) .expect("selected radix resident victim should exist"); @@ -762,51 +633,6 @@ fn insert_saved_resident( } } -fn resident_estimated_bytes(token_count: u64, layer_count: u32) -> u64 { - token_count - .saturating_mul(u64::from(layer_count)) - .saturating_mul(2) -} - -/// Longest prefix this cache may record for a request whose identity covers -/// `requested` tokens. -/// -/// Two bounds keep the pinned cells out of the way of the active lanes, which -/// share one unified `n_ctx` cell pool with the resident cache: the per-entry -/// cell cap (`max_resident_tokens`, `n_ctx - n_ctx/8`) and the per-entry byte -/// budget (`max_bytes`). Treating either as all-or-nothing silently disabled -/// reuse for every prompt above the bound - a prompt one token over the cell cap -/// re-prefilled in full on an identical re-send (mesh-llm#1358). Clamping keeps -/// each bound exactly (pinned cells never exceed it, so the lane reserve is -/// unchanged) and still makes most of an over-long prompt reusable, because -/// restore is a longest-prefix match against the recorded entry. -fn recordable_token_count( - config: skippy_cache::ResidentCacheConfig, - requested: usize, - layer_count: u32, -) -> usize { - let mut allowed = requested; - if config.max_resident_tokens > 0 { - allowed = allowed.min(usize::try_from(config.max_resident_tokens).unwrap_or(usize::MAX)); - } - if config.max_bytes > 0 { - let bytes_per_token = resident_estimated_bytes(1, layer_count).max(1); - allowed = - allowed.min(usize::try_from(config.max_bytes / bytes_per_token).unwrap_or(usize::MAX)); - } - allowed -} - -fn resident_index_over_capacity( - config: skippy_cache::ResidentCacheConfig, - stats: skippy_cache::UnifiedRadixCacheStats, - new_entry_bytes: u64, -) -> bool { - stats.resident_entries.saturating_add(1) > config.max_entries - || (config.max_bytes > 0 - && stats.resident_logical_bytes.saturating_add(new_entry_bytes) > config.max_bytes) -} - #[cfg(test)] mod proactive_eviction_tests { use super::*; @@ -865,6 +691,8 @@ mod proactive_eviction_tests { &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, resident: true, kv_recurrent: true, full_state: true, @@ -993,7 +821,8 @@ mod proactive_eviction_tests { .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |seq_id| { + let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) }) @@ -1080,7 +909,8 @@ mod proactive_eviction_tests { .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |seq_id| { + let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) }) @@ -1219,83 +1049,3 @@ mod proactive_eviction_tests { assert_eq!(sequences.allocate().unwrap(), duplicate_seq_id); } } - -#[cfg(test)] -mod resident_record_cap_tests { - use super::*; - - fn config(max_resident_tokens: u64, max_bytes: u64) -> skippy_cache::ResidentCacheConfig { - skippy_cache::ResidentCacheConfig { - max_entries: 64, - max_bytes, - min_tokens: 1, - reserved_seq_count: 8, - max_resident_tokens, - } - } - - #[test] - fn prompt_above_the_cell_cap_records_the_cap_instead_of_nothing() { - // mesh-llm#1358: n_ctx 28_672 -> cap 25_088. A 25_989-token prompt used - // to be dropped entirely; it must be recorded at the cap. - let ctx: u64 = 28_672; - let cap = ctx - ctx / 8; - assert_eq!(cap, 25_088); - assert_eq!(recordable_token_count(config(cap, 0), 25_989, 42), 25_088); - assert_eq!(recordable_token_count(config(cap, 0), 24_000, 42), 24_000); - } - - #[test] - fn unset_caps_keep_the_requested_prefix() { - assert_eq!(recordable_token_count(config(0, 0), 40_000, 42), 40_000); - } - - #[test] - fn byte_budget_clamps_to_whole_tokens() { - // 42 layers, two bytes per cell per token: 84 bytes/token. - assert_eq!(resident_estimated_bytes(1, 42), 84); - let budget = 84 * 1_000; - let clamped = recordable_token_count(config(0, budget), 40_000, 42); - assert_eq!(clamped, 1_000); - assert!(resident_estimated_bytes(clamped as u64, 42) <= budget); - } - - #[test] - fn byte_budget_below_one_token_records_nothing() { - // Falls to 0 so the caller's min_tokens guard rejects the record - // instead of pinning a zero-length snapshot. - assert_eq!(recordable_token_count(config(0, 1), 40_000, 42), 0); - } - - #[test] - fn clamped_entry_is_found_by_a_longer_request() { - // Restore is a longest-prefix match, so an entry recorded at the cap - // still serves a longer prompt: the identical re-send reuses the cap - // and prefills only the remainder. - let stored: Vec = (0..100).collect(); - let mut radix: skippy_cache::UnifiedRadixCache< - RadixResidentEntry, - crate::kv_integration::RadixExactEntry, - > = skippy_cache::UnifiedRadixCache::new(); - let mut sequences = ResidentSequencePool::new(4); - let seq_id = sequences.allocate().unwrap(); - radix - .insert_resident( - "stage", - &stored, - 100, - RadixResidentEntry { - page_id: "page".to_string(), - seq_id, - token_count: 100, - recompute_cost: 100, - }, - ) - .unwrap(); - let longer: Vec = (0..140).collect(); - let hit = radix - .peek_resident("stage", &longer) - .expect("clamped prefix must still match a longer request"); - assert_eq!(hit.matched_tokens, 100); - } -} diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs new file mode 100644 index 0000000000..b23e3ba6c0 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -0,0 +1,397 @@ +use super::*; + +impl KvStageIntegration { + pub fn record_resident_prefix( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + ) -> Result> { + let Some((token_count, layers)) = + self.resident_capture_boundary(runtime, session_id, identity, token_ids)? + else { + return Ok(None); + }; + let tokens = &identity.token_ids[..token_count]; + let mut radix = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let mut sequences = lock_resident_sequences(&self.resident_sequences); + if let Some(existing) = radix.resident_exact(&identity.namespace, tokens) { + return Ok(Some(resident_record( + existing.value, + false, + radix.stats(), + (0, 0), + ))); + } + let mut evicted = (0_usize, 0_u64); + let seq_id = match sequences.allocate() { + Ok(sequence) => sequence, + Err(error) => { + let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + self.release_native_prefix(runtime, session_id, victim) + })?; + let Some(removed) = removed else { + return Err(error); + }; + evicted.0 += 1; + evicted.1 = evicted.1.saturating_add(removed.value.token_count); + sequences.allocate()? + } + }; + if let Err(error) = runtime.save_resident_prefix(session_id, seq_id, token_count as u64) { + if let Err(release_error) = sequences.release(seq_id) { + sequences.force_quarantine(seq_id); + return Err(error).context(format!( + "quarantined resident sequence {seq_id} after release failed: {release_error:#}" + )); + } + return Err(error); + } + let entry = RadixResidentEntry { + page_id: identity.page_id.clone(), + seq_id, + token_count: token_count as u64, + recompute_cost: (token_count as u64).saturating_mul(u64::from(layers)), + }; + let candidate = skippy_cache::RadixEvictionCandidate { + namespace: identity.namespace.clone(), + tokens: tokens.to_vec(), + logical_bytes: 0, + last_used: 0, + value: entry.clone(), + }; + let bytes = match runtime.resident_prefix_bytes(session_id, seq_id) { + Ok(bytes) => bytes, + Err(error) => { + self.release_unpublished_prefix(runtime, session_id, &mut sequences, &candidate)?; + return Err(error); + } + }; + let room = if bytes > self.resident_checkpoint_max_bytes { + Ok(false) + } else { + make_record_room( + self.resident_config, + &mut radix, + &mut sequences, + bytes, + &mut evicted, + |victim| self.release_native_prefix(runtime, session_id, victim), + ) + }; + if !matches!(room, Ok(true)) { + self.release_unpublished_prefix(runtime, session_id, &mut sequences, &candidate)?; + room?; + return Ok(None); + } + let inserted = insert_saved_resident( + &mut radix, + &mut sequences, + identity.namespace.clone(), + tokens, + bytes, + entry.clone(), + |seq| runtime.drop_resident_prefix_sequence(session_id, seq), + )?; + let entry = if inserted { + entry + } else { + radix + .resident_exact(&identity.namespace, tokens) + .context("occupied resident radix entry disappeared after rejected insert")? + .value + }; + #[cfg(test)] + if inserted { + crate::frontend::capture_trace::log_stored_identity(&identity.namespace, tokens); + } + self.verify_resident_ownership(radix.stats().resident_entries, sequences.stats().0)?; + Ok(Some(resident_record( + entry, + inserted, + radix.stats(), + evicted, + ))) + } + + fn resident_capture_boundary( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + ) -> Result> { + if !self.should_record() || self.payload != StagePrefixCachePayload::ResidentKv { + return Ok(None); + } + let requested = usize::try_from(identity.identity.token_count) + .unwrap_or(usize::MAX) + .min(token_ids.len()); + let layers = identity + .identity + .layer_end + .saturating_sub(identity.identity.layer_start) + .max(1); + let checkpoint = self.resident_requires_checkpoint(); + let count = if checkpoint { + if runtime.canonical_session_position(session_id)? != requested as u64 { + return Ok(None); + } + requested + } else { + recordable_token_count(self.resident_config, requested) + }; + if count == 0 || (count as u64) < self.checkpoint_policy.min_tokens { + return Ok(None); + } + anyhow::ensure!( + identity.token_ids.get(..count) == token_ids.get(..count), + "resident prefix identity does not match the session token path" + ); + Ok(Some((count, layers))) + } +} + +fn resident_record( + entry: RadixResidentEntry, + stored: bool, + stats: skippy_cache::UnifiedRadixCacheStats, + evicted: (usize, u64), +) -> ResidentPrefixRecord { + ResidentPrefixRecord { + page_id: entry.page_id, + token_count: entry.token_count as usize, + seq_id: entry.seq_id, + stored, + evicted_entries: evicted.0, + evicted_tokens: evicted.1, + entries: stats.resident_entries, + resident_tokens: stats.resident_tokens, + } +} + +impl KvStageIntegration { + fn release_unpublished_prefix( + &self, + runtime: &mut RuntimeState, + session: &str, + sequences: &mut ResidentSequencePool, + candidate: &skippy_cache::RadixEvictionCandidate, + ) -> Result<()> { + if let Err(error) = self.release_native_prefix(runtime, session, candidate) { + sequences.quarantine(candidate.value.seq_id)?; + return Err(error); + } + sequences.release(candidate.value.seq_id) + } +} + +fn make_record_room( + config: skippy_cache::ResidentCacheConfig, + radix: &mut skippy_cache::UnifiedRadixCache, + sequences: &mut ResidentSequencePool, + bytes: u64, + evicted: &mut (usize, u64), + mut drop_native: impl FnMut(&skippy_cache::RadixEvictionCandidate) -> Result<()>, +) -> Result { + while resident_index_over_capacity(config, radix.stats(), bytes) { + let Some(removed) = evict_one_resident(radix, sequences, &mut drop_native)? else { + return Ok(false); + }; + evicted.0 = evicted.0.saturating_add(1); + evicted.1 = evicted.1.saturating_add(removed.value.token_count); + } + Ok(true) +} + +/// Dense KV can retain a shorter alias; recurrent checkpoints cannot be sliced. +fn recordable_token_count(config: skippy_cache::ResidentCacheConfig, requested: usize) -> usize { + if config.max_resident_tokens > 0 { + requested.min(usize::try_from(config.max_resident_tokens).unwrap_or(usize::MAX)) + } else { + requested + } +} + +pub(super) fn resident_index_over_capacity( + config: skippy_cache::ResidentCacheConfig, + stats: skippy_cache::UnifiedRadixCacheStats, + new_entry_bytes: u64, +) -> bool { + stats.resident_entries.saturating_add(1) > config.max_entries + || (config.max_bytes > 0 + && stats.resident_logical_bytes.saturating_add(new_entry_bytes) > config.max_bytes) +} + +#[cfg(test)] +mod resident_record_cap_tests { + use super::*; + + fn config(max_resident_tokens: u64, max_bytes: u64) -> skippy_cache::ResidentCacheConfig { + skippy_cache::ResidentCacheConfig { + max_entries: 64, + max_bytes, + min_tokens: 1, + reserved_seq_count: 8, + max_resident_tokens, + } + } + + #[test] + fn prompt_above_the_cell_cap_records_the_cap_instead_of_nothing() { + // mesh-llm#1358: n_ctx 28_672 -> cap 25_088. A 25_989-token prompt used + // to be dropped entirely; it must be recorded at the cap. + let ctx: u64 = 28_672; + let cap = ctx - ctx / 8; + assert_eq!(cap, 25_088); + assert_eq!(recordable_token_count(config(cap, 0), 25_989), 25_088); + assert_eq!(recordable_token_count(config(cap, 0), 24_000), 24_000); + } + + #[test] + fn unset_caps_keep_the_requested_prefix() { + assert_eq!(recordable_token_count(config(0, 0), 40_000), 40_000); + } + + #[test] + fn host_budget_does_not_truncate_dense_token_identity() { + // Host allocations are charged after capture; shared attention cells + // are controlled by measured native pool occupancy. + assert_eq!(recordable_token_count(config(0, 1), 40_000), 40_000); + } + + #[test] + fn clamped_entry_is_found_by_a_longer_request() { + // Restore is a longest-prefix match, so an entry recorded at the cap + // still serves a longer prompt: the identical re-send reuses the cap + // and prefills only the remainder. + let stored: Vec = (0..100).collect(); + let mut radix: skippy_cache::UnifiedRadixCache< + RadixResidentEntry, + crate::kv_integration::RadixExactEntry, + > = skippy_cache::UnifiedRadixCache::new(); + let mut sequences = ResidentSequencePool::new(4); + let seq_id = sequences.allocate().unwrap(); + radix + .insert_resident( + "stage", + &stored, + 100, + RadixResidentEntry { + page_id: "page".to_string(), + seq_id, + token_count: 100, + recompute_cost: 100, + }, + ) + .unwrap(); + let longer: Vec = (0..140).collect(); + let hit = radix + .peek_resident("stage", &longer) + .expect("clamped prefix must still match a longer request"); + assert_eq!(hit.matched_tokens, 100); + } +} + +#[cfg(test)] +mod checkpoint_budget_tests { + use super::*; + + #[test] + fn native_host_bytes_evict_unpinned_owner_without_summing_shared_kv() { + let mut radix = skippy_cache::UnifiedRadixCache::new(); + let mut sequences = ResidentSequencePool::new(4); + let first = sequences.allocate().unwrap(); + let second = sequences.allocate().unwrap(); + for (tokens, seq, bytes) in [(&[1, 2][..], first, 60), (&[1, 2, 3][..], second, 40)] { + radix + .insert_resident( + "model", + tokens, + bytes, + RadixResidentEntry { + page_id: seq.to_string(), + seq_id: seq, + token_count: tokens.len() as u64, + recompute_cost: 1, + }, + ) + .unwrap(); + } + let pin = radix.acquire_resident_checkpoint("model", &[1, 2]).unwrap(); + let config = skippy_cache::ResidentCacheConfig { + max_entries: 8, + max_bytes: 100, + min_tokens: 1, + reserved_seq_count: 4, + max_resident_tokens: 2, + }; + let mut dropped = Vec::new(); + let mut evicted = (0, 0); + assert!( + make_record_room( + config, + &mut radix, + &mut sequences, + 30, + &mut evicted, + |seq| { + dropped.push(seq.value.seq_id); + Ok(()) + } + ) + .unwrap() + ); + assert_eq!(dropped, [second]); + assert_eq!(radix.stats().resident_logical_bytes, 60); + assert!(radix.resident_exact("model", &[1, 2]).is_some()); + assert!(radix.release_resident("model", &pin.stored_tokens)); + } + + #[test] + fn pinned_checkpoint_owners_cannot_be_discarded_to_satisfy_ram_budget() { + let mut radix = skippy_cache::UnifiedRadixCache::new(); + let mut sequences = ResidentSequencePool::new(4); + let seq = sequences.allocate().unwrap(); + radix + .insert_resident( + "model", + &[1, 2], + 90, + RadixResidentEntry { + page_id: "owner".into(), + seq_id: seq, + token_count: 2, + recompute_cost: 1, + }, + ) + .unwrap(); + radix + .acquire_resident_checkpoint("model", &[1, 2, 3]) + .unwrap(); + let config = skippy_cache::ResidentCacheConfig { + max_entries: 8, + max_bytes: 100, + min_tokens: 1, + reserved_seq_count: 4, + max_resident_tokens: 0, + }; + assert!( + !make_record_room( + config, + &mut radix, + &mut sequences, + 30, + &mut (0, 0), + |_| panic!("pinned checkpoint must not be dropped") + ) + .unwrap() + ); + assert_eq!(radix.stats().resident_entries, 1); + assert_eq!(sequences.stats().0, 1); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs new file mode 100644 index 0000000000..1158bfb9e5 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs @@ -0,0 +1,27 @@ +//! Native memory determines whether prefix matches may truncate attention state. +use super::*; +use crate::kv_integration::RadixExactEntry; + +impl KvStageIntegration { + pub(crate) fn retains_recurrent_checkpoints(&self) -> bool { + self.payload_is_exact_state() || self.resident_requires_checkpoint() + } + + pub(crate) fn resident_requires_checkpoint(&self) -> bool { + self.loaded_memory_cache + .is_some_and(|caps| caps.resident_checkpoint) + } + + pub(crate) fn peek_native_prefix( + &self, + radix: &skippy_cache::UnifiedRadixCache, + namespace: &str, + tokens: &[i32], + ) -> Option> { + if self.resident_requires_checkpoint() { + radix.peek_resident_checkpoint(namespace, tokens) + } else { + radix.peek_resident(namespace, tokens) + } + } +} diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index 777db7379a..e90b7c119b 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -23,9 +23,14 @@ pub(crate) use frame_operations::slice_activation_frame; mod lane_lifecycle; pub mod lifecycle; pub mod panic_recovery; +mod resident_prefix; mod restore_transaction; mod state_transfer; +#[cfg(test)] +use context_capacity::lane_count_for_workload; +use context_capacity::{ContextCapacity, effective_lane_count}; + pub use lifecycle::{SessionLifecycleEvent, SessionLifecycleObserver}; #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -44,11 +49,7 @@ pub struct RuntimeState { layer_start: u32, layer_end: u32, lane_count: u32, - /// Size of the context's KV cell pool, in tokens (llama.cpp `n_ctx`). In - /// unified-KV mode every lane draws decode/prefill cells from this single - /// shared pool, so it is the real ceiling for scheduler admission — see - /// [`Self::kv_pool_tokens`]. - ctx_size: u32, + context_capacity: ContextCapacity, /// High-water mark of lane indices ever handed out. Combined with /// [`Self::free_lane_indices`], the count of live lanes equals /// `next_lane_index - free_lane_indices.len()`. @@ -261,7 +262,7 @@ impl RuntimeState { layer_start: 0, layer_end: 1, lane_count, - ctx_size, + context_capacity: ContextCapacity::modelless(ctx_size), next_lane_index: 0, free_lane_indices: Vec::new(), sessions: BTreeMap::new(), @@ -320,16 +321,6 @@ impl RuntimeState { self.sessions.len() } - /// Total KV cell pool available to this context, in tokens (`n_ctx`). - /// - /// In unified-KV mode all lanes share this single pool, so it is the real - /// token budget the iteration scheduler must admit against. Returns 0 for - /// the modelless test runtime, in which case callers should fall back to a - /// configured default. - pub fn kv_pool_tokens(&self) -> u32 { - self.ctx_size - } - #[cfg(test)] pub(crate) fn is_modelless_for_test(&self) -> bool { self.modelless_for_test @@ -412,12 +403,14 @@ fn runtime_from_loaded_model( ) -> Result>> { reject_unsupported_staged_workload(config, &model)?; let lane_count = effective_lane_count(config.lane_count, &model)?; + let context_capacity = + ContextCapacity::for_loaded_model(config.ctx_size, lane_count, model.has_native_model())?; Ok(Arc::new(Mutex::new(RuntimeState { model, layer_start: config.layer_start, layer_end: config.layer_end, lane_count, - ctx_size: config.ctx_size, + context_capacity, next_lane_index: 0, free_lane_indices: Vec::new(), sessions: BTreeMap::new(), @@ -470,38 +463,6 @@ pub fn load_runtime_with_overrides_and_open_events( )?)) } -/// Effective lane-admission bound for a loaded model. -/// -/// Mirrors the native encoder-decoder serialization (skippy/llama_cpp/patches/ -/// 0002-skippy-implement-graph-planning-realization-and-runt.patch: -/// `lane_count = encoder_decoder ? 1 : configured_lane_count`): -/// encoder output is context-global in llama.cpp, so native only ever serves -/// lane 0 for encoder-decoder models. Admission must not assign lane indices -/// that native will never serve. The load-bypass dummy has no native model, -/// so there is no native contract to mirror and the configured value stands. -fn effective_lane_count(configured: u32, model: &StageModel) -> Result { - if !model.has_native_model() { - return Ok(configured); - } - Ok(lane_count_for_workload( - configured, - model.workload_info()?.kind, - )) -} - -/// Pure lane-clamp decision: encoder-decoder work is serialized onto one -/// lane (see [`effective_lane_count`]); every other workload keeps the -/// configured bound. -fn lane_count_for_workload(configured: u32, workload: ModelWorkload) -> u32 { - if configured <= 1 { - return configured; - } - if workload == ModelWorkload::EncoderDecoder { - return 1; - } - configured -} - /// Reject full-model-only workloads before filtered stages can begin serving. pub(crate) fn reject_unsupported_staged_workload( config: &StageConfig, diff --git a/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs b/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs new file mode 100644 index 0000000000..a5a2b2b821 --- /dev/null +++ b/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs @@ -0,0 +1,198 @@ +//! Context limits admitted by the loaded native workload. + +use anyhow::{Context, Result}; +use skippy_runtime::{ModelWorkload, StageModel}; + +use super::RuntimeState; + +#[derive(Clone, Copy)] +pub(super) struct ContextCapacity { + per_lane_tokens: u32, + pool_tokens: u32, +} + +impl ContextCapacity { + /// Mirror `skippy_context_capacity`: native ctx_size is per execution lane. + /// This runs only after model open has admitted the corresponding config. + pub(super) fn for_loaded_model( + configured_tokens: u32, + effective_lanes: u32, + has_native_model: bool, + ) -> Result { + if !has_native_model { + return Ok(Self::modelless(configured_tokens)); + } + let per_lane_tokens = if configured_tokens == 0 { + 512 + } else { + configured_tokens + }; + let pool_tokens = per_lane_tokens + .checked_mul(effective_lanes.max(1)) + .context( + "ctx_size multiplied by admitted lane_count exceeds the native context range", + )?; + Ok(Self { + per_lane_tokens, + pool_tokens, + }) + } + + /// Modelless fixtures supply an aggregate pool directly, without native + /// per-lane allocation or native defaults. + pub(super) const fn modelless(pool_tokens: u32) -> Self { + Self { + per_lane_tokens: pool_tokens, + pool_tokens, + } + } +} + +impl RuntimeState { + /// Aggregate KV cells reserved for all admitted execution lanes (`n_ctx`). + /// Zero denotes unknown capacity in a modelless fixture. + pub fn kv_pool_tokens(&self) -> u32 { + self.context_capacity.pool_tokens + } + + /// Context limit for one request, including its sampling penalty history. + /// Shared KV capacity does not enlarge an individual request's window. + pub fn context_tokens_per_lane(&self) -> u32 { + self.context_capacity.per_lane_tokens + } +} + +/// Encoder output is context-global, so native admits only one execution lane +/// for encoder-decoder workloads. Dummy models have no native contract. +pub(super) fn effective_lane_count(configured: u32, model: &StageModel) -> Result { + if !model.has_native_model() { + return Ok(configured); + } + Ok(lane_count_for_workload( + configured, + model.workload_info()?.kind, + )) +} + +pub(super) fn lane_count_for_workload(configured: u32, workload: ModelWorkload) -> u32 { + if workload == ModelWorkload::EncoderDecoder { + 1 + } else { + configured.max(1) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_pool_includes_every_lane_without_enlarging_request_history() { + let capacity = ContextCapacity::for_loaded_model(131_072, 4, true).unwrap(); + let mut runtime = RuntimeState::new_modelless_for_test(4); + runtime.context_capacity = capacity; + assert_eq!(runtime.kv_pool_tokens(), 524_288); + assert_eq!(runtime.context_tokens_per_lane(), 131_072); + let sampling = skippy_runtime::SamplingConfig { + penalty_last_n: i32::MAX, + dry: skippy_runtime::DrySamplingConfig { + penalty_last_n: i32::MAX, + ..Default::default() + }, + ..Default::default() + } + .with_penalty_windows_within(runtime.context_tokens_per_lane() as usize); + assert_eq!(sampling.penalty_last_n, 131_072); + assert_eq!(sampling.dry.penalty_last_n, 131_072); + } + + #[test] + fn multi_lane_admission_keeps_work_that_fits_the_shared_pool() { + use skippy_protocol::{StageConfig, StageKvCacheConfig, StageKvCacheMode}; + use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; + + let config = StageConfig { + ctx_size: 131_072, + lane_count: 4, + kv_cache: Some(StageKvCacheConfig { + exact_max_bytes: None, + mode: StageKvCacheMode::LookupRecord, + max_entries: 64, + max_bytes: 0, + l2_max_bytes: 0, + codec: skippy_protocol::StageKvCacheCodec::Native, + min_tokens: 1, + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 1, + }), + ..Default::default() + }; + let cache = crate::kv_integration::KvStageIntegration::from_loaded_model( + &config, + Some(ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_attention: true, + resident_checkpoint: false, + kv_recurrent: true, + full_state: true, + }), + None, + ) + .unwrap() + .unwrap(); + let mut runtime = RuntimeState::new_modelless_for_test(4); + runtime.context_capacity = ContextCapacity::for_loaded_model(131_072, 4, true).unwrap(); + let _reservations = (0..4) + .map(|lane| { + cache + .reserve_resident_capacity(&format!("lane-{lane}"), 94_000) + .unwrap() + }) + .collect::>(); + let decision = cache + .admit_resident_capacity(&mut runtime, "next-wave", 94_000, 0, 0, None) + .unwrap(); + assert!(decision.admitted); + assert_eq!(decision.capacity_tokens, 524_288); + assert_eq!(decision.inflight_outstanding_tokens, 376_000); + assert_eq!(decision.evicted_entries, 0); + assert_eq!(decision.projected_free_tokens, 148_288); + + runtime.context_capacity = ContextCapacity::modelless(config.ctx_size); + let understated = cache + .admit_resident_capacity(&mut runtime, "next-wave", 94_000, 0, 0, None) + .unwrap(); + assert!(!understated.admitted); + assert_eq!(understated.admission_deficit_tokens, 244_928); + } + + #[test] + fn native_pool_uses_effective_workload_lanes_and_native_defaults() { + let lanes = lane_count_for_workload(4, ModelWorkload::EncoderDecoder); + let capacity = ContextCapacity::for_loaded_model(2048, lanes, true).unwrap(); + assert_eq!(capacity.pool_tokens, 2048); + assert_eq!(capacity.per_lane_tokens, 2048); + let capacity = ContextCapacity::for_loaded_model(0, 0, true).unwrap(); + assert_eq!(capacity.pool_tokens, 512); + assert_eq!( + lane_count_for_workload(0, ModelWorkload::CausalGeneration), + 1 + ); + } + + #[test] + fn native_pool_rejects_overflow_instead_of_understating_capacity() { + assert!(ContextCapacity::for_loaded_model(u32::MAX, 2, true).is_err()); + } + + #[test] + fn modelless_capacity_remains_the_explicit_aggregate_input() { + for tokens in [0, 131_072] { + let runtime = RuntimeState::new_modelless_with_capacity_for_test(4, tokens); + assert_eq!(runtime.kv_pool_tokens(), tokens); + let capacity = ContextCapacity::for_loaded_model(tokens, 4, false).unwrap(); + assert_eq!(capacity.pool_tokens, tokens); + } + } +} diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 5ee6922473..0b2e2b1c88 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -451,6 +451,11 @@ impl RuntimeState { Ok(()) } + pub fn resident_prefix_bytes(&mut self, session_id: &str, cache_seq_id: i32) -> Result { + self.session(session_id)? + .resident_prefix_bytes(cache_seq_id) + } + pub fn save_resident_prefix( &mut self, session_id: &str, @@ -469,6 +474,7 @@ impl RuntimeState { ) -> Result<()> { let session = self.session(session_id)?; session.restore_prefix(cache_seq_id, token_ids)?; + session.restore_token_history(token_ids)?; self.session_token_counts .insert(session_id.to_string(), token_ids.len() as u64); Ok(()) diff --git a/skippy/crates/skippy-serving/src/runtime_state/resident_prefix.rs b/skippy/crates/skippy-serving/src/runtime_state/resident_prefix.rs new file mode 100644 index 0000000000..c1baa6b394 --- /dev/null +++ b/skippy/crates/skippy-serving/src/runtime_state/resident_prefix.rs @@ -0,0 +1,52 @@ +//! Cold exports read immutable cache owners, never a borrowed execution lane. +use super::*; + +impl RuntimeState { + pub(crate) fn resident_kv_page_desc( + &mut self, + session: &str, + sequence: i32, + tokens: u64, + ) -> Result { + let layers = ( + i32::try_from(self.model_layer_start())?, + i32::try_from(self.model_layer_end())?, + ); + self.session(session)? + .resident_kv_page_desc(sequence, layers, tokens) + } + + pub(crate) fn export_resident_kv_page( + &mut self, + session: &str, + sequence: i32, + tokens: u64, + bytes: usize, + ) -> Result { + let layers = ( + i32::try_from(self.model_layer_start())?, + i32::try_from(self.model_layer_end())?, + ); + self.session(session)? + .export_resident_kv_page(sequence, layers, tokens, bytes) + } + + pub(crate) fn resident_recurrent_state_bytes( + &mut self, + session: &str, + sequence: i32, + ) -> Result { + self.session(session)? + .resident_recurrent_state_bytes(sequence) + } + + pub(crate) fn export_resident_recurrent_state( + &mut self, + session: &str, + sequence: i32, + bytes: usize, + ) -> Result> { + self.session(session)? + .export_resident_recurrent_state(sequence, bytes) + } +} diff --git a/skippy/docs/KV_CACHE_DISK.md b/skippy/docs/KV_CACHE_DISK.md index 91cf8812cd..b29bff0d0b 100644 --- a/skippy/docs/KV_CACHE_DISK.md +++ b/skippy/docs/KV_CACHE_DISK.md @@ -1,5 +1,12 @@ # KV-Cache Disk Tier — Operator Guide +Complete native resident prefix caching uses radix-owned attention references +and recurrent checkpoints. It exports to persistent L3 at cold eviction +boundaries, rather than writing through on every warm cache record. Committed +L3 entries survive model unload and process restart; hot prefixes that have not +been persisted do not. Offload is bounded and best effort, and shutdown does +not flush all resident entries. See [prompt-cache ownership](PROMPT_CACHE.md). + The node-local **disk prompt cache** is the durable tier under Skippy's radix cache: exported continuation (KV) state is cut into content-addressed segments and committed under manifests so a later run can restore an exact prefix from @@ -18,8 +25,16 @@ directory, or a minimum-free reserve below 1 GiB — by returning an error, so a node refuses to start on a broken cache setting rather than silently ignoring it. A *valid* configuration is then **fail-open for inference**: if the store cannot open, reaches low space, or cannot admit a write, the node logs a warning -and serves with cold prefill. Valid runtime unavailability never blocks -generation. +and serves with cold prefill. Runtime unavailability does not turn a cache +miss into an inference failure. + +Cold offload still materializes native attention state synchronously before +queuing background hashing and disk writes. Large or fragmented prefixes can +therefore delay the request that needs eviction, even though disk I/O runs on +a worker. The queue reserves payload bytes before export and has a strict +4 GiB limit; an entry or backlog that cannot fit is skipped. Warm resident +hits avoid this attention export. An L3 restore and an L3 offload have different +costs, so measure them separately when choosing disk-cache settings. ## Modes and safe defaults @@ -67,7 +82,11 @@ Notes: - Directories must be absolute. Relative paths (including bare-drive forms like `C:\cache` on non-Windows hosts) fail closed rather than resolving under the working directory. -- `codec = "native"` is the default. `codec = "cachegen"` is opt-in and only +- Resident-prefix offload writes native components so its reserved byte budget + also bounds payload workspace. Experimental CacheGen encoding remains on the + separate serialized-exporter path. +- `codec = "native"` is the default. On that serialized path, + `codec = "cachegen"` is opt-in and only writes CacheGen archives for explicitly qualified Metal F32/F32, F32/F16, and F16/F32 KV layouts. Every other backend or layout writes native pages. diff --git a/skippy/docs/PROMPT_CACHE.md b/skippy/docs/PROMPT_CACHE.md index 42272ba8db..257bfab922 100644 --- a/skippy/docs/PROMPT_CACHE.md +++ b/skippy/docs/PROMPT_CACHE.md @@ -1,165 +1,105 @@ -# Skippy OpenAI Prompt Cache - -Skippy OpenAI serving has an automatic prompt-prefix cache for normal text -generation. The cache is intended to provide the same operator-facing outcome -as llama-server prompt reuse: repeated prompts, and prompts with a long shared -prefix, avoid recomputing the whole prefix on later requests. - -## llama-server Reference Behavior - -llama-server keeps prompt state in serving slots. With `cache_prompt` enabled, -each request compares its prompt tokens with the selected slot and reuses the -longest common prefix already resident in that slot. With `--cache-ram`, -llama-server can also save idle slot state into a RAM prompt cache and reload -the closest reusable prompt state later. No client cache key is required for -the common case. - -Important llama-server properties: - -- `cache_prompt` controls per-request prompt reuse. -- `--cache-ram N` enables RAM prompt-cache storage. -- idle slots may be saved to the prompt cache and cleared. -- later requests choose reusable state by prompt similarity or cache lookup. -- reported timings include cached versus processed prompt tokens. - -## Skippy Behavior - -Skippy uses the stage KV integration rather than llama-server slots. When a -stage has `kv_cache.mode = "lookup-record"`, Skippy records prompt-prefix -state after prefill and probes that state before later OpenAI chat/completion -requests. A client `prompt_cache_key` is optional; ordinary requests without a -key share the default namespace and can hit automatically. - -Skippy records exact prompt-prefix identities and a small shared-prefix grid. -The exact path covers identical prompts. The shared-prefix path covers prompts -whose common prefix falls on the configured stride, such as a stable system -prompt or tool schema followed by different user tails. This is not arbitrary -llama-server LCP slot selection; it is deterministic prefix identity probing. - -Skippy reports cache state in OpenAI usage and telemetry: - -- `usage.prompt_tokens_details.cached_tokens` is the OpenAI-compatible cached - prompt token count. -- `stage.openai_generation_summary` emits `skippy.kv.status`, one of - `disabled`, `miss`, or `hit`. -- The same summary emits `skippy.kv.cached_prompt_tokens`, - `skippy.kv.matched_prefix_tokens`, `skippy.kv.suffix_prefill_tokens`, and - `skippy.kv.hit_kind`. The hit kind is `none` for disabled or missed cache - lookups. - -## Exact-State Retention - -Recurrent and hybrid families store an exact-state snapshot: the complete -native session state, which is indivisible and includes recurrent and -convolution buffers. The stage byte budget (`prefix_cache.max_bytes`, or -`SKIPPY_KV_CACHE_MAX_BYTES`) is derived from attention KV metadata, so it -systematically undercounts those snapshots and a single snapshot can exceed it. - -The exact catalog therefore treats that budget as a soft cap. It keeps a small -working set of snapshots past the soft cap, so concurrent sessions on one stage -do not evict each other on every request, and it never evicts its last entry, -because a snapshot that self-evicts leaves the stage with no exact prefix reuse -at all. A hard limit bounds that allowance and defaults to a multiple of the -soft cap, but it is not an absolute physical-byte ceiling: the last indivisible -snapshot remains reusable even when it exceeds the limit. Set -`SKIPPY_KV_CACHE_EXACT_MAX_BYTES` to pin the limit in bytes on a worker whose -memory headroom does not match the attention-derived estimate; `0` disables the -limit. Both limits are reported on -`stage.openai_generation_summary` as `skippy.exact_cache.max_bytes` and -`skippy.exact_cache.hard_max_bytes`. - -## Host-RAM L2 Cache - -Set `model_fit.cache_ram_mib` to a positive MiB value to enable the bounded -host-RAM exact-state tier for that model. The default value, `0`, leaves L2 -disabled. Prefix caching and the node-local L3 cache must also be enabled. - -Exact-state lookup proceeds from the in-process radix cache (L1), to host RAM -(L2), then to the node-local disk cache (L3). L3 remains authoritative: the -server locates the current durable manifest before serving an L2 mirror and -requires the mirror digest to match it. The cache worker promotes an L3 fill -on its second hit within ten minutes, or on the first hit for prefixes of at -least 4,096 tokens. Payloads larger than 64 MiB stay out of L2. A verified L2 -hit restores the request immediately and queues the same payload to rewarm L1. -Rewarm records do not rewrite an existing L3 entry. Unloading the stage drops -its L2 tier. - -`stage.openai_generation_summary` reports `skippy.kv.l2.enabled`, budget and -resident byte counts, logical bytes, entries, segments, hits, misses, inserts, -evictions, and admission refusals. Exact-hit telemetry identifies the restore -source as `l2` and includes fill time and whether the L1 rewarm was queued. - -## Durable admission - -After a stage has measured an L3 restore, local OpenAI serving uses that -restore-cost EWMA with the generation service estimator's cold-prefill cost. -New entries remain in L1 probation and reach L3 after two observed reuses. -Admission scores reuse probability and saved prefill time per exclusive and -fractionally shared byte. Under disk pressure, the shared node manager removes -the lowest-benefit inactive manifests first and preserves active pins. Before -the first usable timing sample, or on serving paths without one, the existing -reference-aware LRU write-through remains the safe fallback. - -The L3 activity status reports `benefit_probation`, `benefit_persist`, -`benefit_lru_fallback`, and `benefit_evictions` counters. - -## mesh-llm Defaults - -mesh-llm wires Skippy prefix cache through family policy. For supported model -families, generated `StageConfig` values receive a bounded cache config with -`mode = "lookup-record"` and a production payload such as `resident-kv` or -`kv-recurrent`. This applies to normal mesh-llm embedded Skippy serving without -requiring users to send `prompt_cache_key`. - -The default is conditional, not universal: - -- unsupported or unknown families may leave `kv_cache` unset. -- raw `skippy serve` leaves cache off unless the stage config or - `SKIPPY_KV_CACHE`/`SKIPPY_PREFIX_CACHE` enables it. -- operators can disable cache with `model_fit.prompt_cache = false` or - `model_fit.prefix_cache.enabled = false`. -- recurrent-state families use `kv-recurrent` rather than `resident-kv` when - the family policy requires it. - -## Benchmarking - -Use `just automation-run automation openai-cache-matrix` to compare cold and warm behavior -across native llama-server and Skippy OpenAI endpoints. The native command records four -rows: - -- cold native: llama-server with request cache disabled. -- cold Skippy: Skippy endpoint started with prefix cache disabled. -- warm native: llama-server with request cache enabled. -- warm Skippy: Skippy endpoint started with prefix cache enabled. - -The report is intended to prove cache behavior before comparing timing. Each -row includes a verdict, observed cache statuses, prompt tokens, cacheable -prefix tokens, cached tokens, suffix/uncached prefix tokens, and cache -efficiency. For Skippy OpenAI chat generation, the cacheable prefix excludes -the final current token that drives decode, so `cacheable = prompt_tokens - 1`. - -Example: - -```bash -just automation-run automation openai-cache-matrix \ - --llama-cold-base-url http://127.0.0.1:8081 \ - --llama-warm-base-url http://127.0.0.1:8082 \ - --skippy-cold-base-url http://127.0.0.1:9337/v1 \ - --skippy-warm-base-url http://127.0.0.1:9447/v1 \ - --model Qwen/Qwen3-0.6B:Q4_K_M \ - --output-dir target/skippy-openai-cache-matrix/local -``` - -Start the cold native endpoint with `--cache-ram 0`. Start the warm native -endpoint with `--cache-ram N` or the llama-server default prompt-cache setting. - -The default benchmark pattern is `exact`, so the warmup and measured request -use the same prompt. To exercise Skippy's shared-prefix grid against -llama-server's LCP reuse, add `--pattern shared-prefix`. By default, the command -exits non-zero when either warm row reports zero cached tokens; use -`--allow-missing-warm-cache` only for exploratory timing runs where the endpoint -does not expose cached-token counts. - -The cold Skippy endpoint should use a config with no `kv_cache` or with -`kv_cache.mode = "disabled"`. The warm Skippy endpoint should use mesh-llm -family defaults or an explicit `lookup-record` prefix cache. +# Skippy OpenAI prompt cache + +Skippy reuses exact token prefixes through a radix tree. A cache entry owns its +native continuation state independently of a request or an execution lane. +Recycling a lane releases the request's state; it does not discard cache-owned +prefixes. + +## Shared attention and recurrent checkpoints + +The loaded runtime admits complete cache representations from its graph and +memory capabilities. Serving does not choose a representation by model name. + +For an admitted resident representation: + +- Attention KV remains in the native memory pool. Cache sequence references + share existing cells; retaining a prefix does not export those cells to RAM. +- A hybrid or recurrent prefix also owns an immutable recurrent checkpoint at + a recorded token boundary. Restoring it copies the recurrent component into + an execution lane and shares the corresponding attention cells. +- A request holds a lease while restoring an entry. Eviction cannot remove a + leased source. Divergent continuations cannot mutate the saved checkpoint. +- Dense attention can reuse the common part of a longer stored prefix. + Recurrent state can resume only at a saved checkpoint whose entire token + path is a prefix of the request. A longer recurrent checkpoint cannot be + truncated to an arbitrary common-prefix length. + +This follows SGLang's radix ownership model: token paths identify shared KV +blocks, while recurrent state has separate checkpoint ownership. It is an +adaptation to llama.cpp's native memory interfaces, rather than a dependency +on SGLang's Torch-based runtime. See the pinned upstream +[radix cache](https://github.com/sgl-project/sglang/blob/1f152be6c5e1a36f27f1800762f5e0131f127a41/python/sglang/srt/mem_cache/radix_cache.py) +and [Mamba cache component](https://github.com/sgl-project/sglang/blob/1f152be6c5e1a36f27f1800762f5e0131f127a41/python/sglang/srt/mem_cache/unified_cache/components/mamba.py). + +## Identity and lifetime + +A hit must match the model weights, layer range, runtime state layout, +position rules, namespace, and token prefix. The radix key describes these +inputs; serving does not discover common prefixes by hashing exported KV +payloads. An optional client `prompt_cache_key` separates namespaces. Requests +without a key share the default namespace. + +Run and topology instance IDs do not fragment the namespace. Equivalent +placements can reuse state when the numerical model and state layout match. + +A saved native prefix remains usable after the originating session is freed. +Eviction drops the cache's native attention references and recurrent checkpoint. +The attention pool releases cells once no cache entry or request references +them. Unloading the model releases its retained state. + +## Capacity + +Attention admission uses physical occupancy of the shared native pool. Adding +logical prefix lengths would count shared cells repeatedly and evict reusable +state prematurely. Active restore leases protect their source from eviction. + +Retained attention cells also affect the physical span read by llama.cpp's +attention kernels. Masked idle cells can increase attention work even when a +request gets a cache hit. This ownership change does not port SGLang's paged +attention kernels; benchmark both reuse and attention cost as the retained +working set grows. + +Recurrent checkpoints consume host RAM independently of the attention pool. +Their budget is bounded and does not require a disk cache. An entry that cannot +fit the checkpoint budget is not retained; it cannot remain indefinitely over +budget merely because it is the last entry. Standalone +`--prefix-cache-ram SIZE` or Mesh's `model_fit.cache_ram_mib` supplies this +budget. A zero/unset value selects the bounded 1 GiB native-cache default; +disable prefix caching itself to retain no entries. + +## Persistence boundary + +The resident path does not eagerly export complete KV state into a blob store +or mirror every new prefix to disk. When persistent L3 is enabled, eviction is +the cold offload boundary: serving exports the retained attention cells and +their recurrent checkpoint, then queues a bounded durable write before +releasing native cache ownership. Disk payload integrity remains verified. + +An L3 fill restores the complete state after a resident miss and can warm the +native radix cache again. Completed durable records survive a process restart. +Entries still held only in native memory, and writes interrupted before their +manifest commits, do not. Model unload and shutdown do not promise to flush +every hot prefix. A refused or failed best-effort offload becomes a cache miss +and cold prefill, rather than an inference failure. + +Durable identity includes the native ABI and state layout. Older serialized +entries are not imported into the new runtime; they miss and are recomputed. +No migration of the superseded cache representation is required. + +Portable state export/import also remains available for explicit transfer and +correctness checks. Runtimes without a complete resident representation use +their admitted serialized representation. See [the disk-tier +guide](KV_CACHE_DISK.md) for persistent store controls. + +## Observing reuse + +`usage.prompt_tokens_details.cached_tokens` reports cached input tokens in the +OpenAI response. Generation telemetry also reports cache status, matched prefix +length, suffix-prefill tokens, and hit kind. A match identifies reusable state; +it is not proof that generated tokens are correct. + +Validate cold, repeated, changed-tail, and lane-pressure requests separately. +Use uninterrupted continuations as the correctness reference for restored and +forked state, and compare cache reuse and timings against vanilla llama on the +same model, prompt tokens, output limits, and concurrency. Report actual native +and Rust binary provenance with the results. diff --git a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch index 870fe4cb9a..a988945550 100644 --- a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch +++ b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch @@ -1818,10 +1818,10 @@ index 000000000..7ffe65277 +#endif // SKIPPY_STAGE_PLAN_H diff --git a/include/skippy/state.h b/include/skippy/state.h new file mode 100644 -index 000000000..1cfaaa5c6 +index 000000000..0fe373d78 --- /dev/null +++ b/include/skippy/state.h -@@ -0,0 +1,236 @@ +@@ -0,0 +1,274 @@ +#ifndef SKIPPY_STATE_H +#define SKIPPY_STATE_H + @@ -1841,6 +1841,10 @@ index 000000000..1cfaaa5c6 + SKIPPY_MEMORY_CACHE_RESIDENT = 1 << 0, + SKIPPY_MEMORY_CACHE_KV_RECURRENT = 1 << 1, + SKIPPY_MEMORY_CACHE_FULL_STATE = 1 << 2, ++ /** Resident prefixes restore only their exact saved recurrent checkpoint boundary. */ ++ SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT = 1 << 3, ++ /** Complete resident prefixes contain attention cells in addition to any recurrent state. */ ++ SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION = 1 << 4, +}; + +/** @brief Returns complete cache representations admitted by the built graph and loaded memory. @@ -1960,7 +1964,7 @@ index 000000000..1cfaaa5c6 + size_t * out_bytes, + struct skippy_error ** out_error); + -+/** @brief Exports recurrent state for models that maintain recurrent memory. */ ++/** @brief Exports only recurrent memory; attention pages are exported independently. */ +LLAMA_API enum skippy_status skippy_export_recurrent_state( + struct skippy_session * session, + void * output, @@ -1977,7 +1981,7 @@ index 000000000..1cfaaa5c6 + size_t input_bytes, + struct skippy_error ** out_error); + -+/** @brief Imports recurrent state into a session. */ ++/** @brief Imports recurrent-only state into a session. */ +LLAMA_API enum skippy_status skippy_import_recurrent_state( + struct skippy_session * session, + const void * input, @@ -2026,14 +2030,18 @@ index 000000000..1cfaaa5c6 + size_t record_count, + struct skippy_error ** out_error); + -+/** @brief Saves a session prefix into a resident cache sequence. */ ++/** @brief Retains shared attention cells and an immutable recurrent checkpoint owned by the cache. ++ * Recurrent memory requires token_count equal to the current session position. ++ */ +LLAMA_API enum skippy_status skippy_session_save_prefix( + struct skippy_session * session, + int32_t cache_seq_id, + uint64_t token_count, + struct skippy_error ** out_error); + -+/** @brief Restores a session prefix from a resident cache sequence. */ ++/** @brief Shares retained attention cells and restores a private mutable recurrent row. ++ * Token identity must match; recurrent prefixes require the exact saved boundary. ++ */ +LLAMA_API enum skippy_status skippy_session_restore_prefix( + struct skippy_session * session, + int32_t cache_seq_id, @@ -2041,6 +2049,36 @@ index 000000000..1cfaaa5c6 + size_t token_count, + struct skippy_error ** out_error); + ++/** @brief Exports a cache-owned attention page for cold offload without claiming or restoring an execution lane. */ ++LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ int32_t layer_start, ++ int32_t layer_end, ++ uint64_t token_start, ++ uint64_t token_count, ++ struct skippy_kv_page_desc * out_desc, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error); ++ ++/** @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors. */ ++LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error); ++ ++/** @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool. */ ++LLAMA_API enum skippy_status skippy_session_resident_prefix_bytes( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ uint64_t * out_bytes, ++ struct skippy_error ** out_error); ++ +/** @brief Reports physically occupied cells in the session's unified KV cache. */ +LLAMA_API enum skippy_status skippy_session_memory_used_cells( + struct skippy_session * session, diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 7a8e386451..7eb2a5d724 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -50,20 +50,21 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/model_lifecycle.cpp | 155 +++ src/skippy/model_load_config.cpp | 213 ++++ src/skippy/model_load_config_internal.h | 35 + - src/skippy/model_loading.cpp | 1189 +++++++++++++++++++++++ + src/skippy/model_loading.cpp | 1188 +++++++++++++++++++++++ src/skippy/model_loading_internal.h | 38 + src/skippy/model_package.cpp | 782 +++++++++++++++ src/skippy/model_source.cpp | 463 +++++++++ src/skippy/package_tensor_binding.cpp | 120 +++ src/skippy/package_tensor_binding.h | 27 + src/skippy/rerank_template.h | 36 + + src/skippy/resident_prefix.cpp | 446 +++++++++ src/skippy/runtime_support.h | 47 + - src/skippy/runtime_types.h | 183 ++++ + src/skippy/runtime_types.h | 190 ++++ src/skippy/sampling.cpp | 602 ++++++++++++ src/skippy/sampling_config.cpp | 178 ++++ src/skippy/sampling_internal.h | 67 ++ src/skippy/sampling_vocab.cpp | 74 ++ - src/skippy/session.cpp | 521 ++++++++++ + src/skippy/session.cpp | 501 ++++++++++ src/skippy/speculative_decoding.cpp | 568 +++++++++++ src/skippy/speculative_internal.h | 32 + src/skippy/stage_execution_contract.cpp | 78 ++ @@ -76,7 +77,7 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/state.cpp | 1189 +++++++++++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ - src/skippy/state_memory.cpp | 116 +++ + src/skippy/state_memory.cpp | 115 +++ src/skippy/state_memory.h | 16 + src/skippy/tokenization.cpp | 179 ++++ src/skippy/verification.cpp | 256 +++++ @@ -125,6 +126,7 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs create mode 100644 src/skippy/package_tensor_binding.cpp create mode 100644 src/skippy/package_tensor_binding.h create mode 100644 src/skippy/rerank_template.h + create mode 100644 src/skippy/resident_prefix.cpp create mode 100644 src/skippy/runtime_support.h create mode 100644 src/skippy/runtime_types.h create mode 100644 src/skippy/sampling.cpp @@ -7920,10 +7922,10 @@ index 000000000..554d2bdd3 +skippy_context_capabilities skippy_context_capabilities_of(const llama_model * model); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp new file mode 100644 -index 000000000..60a27669f +index 000000000..b82ec9aca --- /dev/null +++ b/src/skippy/model_loading.cpp -@@ -0,0 +1,1189 @@ +@@ -0,0 +1,1188 @@ +#include "skippy.h" +#include "skippy/errors.h" +#include "skippy/environment.h" @@ -8798,7 +8800,6 @@ index 000000000..60a27669f + + + stage_model->lane_in_use.assign(stage_model->lane_count, false); -+ stage_model->lane_resident_prefix_tokens.resize(stage_model->lane_count); + + const uint64_t native_model_id = reinterpret_cast(stage_model); + if (event_scope != nullptr) { @@ -10615,6 +10616,458 @@ index 000000000..f0c3b2ea7 + } + return rendered; +} +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +new file mode 100644 +index 000000000..1b82ba6ba +--- /dev/null ++++ b/src/skippy/resident_prefix.cpp +@@ -0,0 +1,446 @@ ++#include "skippy/state.h" ++#include "skippy/state_memory.h" ++#include "skippy/errors.h" ++#include "skippy/runtime_support.h" ++#include "skippy/runtime_types.h" ++#include "skippy-verify-checkpoint.h" ++#include "llama-io.h" ++#include "llama-kv-cache.h" ++#include "llama-kv-cache-iswa.h" ++#include "llama-memory-hybrid.h" ++#include "llama-memory-hybrid-iswa.h" ++#include "llama-memory-recurrent.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace { ++ ++// These adapters cover complete memory objects, not model-family names. Never ++// silently drop auxiliary state belonging to an unknown derived memory type. ++llama_memory_t attention_memory(llama_memory_t memory) { ++ if (auto * hybrid = dynamic_cast(memory)) { ++ return hybrid->get_mem_attn(); ++ } ++ if (auto * hybrid = dynamic_cast(memory)) { ++ return hybrid->get_mem_attn(); ++ } ++ return skippy_memory_recurrent_adapter(memory) ? nullptr : memory; ++} ++ ++skippy_status validate_session(skippy_session * session, int32_t cache_seq_id, ++ skippy_error ** error) { ++ if (!session || !session->ctx || !session->stage_model || !session->ctx->get_memory()) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model-backed session is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (cache_seq_id < static_cast(session->stage_model->lane_count * 2) ++ || cache_seq_id >= LLAMA_MAX_SEQ) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id is outside the resident cache range"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * memory = session->ctx->get_memory(); ++ if (!(skippy_model_memory_cache_capabilities(session->stage_model) & SKIPPY_MEMORY_CACHE_RESIDENT) ++ || (attention_memory(memory) && !session->ctx->get_cparams().kv_unified)) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "memory does not support complete shared resident prefixes"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ return SKIPPY_STATUS_OK; ++} ++ ++// A size query never touches tensor bytes. Export writes directly to the ++// caller's allocation, avoiding an extra full recurrent payload temporary. ++class recurrent_buffer_writer final : public llama_io_write_i { ++public: ++ recurrent_buffer_writer(void * data = nullptr, size_t capacity = 0) ++ : data(static_cast(data)), capacity(capacity) {} ++ void write(const void * source, size_t bytes) override { ++ reserve(bytes); ++ if (data && bytes) { std::memcpy(data + position, source, bytes); } ++ position += bytes; ++ } ++ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ reserve(bytes); ++ if (data && bytes) { ggml_backend_tensor_get(tensor, data + position, offset, bytes); } ++ position += bytes; ++ } ++ size_t n_bytes() override { return position; } ++private: ++ void reserve(size_t bytes) const { ++ if (bytes > std::numeric_limits::max() - position ++ || (data && (position > capacity || bytes > capacity - position))) { ++ throw std::runtime_error("recurrent export buffer is too small"); ++ } ++ } ++ uint8_t * data; ++ size_t capacity; ++ size_t position = 0; ++}; ++ ++class checkpoint_writer final : public llama_io_write_i { ++public: ++ void write(const void * source, size_t bytes) override { ++ const auto * data = static_cast(source); ++ if (bytes) { payload.insert(payload.end(), data, data + bytes); } ++ } ++ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ const size_t start = payload.size(); ++ payload.resize(start + bytes); ++ if (bytes) { ggml_backend_tensor_get(tensor, payload.data() + start, offset, bytes); } ++ } ++ size_t n_bytes() override { return payload.size(); } ++ std::vector payload; ++}; ++ ++class checkpoint_reader final : public llama_io_read_i { ++public: ++ explicit checkpoint_reader(const std::vector & payload) : payload(payload.data()), bytes(payload.size()) {} ++ checkpoint_reader(const uint8_t * payload, size_t bytes) : payload(payload), bytes(bytes) {} ++ void read(void * destination, size_t bytes) override { ++ require(bytes); ++ if (bytes) { std::memcpy(destination, payload + position, bytes); } ++ position += bytes; ++ } ++ void read_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ require(bytes); ++ if (bytes) { ggml_backend_tensor_set(tensor, payload + position, offset, bytes); } ++ position += bytes; ++ } ++ size_t n_bytes() override { return position; } ++private: ++ void require(size_t bytes) const { ++ if (bytes > this->bytes - position) { ++ throw std::runtime_error("resident recurrent checkpoint is truncated"); ++ } ++ } ++ const uint8_t * payload; ++ const size_t bytes; ++ size_t position = 0; ++}; ++ ++skippy_status validate_checkpoint(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ if (count > static_cast(std::numeric_limits::max()) || (count && !tokens)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix tokens are invalid"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto found = checkpoints.find(cache_seq_id); ++ if (found == checkpoints.end() || count > found->second.tokens.size() ++ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) ++ && count != found->second.tokens.size()) ++ || (count && !std::equal(tokens, tokens + count, found->second.tokens.begin()))) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix identity or exact recurrent boundary does not match"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * attention = attention_memory(session->ctx->get_memory()); ++ if (attention && count && attention->seq_pos_max(cache_seq_id) < static_cast(count - 1)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident attention prefix is incomplete"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ return SKIPPY_STATUS_OK; ++} ++ ++skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto status = validate_checkpoint(session, cache_seq_id, tokens, count, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ // Allocate history before clearing live state. Checkpoint bytes stay immutable ++ // while each restoring lane receives its own mutable recurrent row. ++ std::vector history; ++ if (count) { history.assign(tokens, tokens + count); } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ auto * memory = session->ctx->get_memory(); ++ if (!memory->seq_rm(session->seq_id, -1, -1)) { ++ throw std::runtime_error("failed to clear execution lane for resident prefix"); ++ } ++ const auto & checkpoint = session->stage_model->resident_prefixes.at(cache_seq_id); ++ try { ++ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { ++ checkpoint_reader reader(checkpoint.recurrent); ++ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (reader.n_bytes() != checkpoint.recurrent.size()) { ++ throw std::runtime_error("resident recurrent checkpoint has trailing data"); ++ } ++ } ++ if (auto * attention = attention_memory(memory)) { ++ if (count) { attention->seq_cp(cache_seq_id, session->seq_id, 0, static_cast(count)); } ++ } ++ } catch (...) { ++ memory->seq_rm(session->seq_id, -1, -1); ++ session->n_past = 0; ++ session->token_history.clear(); ++ throw; ++ } ++ session->n_past = static_cast(count); ++ session->token_history = std::move(history); ++ skippy_mtp_clear_session_state(session); ++ session->verify_checkpoints.clear(); ++ return skippy_success(error); ++} ++ ++skippy_status native_error(skippy_error ** error, const std::exception & exception) { ++ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, exception.what()); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++} ++ ++bool used_attention_cells(llama_memory_t memory, uint64_t * cells) { ++ if (!memory) { *cells = 0; return true; } ++ if (auto * kv = dynamic_cast(memory)) { ++ *cells = kv->get_used_cells(); ++ return true; ++ } ++ if (auto * iswa = dynamic_cast(memory)) { ++ *cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); ++ return true; ++ } ++ return false; ++} ++ ++} // namespace ++ ++extern "C" { ++ ++enum skippy_status skippy_session_save_prefix(skippy_session * session, int32_t cache_seq_id, ++ uint64_t token_count, skippy_error ** error) { ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ if (token_count == 0 || token_count > static_cast(std::max(session->n_past, 0)) ++ || token_count > session->token_history.size() ++ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) ++ && token_count != static_cast(session->n_past))) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident save requires an available exact checkpoint boundary"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto previous = checkpoints.find(cache_seq_id); ++ if (previous != checkpoints.end()) { ++ if (previous->second.tokens.size() == token_count ++ && std::equal(previous->second.tokens.begin(), previous->second.tokens.end(), session->token_history.begin())) { ++ return skippy_success(error); ++ } ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident cache sequence already owns a different prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ skippy_resident_checkpoint checkpoint; ++ checkpoint.tokens.assign(session->token_history.begin(), session->token_history.begin() + token_count); ++ skippy_synchronize_context_if_pending(session->stage_model); ++ auto * memory = session->ctx->get_memory(); ++ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { ++ recurrent_buffer_writer measure; ++ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ checkpoint_writer writer; ++ writer.payload.reserve(measure.n_bytes()); ++ recurrent->state_write(writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ checkpoint.recurrent = std::move(writer.payload); ++ } ++ // Allocate metadata first. On allocation failure during seq_cp, remove ++ // every partially attached attention reference and unpublished map node. ++ auto [entry, inserted] = checkpoints.try_emplace(cache_seq_id); ++ GGML_ASSERT(inserted); ++ auto * attention = attention_memory(memory); ++ try { ++ if (attention) { ++ attention->seq_cp(session->seq_id, cache_seq_id, 0, static_cast(token_count)); ++ } ++ entry->second = std::move(checkpoint); ++ } catch (...) { ++ if (attention) { attention->seq_rm(cache_seq_id, -1, -1); } ++ checkpoints.erase(entry); ++ throw; ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_restore_prefix(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ try { return restore_checkpoint(session, cache_seq_id, tokens, count, error); } ++ catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_create_from_resident_prefix(skippy_model * model, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_session ** output, skippy_error ** error) { ++ if (!model || !model->ctx || !output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and output session are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = nullptr; ++ skippy_session * session = nullptr; ++ auto status = skippy_session_create(model, &session, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ status = skippy_session_restore_prefix(session, cache_seq_id, tokens, count, error); ++ if (status != SKIPPY_STATUS_OK) { ++ skippy_session_free(session, nullptr); ++ return status; ++ } ++ *output = session; ++ return skippy_success(error); ++} ++ ++enum skippy_status skippy_session_drop_sequence(skippy_session * session, int32_t cache_seq_id, ++ skippy_error ** error) { ++ try { ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (auto * attention = attention_memory(session->ctx->get_memory())) { ++ if (!attention->seq_rm(cache_seq_id, -1, -1)) { ++ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident attention prefix"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ } ++ session->stage_model->resident_prefixes.erase(cache_seq_id); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_resident_prefix_bytes(skippy_session * session, int32_t cache_seq_id, ++ uint64_t * output, skippy_error ** error) { ++ try { ++ if (!output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident byte count output is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = 0; ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto found = checkpoints.find(cache_seq_id); ++ if (found != checkpoints.end()) { ++ *output = found->second.recurrent.capacity() + found->second.tokens.capacity() * sizeof(llama_token); ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_memory_used_cells(skippy_session * session, uint64_t * output, ++ skippy_error ** error) { ++ if (!session || !session->ctx || !output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and cell count output are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = 0; ++ if (!used_attention_cells(attention_memory(session->ctx->get_memory()), output)) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "attention occupancy is unavailable for this memory type"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ return skippy_success(error); ++} ++ ++enum skippy_status skippy_export_recurrent_state(skippy_session * session, void * output, ++ size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (!session || !session->ctx || !bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent byte count are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *bytes = 0; ++ try { ++ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); ++ if (!recurrent) { return skippy_success(error); } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ recurrent_buffer_writer measure; ++ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ *bytes = measure.n_bytes(); ++ if (!output || capacity < *bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ recurrent_buffer_writer writer(output, capacity); ++ recurrent->state_write(writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_import_recurrent_state(skippy_session * session, const void * input, ++ size_t bytes, skippy_error ** error) { ++ if (!bytes) { return skippy_success(error); } ++ if (!session || !session->ctx || !input) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent payload are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ try { ++ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); ++ if (!recurrent) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ checkpoint_reader reader(static_cast(input), bytes); ++ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (reader.n_bytes() != bytes) { ++ throw std::runtime_error("recurrent checkpoint has trailing data"); ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session * session, ++ int32_t cache_seq_id, void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (!bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent byte count is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *bytes = 0; ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); ++ if (found == session->stage_model->resident_prefixes.end()) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident checkpoint is unavailable"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto & payload = found->second.recurrent; ++ *bytes = payload.size(); ++ if (payload.empty()) { return skippy_success(error); } ++ if (!output || capacity < payload.size()) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ std::memcpy(output, payload.data(), payload.size()); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_export_resident_kv_page(skippy_session * session, ++ int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, ++ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, ++ void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (bytes) { *bytes = 0; } ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); ++ if (found == session->stage_model->resident_prefixes.end() ++ || token_start > found->second.tokens.size() ++ || token_count > found->second.tokens.size() - token_start) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident KV export exceeds the saved prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ // This stack view neither claims an execution lane nor changes its ++ // state. Only the explicitly requested cold payload is materialized. ++ skippy_session view{}; ++ view.stage_model = session->stage_model; ++ view.ctx = session->ctx; ++ view.seq_id = cache_seq_id; ++ view.n_past = static_cast(found->second.tokens.size()); ++ return skippy_export_kv_page(&view, layer_start, layer_end, token_start, ++ token_count, descriptor, output, capacity, bytes, error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++} // extern "C" diff --git a/src/skippy/runtime_support.h b/src/skippy/runtime_support.h new file mode 100644 index 000000000..d7e991307 @@ -10670,10 +11123,10 @@ index 000000000..d7e991307 + skippy_error ** out_error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h new file mode 100644 -index 000000000..f19a25b76 +index 000000000..38cd35c47 --- /dev/null +++ b/src/skippy/runtime_types.h -@@ -0,0 +1,183 @@ +@@ -0,0 +1,190 @@ +#pragma once + +#include "skippy.h" @@ -10685,6 +11138,7 @@ index 000000000..f19a25b76 +#include +#include +#include ++#include +#include +#include + @@ -10759,6 +11213,13 @@ index 000000000..f19a25b76 + skippy_glm_dsa_hot_tensor hot_tensors[SKIPPY_GLM_DSA_HOT_TENSOR_LIMIT] = {}; +}; + ++// Cache-owned checkpoints outlive execution lanes. Attention remains in the ++// native shared cell pool; only the fixed-size recurrent component is copied. ++struct skippy_resident_checkpoint { ++ std::vector tokens; ++ std::vector recurrent; ++}; ++ +struct skippy_model { + llama_model * model = nullptr; + llama_context * ctx = nullptr; @@ -10786,7 +11247,8 @@ index 000000000..f19a25b76 + uint32_t lane_count = 1; + std::mutex lane_mutex; + std::vector lane_in_use; -+ std::vector> lane_resident_prefix_tokens; ++ std::mutex resident_prefix_mutex; ++ std::map resident_prefixes; + std::mutex chat_templates_mutex; + void * chat_templates = nullptr; + void (*chat_templates_free)(void *) = nullptr; @@ -10812,8 +11274,6 @@ index 000000000..f19a25b76 + int32_t n_past = 0; + bool borrowed_sequence = false; + int32_t borrowed_prefix_tokens = 0; -+ bool preserve_prefix_on_free = false; -+ int32_t preserve_prefix_tokens = 0; + std::vector token_history; + std::vector signal_history; + std::vector prefill_positions; @@ -11804,10 +12264,10 @@ index 000000000..baf83db44 +} diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp new file mode 100644 -index 000000000..f1de95cc5 +index 000000000..be612007f --- /dev/null +++ b/src/skippy/session.cpp -@@ -0,0 +1,521 @@ +@@ -0,0 +1,501 @@ +#include "skippy.h" +#include "skippy/errors.h" +#include "skippy/environment.h" @@ -11957,9 +12417,6 @@ index 000000000..f1de95cc5 + if (skippy_mtp_available(session)) { + skippy_mtp_clear_session_state(session); + } -+ if (static_cast(seq_id) < model->lane_resident_prefix_tokens.size()) { -+ model->lane_resident_prefix_tokens[static_cast(seq_id)].clear(); -+ } + if (llama_memory_t memory = model->ctx->get_memory()) { + if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { + skippy_release_execution_lane(model, seq_id); @@ -12221,24 +12678,7 @@ index 000000000..f1de95cc5 + g_skippy_external_decode_session = nullptr; + } + if (session->ctx != nullptr) { -+ if (session->preserve_prefix_on_free && !session->borrowed_sequence && session->stage_model != nullptr) { -+ skippy_synchronize_context_if_pending(session->stage_model); -+ if (llama_memory_t memory = session->ctx->get_memory()) { -+ llama_memory_seq_rm( -+ memory, -+ session->seq_id, -+ static_cast(session->preserve_prefix_tokens), -+ -1); -+ } -+ } else { -+ skippy_session_reset(session, nullptr); -+ if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { -+ const size_t lane = static_cast(session->seq_id); -+ if (lane < session->stage_model->lane_resident_prefix_tokens.size()) { -+ session->stage_model->lane_resident_prefix_tokens[lane].clear(); -+ } -+ } -+ } ++ skippy_session_reset(session, nullptr); + } + skippy_clear_chat_sampling(session); + if (!session->borrowed_sequence) { @@ -15488,121 +15928,6 @@ index 000000000..f035ea13f + return skippy_success(out_error); +} + -+static llama_memory_recurrent * skippy_get_recurrent_memory( -+ skippy_session * session, -+ skippy_error ** out_error) { -+ if (session == nullptr || session->ctx == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); -+ return nullptr; -+ } -+ -+ llama_memory_t memory = session->ctx->get_memory(); -+ if (memory == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); -+ return nullptr; -+ } -+ -+ return skippy_memory_recurrent_adapter(memory); -+} -+ -+enum skippy_status skippy_export_recurrent_state( -+ struct skippy_session * session, -+ void * output, -+ size_t output_capacity, -+ size_t * out_bytes, -+ struct skippy_error ** out_error) { -+ if (out_bytes == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_bytes is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ *out_bytes = 0; -+ skippy_error * recurrent_error = nullptr; -+ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); -+ if (recurrent_error != nullptr) { -+ if (out_error != nullptr) { -+ *out_error = recurrent_error; -+ } else { -+ skippy_error_free(recurrent_error); -+ } -+ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (recurrent == nullptr) { -+ return skippy_success(out_error); -+ } -+ -+ session->ctx->synchronize(); -+ const size_t bytes = llama_state_seq_get_size_ext( -+ session->ctx, -+ session->seq_id, -+ LLAMA_STATE_SEQ_FLAGS_NONE); -+ *out_bytes = bytes; -+ if (bytes == 0) { -+ return skippy_success(out_error); -+ } -+ if (output == nullptr || output_capacity < bytes) { -+ skippy_set_error(out_error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent state output buffer is too small"); -+ return SKIPPY_STATUS_BUFFER_TOO_SMALL; -+ } -+ -+ const size_t written = llama_state_seq_get_data_ext( -+ session->ctx, -+ static_cast(output), -+ output_capacity, -+ session->seq_id, -+ LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (written != bytes) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to export recurrent state"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ -+ return skippy_success(out_error); -+} -+ -+enum skippy_status skippy_import_recurrent_state( -+ struct skippy_session * session, -+ const void * input, -+ size_t input_bytes, -+ struct skippy_error ** out_error) { -+ if (input_bytes == 0) { -+ return skippy_success(out_error); -+ } -+ if (input == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent state input is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ skippy_error * recurrent_error = nullptr; -+ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); -+ if (recurrent_error != nullptr) { -+ if (out_error != nullptr) { -+ *out_error = recurrent_error; -+ } else { -+ skippy_error_free(recurrent_error); -+ } -+ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (recurrent == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ -+ session->ctx->synchronize(); -+ const size_t read = llama_state_seq_set_data_ext( -+ session->ctx, -+ static_cast(input), -+ input_bytes, -+ session->seq_id, -+ LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (read != input_bytes) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to import recurrent state"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ session->ctx->synchronize(); -+ -+ return skippy_success(out_error); -+} -+ +static llama_kv_cache * skippy_get_kv_cache( + skippy_session * session, + skippy_error ** out_error) { @@ -16066,333 +16391,6 @@ index 000000000..f035ea13f + return skippy_success(out_error); +} + -+static bool skippy_is_reserved_sequence_id( -+ const skippy_session * session, -+ int32_t seq_id) { -+ if (session == nullptr || session->stage_model == nullptr || seq_id < 0) { -+ return true; -+ } -+ const int32_t reserved = static_cast(session->stage_model->lane_count) * 2; -+ return seq_id < reserved; -+} -+ -+static bool skippy_is_reserved_sequence_id_for_model( -+ const skippy_model * model, -+ int32_t seq_id) { -+ if (model == nullptr || seq_id < 0) { -+ return true; -+ } -+ const int32_t reserved = static_cast(model->lane_count) * 2; -+ return seq_id < reserved; -+} -+ -+static enum skippy_status skippy_get_resident_prefix_memory( -+ skippy_session * session, -+ llama_memory_t * out_memory, -+ struct skippy_error ** out_error) { -+ if (session == nullptr || session->ctx == nullptr || out_memory == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ llama_memory_t memory = session->ctx->get_memory(); -+ if (memory == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ -+ skippy_error * recurrent_error = nullptr; -+ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); -+ if (recurrent_error != nullptr) { -+ if (out_error != nullptr) { -+ *out_error = recurrent_error; -+ } else { -+ skippy_error_free(recurrent_error); -+ } -+ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (recurrent != nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "resident prefix cache is not enabled for recurrent memory"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ -+ *out_memory = memory; -+ return SKIPPY_STATUS_OK; -+} -+ -+enum skippy_status skippy_session_save_prefix( -+ struct skippy_session * session, -+ int32_t cache_seq_id, -+ uint64_t token_count, -+ struct skippy_error ** out_error) { -+ if (token_count > static_cast(std::numeric_limits::max())) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (session == nullptr || token_count > static_cast(session->n_past)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cannot save prefix beyond current session position"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ llama_memory_t memory = nullptr; -+ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); -+ if (status != SKIPPY_STATUS_OK) { -+ return status; -+ } -+ -+ skippy_synchronize_context_if_pending(session->stage_model); -+ if (!llama_memory_seq_rm(memory, cache_seq_id, -1, -1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear resident prefix sequence"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (token_count > 0) { -+ llama_memory_seq_cp(memory, session->seq_id, cache_seq_id, 0, static_cast(token_count)); -+ } -+ if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { -+ const size_t lane = static_cast(session->seq_id); -+ if (lane < session->stage_model->lane_resident_prefix_tokens.size() -+ && session->token_history.size() >= static_cast(token_count)) { -+ auto & lane_tokens = session->stage_model->lane_resident_prefix_tokens[lane]; -+ lane_tokens.assign( -+ session->token_history.begin(), -+ session->token_history.begin() + static_cast(token_count)); -+ session->preserve_prefix_on_free = true; -+ session->preserve_prefix_tokens = static_cast(token_count); -+ } -+ } -+ return skippy_success(out_error); -+} -+ -+enum skippy_status skippy_session_restore_prefix( -+ struct skippy_session * session, -+ int32_t cache_seq_id, -+ const llama_token * token_ids, -+ size_t token_count, -+ struct skippy_error ** out_error) { -+ if (token_count > static_cast(std::numeric_limits::max())) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (token_count > 0 && token_ids == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ llama_memory_t memory = nullptr; -+ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); -+ if (status != SKIPPY_STATUS_OK) { -+ return status; -+ } -+ -+ skippy_synchronize_context_if_pending(session->stage_model); -+ if (token_count > 0) { -+ const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); -+ if (max_pos < static_cast(token_count - 1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ } -+ if (!llama_memory_seq_rm(memory, session->seq_id, -1, -1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear execution lane"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (token_count > 0) { -+ llama_memory_seq_cp(memory, cache_seq_id, session->seq_id, 0, static_cast(token_count)); -+ } -+ session->n_past = static_cast(token_count); -+ if (token_count == 0) { -+ session->token_history.clear(); -+ } else { -+ session->token_history.assign(token_ids, token_ids + token_count); -+ } -+ session->signal_history.clear(); -+ skippy_mtp_clear_session_state(session); -+ session->verify_checkpoints.clear(); -+ return skippy_success(out_error); -+} -+ -+enum skippy_status skippy_session_create_from_resident_prefix( -+ struct skippy_model * model, -+ int32_t cache_seq_id, -+ const llama_token * token_ids, -+ size_t token_count, -+ struct skippy_session ** out_session, -+ struct skippy_error ** out_error) { -+ if (model == nullptr || model->model == nullptr || model->ctx == nullptr || out_session == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and out_session are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *out_session = nullptr; -+ if (token_count > static_cast(std::numeric_limits::max()) -+ || token_count > static_cast(std::numeric_limits::max())) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds supported position range"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (token_count > 0 && token_ids == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (skippy_is_reserved_sequence_id_for_model(model, cache_seq_id)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ const int32_t seq_id = skippy_claim_execution_lane(model); -+ if (seq_id < 0) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "no skippy execution lane is available"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ -+ skippy_session temp{}; -+ temp.stage_model = model; -+ temp.ctx = model->ctx; -+ llama_memory_t memory = nullptr; -+ enum skippy_status status = skippy_get_resident_prefix_memory(&temp, &memory, out_error); -+ if (status != SKIPPY_STATUS_OK) { -+ skippy_release_execution_lane(model, seq_id); -+ return status; -+ } -+ -+ skippy_synchronize_context_if_pending(model); -+ if (token_count > 0) { -+ const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); -+ if (max_pos < static_cast(token_count - 1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); -+ skippy_release_execution_lane(model, seq_id); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ } -+ bool lane_prefix_hit = false; -+ const size_t lane = static_cast(seq_id); -+ if (lane < model->lane_resident_prefix_tokens.size()) { -+ const auto & lane_tokens = model->lane_resident_prefix_tokens[lane]; -+ lane_prefix_hit = lane_tokens.size() == token_count -+ && (token_count == 0 || std::equal(lane_tokens.begin(), lane_tokens.end(), token_ids)); -+ } -+ if (!lane_prefix_hit) { -+ if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear borrowed execution lane"); -+ skippy_release_execution_lane(model, seq_id); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ if (token_count > 0) { -+ llama_memory_seq_cp(memory, cache_seq_id, seq_id, 0, static_cast(token_count)); -+ } -+ } -+ if (!llama_memory_seq_rm(memory, seq_id, static_cast(token_count), -1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to trim borrowed execution lane"); -+ skippy_release_execution_lane(model, seq_id); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ -+ skippy_session * session = new skippy_session{}; -+ session->stage_model = model; -+ session->ctx = model->ctx; -+ session->seq_id = seq_id; -+ session->n_past = static_cast(token_count); -+ session->borrowed_sequence = false; -+ session->borrowed_prefix_tokens = 0; -+ if (token_count > 0) { -+ session->token_history.assign(token_ids, token_ids + token_count); -+ } -+ skippy_mtp_clear_session_state(session); -+ *out_session = session; -+ return skippy_success(out_error); -+} -+ -+enum skippy_status skippy_session_drop_sequence( -+ struct skippy_session * session, -+ int32_t seq_id, -+ struct skippy_error ** out_error) { -+ if (skippy_is_reserved_sequence_id(session, seq_id)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "sequence id overlaps execution lanes"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ -+ llama_memory_t memory = nullptr; -+ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); -+ if (status != SKIPPY_STATUS_OK) { -+ return status; -+ } -+ skippy_synchronize_context_if_pending(session->stage_model); -+ if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident prefix sequence"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ return skippy_success(out_error); -+} -+ -+static bool skippy_memory_used_cells(llama_memory_t memory, uint64_t * out_used_cells) { -+ if (auto * cache = dynamic_cast(memory)) { -+ *out_used_cells = cache->get_used_cells(); -+ return true; -+ } -+ if (auto * dsa = dynamic_cast(memory)) { -+ *out_used_cells = std::max(dsa->get_mla()->get_used_cells(), dsa->get_lid()->get_used_cells()); -+ return true; -+ } -+ if (auto * iswa = dynamic_cast(memory)) { -+ *out_used_cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); -+ return true; -+ } -+ if (auto * dsa_iswa = dynamic_cast(memory)) { -+ uint64_t dsa_used_cells = 0; -+ if (!skippy_memory_used_cells(dsa_iswa->get_dsa(), &dsa_used_cells)) { -+ return false; -+ } -+ *out_used_cells = std::max(dsa_used_cells, dsa_iswa->get_swa()->get_used_cells()); -+ return true; -+ } -+ if (auto * msa = dynamic_cast(memory)) { -+ *out_used_cells = std::max(msa->get_base()->get_used_cells(), msa->get_idx()->get_used_cells()); -+ return true; -+ } -+ if (auto * dsv4 = dynamic_cast(memory)) { -+ uint64_t raw_used_cells = 0; -+ if (!skippy_memory_used_cells(dsv4->get_raw(), &raw_used_cells)) { -+ return false; -+ } -+ *out_used_cells = std::max({ -+ raw_used_cells, -+ dsv4->get_csa()->get_used_cells(), -+ dsv4->get_hca()->get_used_cells(), -+ dsv4->get_lid()->get_used_cells(), -+ }); -+ return true; -+ } -+ return false; -+} -+ -+enum skippy_status skippy_session_memory_used_cells( -+ struct skippy_session * session, -+ uint64_t * out_used_cells, -+ struct skippy_error ** out_error) { -+ if (out_used_cells == nullptr) { -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_used_cells is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *out_used_cells = 0; -+ -+ llama_memory_t memory = nullptr; -+ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); -+ if (status != SKIPPY_STATUS_OK) { -+ return status; -+ } -+ if (!skippy_memory_used_cells(memory, out_used_cells)) { -+ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "physical occupancy is unavailable for this memory type"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ return skippy_success(out_error); -+} -+ +} // extern "C" diff --git a/src/skippy/state_effects.cpp b/src/skippy/state_effects.cpp new file mode 100644 @@ -16932,10 +16930,10 @@ index 000000000..5bb6b779b + std::string & error); diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp new file mode 100644 -index 000000000..e271852ff +index 000000000..2d7b1a2ae --- /dev/null +++ b/src/skippy/state_memory.cpp -@@ -0,0 +1,116 @@ +@@ -0,0 +1,115 @@ +#include "skippy/state_memory.h" +#include "skippy/state.h" +#include "skippy/runtime_types.h" @@ -16994,16 +16992,16 @@ index 000000000..e271852ff + // coverage merely from a successful dynamic_cast or a nonempty export. + const auto & type = typeid(*memory); + if (type == typeid(llama_kv_cache) || type == typeid(llama_kv_cache_iswa)) { -+ return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; ++ return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_recurrent)) { + return skippy_memory_recurrent_adapter(memory) -+ ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_hybrid) || type == typeid(llama_memory_hybrid_iswa)) { + return skippy_memory_recurrent_adapter(memory) && + (skippy_memory_kv_adapter(memory) || skippy_memory_iswa_adapter(memory)) -+ ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + // DSA/MSA memories include an indexer tier. Until a real-model resident + // save/restore proves that tier survives, use complete state snapshots. @@ -17027,7 +17025,7 @@ index 000000000..e271852ff + } + // A phase with no persistent effects adds no cache restrictions. It must + // not be confused with failed graph admission or unexported context state. -+ uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | ++ uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | + SKIPPY_MEMORY_CACHE_FULL_STATE; + for (const auto & effect : effects) { + switch (effect.kind) { @@ -17036,7 +17034,6 @@ index 000000000..e271852ff + break; + case skippy_state_kind::recurrent_conv: + case skippy_state_kind::recurrent_ssm: -+ supported &= ~SKIPPY_MEMORY_CACHE_RESIDENT; + break; + case skippy_state_kind::derived_persistent: + supported &= SKIPPY_MEMORY_CACHE_FULL_STATE; diff --git a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch index 34e9e0a62d..4908abdb81 100644 --- a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch +++ b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch @@ -3410,7 +3410,7 @@ index 426c48741..0a5980aaa 100644 # # libraries -@@ -47,6 +48,50 @@ set(LLAMA_CORE_SOURCES +@@ -47,6 +48,51 @@ set(LLAMA_CORE_SOURCES add_library(llama ../include/llama.h ${LLAMA_CORE_SOURCES} @@ -3453,6 +3453,7 @@ index 426c48741..0a5980aaa 100644 + skippy/stage_realization.cpp + skippy/stage_execution_contract.cpp + skippy/state.cpp ++ skippy/resident_prefix.cpp + skippy/state_memory.cpp + skippy/state_effects.cpp + skippy/speculative_decoding.cpp @@ -3771,12 +3772,14 @@ index 426c48741..0a5980aaa 100644 + set_tests_properties(skippy_generate_gemma_fixture PROPERTIES + FIXTURES_SETUP skippy-model-loader-fixtures) + -+ add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) ++ add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) + target_include_directories(skippy-sampling-history PRIVATE .) + target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) + target_link_libraries(skippy-sampling-history PRIVATE llama) ++ add_test(NAME skippy_resident_checkpoint_gpu_long COMMAND skippy-sampling-history resident-gpu-long) ++ set_tests_properties(skippy_resident_checkpoint_gpu_long PROPERTIES SKIP_RETURN_CODE 77) + function(add_skippy_sampling_history_tests family fixture state) -+ foreach(mode grammar penalty) ++ foreach(mode grammar penalty resident) + add_test(NAME skippy_sampling_history_${family}_${mode} + COMMAND skippy-sampling-history + "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 055f77523b..25c7342fc2 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -54,6 +54,7 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts create mode 100644 src/skippy/tests/noalloc_graph_planning.cpp create mode 100644 src/skippy/tests/profile_residency.cpp create mode 100644 src/skippy/tests/renamed_multishard_planning.cpp + create mode 100644 src/skippy/tests/resident_checkpoint_gpu.cpp create mode 100644 src/skippy/tests/residual_checkpoint_regression.h create mode 100644 src/skippy/tests/runtime_events.cpp create mode 100644 src/skippy/tests/sampling_history.cpp @@ -5153,6 +5154,299 @@ index 000000000..0832b018e + llama_backend_free(); + return result; +} +diff --git a/src/skippy/tests/resident_checkpoint_gpu.cpp b/src/skippy/tests/resident_checkpoint_gpu.cpp +new file mode 100644 +index 000000000..691e92c37 +--- /dev/null ++++ b/src/skippy/tests/resident_checkpoint_gpu.cpp +@@ -0,0 +1,287 @@ ++// Opt-in real-model GPU proof: separate checkpoint ownership from HTTP scheduling. ++#include "skippy.h" ++#include "../runtime_types.h" ++#include "llama-model.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); ++ ++namespace { ++constexpr size_t lanes = 4; ++constexpr size_t suffix_steps = 32; ++constexpr size_t pressure_tokens = 4096; ++using Sessions = std::array; ++using Prefixes = std::array, lanes>; ++ ++#define REQUIRE(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "long GPU checkpoint failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++void ok(skippy_status status, skippy_error * error) { ++ if (status != SKIPPY_STATUS_OK) { ++ std::fprintf(stderr, "long GPU native error: %s\n", error ? error->message : "no detail"); ++ std::exit(1); ++ } ++ skippy_error_free(error); ++} ++ ++size_t prefix_tokens() { ++ const char * value = std::getenv("SKIPPY_NATIVE_TEST_PREFIX_TOKENS"); ++ if (!value) { return 23497; } ++ REQUIRE(*value && std::strspn(value, "0123456789") == std::strlen(value)); ++ const unsigned long count = std::strtoul(value, nullptr, 10); ++ REQUIRE(count >= 128 && count <= 65536); ++ return static_cast(count); ++} ++ ++Sessions create(skippy_model * model) { ++ Sessions sessions{}; ++ for (auto & session : sessions) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_create(model, &session, &error); ++ ok(status, error); ++ } ++ return sessions; ++} ++ ++void release(Sessions & sessions) { ++ for (auto & session : sessions) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_free(session, &error); ++ ok(status, error); ++ session = nullptr; ++ } ++} ++ ++void prefill(Sessions & sessions, const Prefixes & prefixes) { ++ // Identical explicit chunk and lane order in every cold reference arm. ++ for (size_t offset = 0; offset < prefixes[0].size(); offset += 512) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ const size_t count = std::min(512, prefixes[lane].size() - offset); ++ skippy_error * error = nullptr; ++ size_t bytes = 0; ++ const auto status = skippy_prefill_chunk(sessions[lane], prefixes[lane].data() + offset, ++ count, nullptr, 0, nullptr, 0, &bytes, &error); ++ ok(status, error); ++ } ++ } ++} ++ ++Prefixes tokens(size_t count, int32_t vocab_size, int32_t salt) { ++ REQUIRE(vocab_size > 64); ++ const int32_t span = std::min(vocab_size - 32, 4096); ++ Prefixes prefixes; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ prefixes[lane].reserve(count); ++ for (size_t i = 0; i < count; ++i) { ++ prefixes[lane].push_back(32 + static_cast((i * 17 + lane * 101 + salt) % span)); ++ } ++ } ++ return prefixes; ++} ++ ++struct Components { ++ std::vector kv; ++ std::vector recurrent; ++}; ++ ++Components components(skippy_session * session) { ++ const int32_t layers = static_cast(session->stage_model->model->hparams.n_layer()); ++ skippy_kv_page_desc desc{}; ++ size_t bytes = 0; ++ skippy_error * error = nullptr; ++ auto status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &desc, nullptr, 0, &bytes, &error); ++ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); ++ skippy_error_free(error); ++ Components result; ++ result.kv.resize(bytes); ++ error = nullptr; ++ status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &desc, result.kv.data(), result.kv.size(), &bytes, &error); ++ ok(status, error); ++ result.kv.resize(bytes); ++ error = nullptr; ++ status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); ++ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); ++ skippy_error_free(error); ++ result.recurrent.resize(bytes); ++ error = nullptr; ++ status = skippy_export_recurrent_state(session, result.recurrent.data(), ++ result.recurrent.size(), &bytes, &error); ++ ok(status, error); ++ result.recurrent.resize(bytes); ++ return result; ++} ++ ++struct DecodeRows { ++ std::array greedy; ++ std::array, lanes> logits; ++}; ++ ++using DecodeTrace = std::vector; ++ ++DecodeTrace decode_fixed_suffix(Sessions & sessions, int32_t vocab_size) { ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.repeat_penalty = 1.0f; ++ sampling.temperature = 0; ++ sampling.top_k = 1; ++ sampling.reasoning_budget_tokens = -1; ++ DecodeTrace trace; ++ trace.reserve(suffix_steps); ++ for (size_t step = 0; step < suffix_steps; ++step) { ++ std::array input{}; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ input[lane] = 32 + static_cast((step * 11 + lane * 37) % (vocab_size - 32)); ++ } ++ DecodeRows rows; ++ skippy_error * error = nullptr; ++ std::array requests{}; ++ std::array sampled_indexes{}; ++ size_t sampled_count = 0; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ requests[lane].session = sessions[lane]; ++ requests[lane].token_ids = &input[lane]; ++ requests[lane].token_count = 1; ++ requests[lane].sampling = &sampling; ++ requests[lane].sample_last = true; ++ } ++ const auto status = skippy_iteration_batch_sampled(requests.data(), requests.size(), ++ nullptr, nullptr, nullptr, nullptr, sampled_indexes.data(), rows.greedy.data(), ++ rows.greedy.size(), &sampled_count, &error); ++ ok(status, error); ++ REQUIRE(sampled_count == lanes); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ REQUIRE(sampled_indexes[lane] == lane); ++ const float * logits = llama_get_logits_ith(sessions[lane]->ctx, static_cast(lane)); ++ REQUIRE(logits != nullptr); ++ rows.logits[lane].assign(logits, logits + vocab_size); ++ REQUIRE(std::all_of(rows.logits[lane].begin(), rows.logits[lane].end(), ++ [](float value) { return std::isfinite(value); })); ++ } ++ trace.push_back(std::move(rows)); ++ } ++ return trace; ++} ++ ++bool compare(const char * arm, const DecodeTrace & reference, const DecodeTrace & actual) { ++ REQUIRE(reference.size() == actual.size()); ++ float max_delta = 0; ++ size_t mismatched_greedy = 0; ++ for (size_t step = 0; step < reference.size(); ++step) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ mismatched_greedy += reference[step].greedy[lane] != actual[step].greedy[lane]; ++ REQUIRE(reference[step].logits[lane].size() == actual[step].logits[lane].size()); ++ for (size_t token = 0; token < reference[step].logits[lane].size(); ++token) { ++ max_delta = std::max(max_delta, ++ std::fabs(reference[step].logits[lane][token] - actual[step].logits[lane][token])); ++ } ++ } ++ } ++ std::fprintf(stderr, "%s: batch=4 steps=%zu max_logit_delta=%.9g greedy_mismatches=%zu\n", ++ arm, reference.size(), max_delta, mismatched_greedy); ++ return max_delta <= 1e-6f && mismatched_greedy == 0; ++} ++ ++void save(Sessions & sessions, size_t count) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_save_prefix(sessions[lane], static_cast(8 + lane), count, &error); ++ ok(status, error); ++ } ++} ++ ++Sessions restore(skippy_model * model, const Prefixes & prefixes) { ++ Sessions sessions{}; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_create_from_resident_prefix(model, static_cast(8 + lane), ++ prefixes[lane].data(), prefixes[lane].size(), &sessions[lane], &error); ++ ok(status, error); ++ } ++ return sessions; ++} ++ ++void require_gpu_weights(skippy_model * model) { ++ REQUIRE(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), ++ [](const auto & item) { ++ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } ++ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( ++ ggml_backend_buffer_get_type(item.second->buffer))); ++ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; ++ })); ++} ++ ++} // namespace ++ ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config) { ++ REQUIRE(model_path && *model_path && config.n_gpu_layers > 0); ++ const size_t count = prefix_tokens(); ++ config.ctx_size = static_cast(count + pressure_tokens + suffix_steps + 64); ++ config.lane_count = lanes; ++ config.kv_unified = 1; ++ config.n_batch = 512; ++ config.n_ubatch = 512; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ auto status = skippy_model_open(model_path, &config, &model, &error); ++ ok(status, error); ++ require_gpu_weights(model); ++ REQUIRE(config.ctx_size <= llama_model_n_ctx_train(model->model)); ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); ++ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); ++ const int32_t vocab_size = llama_vocab_n_tokens(llama_model_get_vocab(model->model)); ++ const auto prefixes = tokens(count, vocab_size, 0); ++ auto source = create(model); ++ prefill(source, prefixes); ++ save(source, count); ++ std::array expected; ++ for (size_t lane = 0; lane < lanes; ++lane) { expected[lane] = components(source[lane]); } ++ const auto reference = decode_fixed_suffix(source, vocab_size); ++ release(source); ++ ++ auto pressure = create(model); ++ prefill(pressure, tokens(pressure_tokens, vocab_size, 503)); ++ release(pressure); ++ auto warm = restore(model, prefixes); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ const auto restored = components(warm[lane]); ++ std::fprintf(stderr, "checkpoint lane=%zu tokens=%zu kv_bytes=%zu recurrent_bytes=%zu kv_exact=%d recurrent_exact=%d\n", ++ lane, count, restored.kv.size(), restored.recurrent.size(), ++ restored.kv == expected[lane].kv, restored.recurrent == expected[lane].recurrent); ++ REQUIRE(restored.kv == expected[lane].kv); ++ REQUIRE(restored.recurrent == expected[lane].recurrent); ++ } ++ const auto restored_trace = decode_fixed_suffix(warm, vocab_size); ++ const bool passed = compare("resident restore vs reference", reference, restored_trace); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ error = nullptr; ++ status = skippy_session_drop_sequence(warm[0], static_cast(8 + lane), &error); ++ ok(status, error); ++ } ++ release(warm); ++ if (!passed) { ++ // Preserve the strict failure. A same-shape second cold reference ++ // distinguishes backend drift before any tolerance change is proposed. ++ auto repeated = create(model); ++ prefill(repeated, prefixes); ++ compare("cold reference vs repeated cold reference", reference, decode_fixed_suffix(repeated, vocab_size)); ++ release(repeated); ++ } ++ error = nullptr; ++ status = skippy_model_free(model, &error); ++ ok(status, error); ++ return passed ? 0 : 1; ++} diff --git a/src/skippy/tests/residual_checkpoint_regression.h b/src/skippy/tests/residual_checkpoint_regression.h new file mode 100644 index 000000000..31734bf56 @@ -5922,9 +6216,11 @@ index 000000000..9e134586f +#include "../runtime_types.h" +#include "../runtime_support.h" +#include "llama-model.h" ++#include "ggml-backend.h" +#include "../../../common/sampling.h" + +#include ++#include +#include +#include +#include @@ -5935,6 +6231,8 @@ index 000000000..9e134586f + std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ + std::exit(1); } } while (0) + ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); ++ +namespace { + +bool require_recurrent = false; @@ -5947,6 +6245,31 @@ index 000000000..9e134586f + skippy_error_free(error); +} + ++void configure_test_gpu(skippy_runtime_config & config) { ++ config.n_gpu_layers = 0; ++ const char * value = std::getenv("SKIPPY_NATIVE_TEST_GPU_LAYERS"); ++ if (!value) { return; } ++ CHECK(*value && std::strspn(value, "0123456789") == std::strlen(value)); ++ const unsigned long layers = std::strtoul(value, nullptr, 10); ++ CHECK(layers <= static_cast(std::numeric_limits::max())); ++ if (!layers) { return; } ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ auto status = skippy_backend_device_count(&count, &error); ++ ok(status, error); ++ for (size_t i = 0; i < count; ++i) { ++ skippy_backend_device device{}; ++ error = nullptr; ++ status = skippy_backend_device_at(i, &device, &error); ++ ok(status, error); ++ if (device.type != SKIPPY_BACKEND_DEVICE_TYPE_GPU && device.type != SKIPPY_BACKEND_DEVICE_TYPE_IGPU) { continue; } ++ config.selected_backend_device = device.name; ++ config.n_gpu_layers = static_cast(layers); ++ return; ++ } ++ CHECK(false && "GPU layers requested but no GPU backend is available"); ++} ++ +void prefill(skippy_session * session, const std::vector & tokens) { + size_t bytes = 0; + skippy_error * error = nullptr; @@ -6230,33 +6553,6 @@ index 000000000..9e134586f + return payload; +} + -+std::vector export_recurrent(skippy_session * session) { -+ skippy_error * error = nullptr; -+ size_t bytes = 0; -+ auto status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); -+ CHECK(status == SKIPPY_STATUS_BUFFER_TOO_SMALL || status == SKIPPY_STATUS_OK); -+ skippy_error_free(error); -+ error = nullptr; -+ std::vector payload(bytes); -+ status = skippy_export_recurrent_state(session, payload.data(), payload.size(), &bytes, &error); -+ ok(status, error); -+ payload.resize(bytes); -+ return payload; -+} -+ -+void restore_recurrent(skippy_session * session, const std::vector & payload, -+ const std::vector & prefix) { -+ skippy_error * error = nullptr; -+ auto status = skippy_import_recurrent_state(session, payload.data(), payload.size(), &error); -+ ok(status, error); -+ error = nullptr; -+ status = skippy_session_set_position(session, prefix.size(), &error); -+ ok(status, error); -+ error = nullptr; -+ status = skippy_session_restore_token_history(session, prefix.data(), prefix.size(), &error); -+ ok(status, error); -+} -+ +skippy_sampling_config greedy_config() { + skippy_sampling_config config{}; + config.version = 1; @@ -6283,27 +6579,20 @@ index 000000000..9e134586f + return std::vector(logits, logits + n_vocab); +} + -+// A declared-exact stage checkpoint must be reconstructible from its export -+// alone. LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY is an alias of -+// LLAMA_STATE_SEQ_FLAGS_SWA_ONLY: it writes the recurrent and sliding-window -+// half of a hybrid memory and nothing from a full-attention KV cache, so a -+// session restored from that half carries no full-attention cells and decodes a -+// different continuation from an uninterrupted prefill. Compare the attention -+// page the restored session exposes with the source's page, and the next-token -+// logits of a restored prefix with those of the same prefix prefilled from -+// scratch. ++// Exact hybrid restoration combines attention pages with a separate recurrent ++// checkpoint. The recurrent component must never duplicate full-attention KV. +void state_round_trip(skippy_model * model) { + const std::vector prefix(128, 1); + auto * source = create(model); + prefill(source, prefix); + const auto source_page = export_page(source, prefix.size()); + CHECK(!source_page.empty()); -+ const auto recurrent = export_recurrent(source); -+ CHECK(!recurrent.empty()); ++ const snapshot checkpoint(source, false); ++ CHECK(!checkpoint.recurrent.empty()); + release(source); + + auto * restored = create(model); -+ restore_recurrent(restored, recurrent, prefix); ++ checkpoint.restore(restored, prefix); + const auto restored_page = export_page(restored, prefix.size()); + CHECK(restored_page.size() == source_page.size()); + CHECK(std::memcmp(restored_page.data(), source_page.data(), source_page.size()) == 0); @@ -6316,7 +6605,7 @@ index 000000000..9e134586f + const auto cold_logits = decode_logits(cold, suffix.back()); + release(cold); + auto * warm = create(model); -+ restore_recurrent(warm, recurrent, prefix); ++ checkpoint.restore(warm, prefix); + prefill(warm, suffix); + const auto warm_logits = decode_logits(warm, suffix.back()); + release(warm); @@ -6335,6 +6624,171 @@ index 000000000..9e134586f + CHECK(max_delta == 0.0f); +} + ++void resident_prefix_ownership(skippy_model * model) { ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT); ++ CHECK(bool(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) == require_recurrent); ++ const std::vector prefix(128, 1); ++ const std::vector suffix_a{2, 3, 4}; ++ const std::vector suffix_b{5, 6, 7}; ++ constexpr int32_t cache_id = 8; ++ auto * source = create(model); ++ prefill(source, prefix); ++ skippy_error * error = nullptr; ++ uint64_t before_cells = 0; ++ ok(skippy_session_memory_used_cells(source, &before_cells, &error), error); ++ error = nullptr; ++ ok(skippy_session_save_prefix(source, cache_id, prefix.size(), &error), error); ++ uint64_t after_cells = 0; ++ error = nullptr; ++ ok(skippy_session_memory_used_cells(source, &after_cells, &error), error); ++ CHECK(before_cells == after_cells); // Sharing must not allocate attention cells. ++ uint64_t checkpoint_bytes = 0; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(source, cache_id, &checkpoint_bytes, &error), error); ++ CHECK(checkpoint_bytes >= prefix.size() * sizeof(llama_token)); ++ const auto source_page = export_page(source, prefix.size()); ++ snapshot persistent(source, false); ++ if (require_recurrent) { ++ CHECK(checkpoint_bytes > prefix.size() * sizeof(llama_token)); ++ error = nullptr; ++ CHECK(skippy_session_save_prefix(source, cache_id, prefix.size() - 1, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ uint64_t unchanged_bytes = 0; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(source, cache_id, &unchanged_bytes, &error), error); ++ CHECK(unchanged_bytes == checkpoint_bytes); ++ } ++ for (const auto token : suffix_a) { prefill(source, {token}); } ++ const auto expected_a = decode_logits(source, suffix_a.back()); ++ const auto expected_page_a = export_page(source, source->n_past); ++ release(source); // Originating lane and mutable recurrent row are gone. ++ ++ auto * recycled = create(model); ++ prefill(recycled, std::vector(32, 9)); ++ decode_logits(recycled, 10); ++ release(recycled); ++ auto * cold_b = create(model); ++ prefill(cold_b, prefix); ++ for (const auto token : suffix_b) { prefill(cold_b, {token}); } ++ const auto expected_b = decode_logits(cold_b, suffix_b.back()); ++ const auto expected_page_b = export_page(cold_b, cold_b->n_past); ++ release(cold_b); ++ ++ // Invalid identity and boundary must neither claim a lane nor damage the ++ // cached checkpoint; repeatedly exercising create catches leaked claims. ++ auto wrong_tokens = prefix; ++ wrong_tokens.back() = 12; ++ for (int attempt = 0; attempt < 4; ++attempt) { ++ skippy_session * invalid = nullptr; ++ error = nullptr; ++ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, ++ wrong_tokens.data(), wrong_tokens.size(), &invalid, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(invalid == nullptr); ++ } ++ if (require_recurrent) { ++ skippy_session * invalid = nullptr; ++ error = nullptr; ++ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, ++ prefix.data(), prefix.size() - 1, &invalid, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(invalid == nullptr); ++ } ++ auto restore = [&]() { ++ skippy_session * restored = nullptr; ++ error = nullptr; ++ ok(skippy_session_create_from_resident_prefix(model, cache_id, ++ prefix.data(), prefix.size(), &restored, &error), error); ++ CHECK(restored->token_history == prefix); ++ CHECK(export_page(restored, prefix.size()) == source_page); ++ return restored; ++ }; ++ auto * a = restore(); ++ auto * b = restore(); ++ // All execution lanes are occupied. Cold offload exports the cache-owned ++ // state directly, without restoring over either live borrower. ++ const auto history_a = a->token_history; ++ const auto history_b = b->token_history; ++ size_t kv_bytes = 0; ++ error = nullptr; ++ CHECK(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, ++ 0, prefix.size(), &persistent.page, nullptr, 0, &kv_bytes, &error) ++ == SKIPPY_STATUS_BUFFER_TOO_SMALL); ++ skippy_error_free(error); ++ CHECK(kv_bytes == persistent.payload.size()); ++ error = nullptr; ++ ok(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, ++ 0, prefix.size(), &persistent.page, persistent.payload.data(), kv_bytes, ++ &kv_bytes, &error), error); ++ CHECK(persistent.payload == source_page); ++ size_t recurrent_bytes = 0; ++ error = nullptr; ++ const auto recurrent_status = skippy_session_export_resident_recurrent_state(a, ++ cache_id, nullptr, 0, &recurrent_bytes, &error); ++ CHECK(recurrent_status == (require_recurrent ? SKIPPY_STATUS_BUFFER_TOO_SMALL : SKIPPY_STATUS_OK)); ++ skippy_error_free(error); ++ CHECK(recurrent_bytes == persistent.recurrent.size()); ++ if (recurrent_bytes) { ++ error = nullptr; ++ ok(skippy_session_export_resident_recurrent_state(a, cache_id, ++ persistent.recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); ++ } ++ CHECK(a->token_history == history_a && b->token_history == history_b); ++ CHECK(a->n_past == static_cast(prefix.size()) && b->n_past == a->n_past); ++ for (size_t i = 0; i < suffix_a.size(); ++i) { ++ prefill(a, {suffix_a[i]}); ++ prefill(b, {suffix_b[i]}); ++ } ++ // Evicting radix ownership must leave both active borrowers valid. ++ error = nullptr; ++ ok(skippy_session_drop_sequence(a, cache_id, &error), error); ++ uint64_t dropped_bytes = 1; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(a, cache_id, &dropped_bytes, &error), error); ++ CHECK(dropped_bytes == 0); ++ const auto actual_a = decode_logits(a, suffix_a.back()); ++ const auto actual_b = decode_logits(b, suffix_b.back()); ++ float delta_a = 0, delta_b = 0; ++ for (size_t i = 0; i < actual_a.size(); ++i) { ++ delta_a = std::max(delta_a, std::fabs(actual_a[i] - expected_a[i])); ++ delta_b = std::max(delta_b, std::fabs(actual_b[i] - expected_b[i])); ++ } ++ std::fprintf(stderr, "resident fork: max delta a=%.9g b=%.9g page a=%d b=%d\n", delta_a, delta_b, ++ export_page(a, a->n_past) == expected_page_a, export_page(b, b->n_past) == expected_page_b); ++ // Different shared-pool occupancy changes the CPU attention reduction ++ // shape. Measured drift is below 2e-7; reject nonfinite or larger errors ++ // and require the selected greedy token to remain identical. ++ for (const auto value : actual_a) { CHECK(std::isfinite(value)); } ++ for (const auto value : actual_b) { CHECK(std::isfinite(value)); } ++ CHECK(delta_a <= 1e-6f && delta_b <= 1e-6f); ++ CHECK(std::max_element(actual_a.begin(), actual_a.end()) - actual_a.begin() ++ == std::max_element(expected_a.begin(), expected_a.end()) - expected_a.begin()); ++ CHECK(std::max_element(actual_b.begin(), actual_b.end()) - actual_b.begin() ++ == std::max_element(expected_b.begin(), expected_b.end()) - expected_b.begin()); ++ if (require_recurrent) { ++ CHECK(export_page(a, a->n_past) == expected_page_a); ++ CHECK(export_page(b, b->n_past) == expected_page_b); ++ } ++ release(a); ++ release(b); ++ // The resident owner has been evicted. The independently exported payload ++ // still reconstructs both attention and recurrent state in a new lane. ++ auto * persisted = create(model); ++ persistent.restore(persisted, prefix); ++ CHECK(export_page(persisted, prefix.size()) == source_page); ++ for (const auto token : suffix_a) { prefill(persisted, {token}); } ++ const auto persisted_logits = decode_logits(persisted, suffix_a.back()); ++ for (size_t i = 0; i < persisted_logits.size(); ++i) { ++ CHECK(std::isfinite(persisted_logits[i])); ++ CHECK(std::fabs(persisted_logits[i] - expected_a[i]) <= 1e-6f); ++ } ++ release(persisted); ++ } ++ +void adapter_contracts(skippy_model * model) { + auto * session = create(model); + prefill(session, {1, 2}); @@ -6393,20 +6847,43 @@ index 000000000..9e134586f +} // namespace + +int main(int argc, char ** argv) { ++ if (argc == 2 && std::strcmp(argv[1], "resident-gpu-long") == 0) { ++ const char * model_path = std::getenv("SKIPPY_NATIVE_TEST_REAL_MODEL"); ++ if (!model_path) { std::fprintf(stderr, "SKIPPY_NATIVE_TEST_REAL_MODEL is unset; skipping real GPU checkpoint proof\n"); return 77; } ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = "CPU"; ++ configure_test_gpu(config); ++ return skippy_test_resident_checkpoint_gpu(model_path, config); ++ } + CHECK(argc == 4); + const bool grammar = std::strcmp(argv[2], "grammar") == 0; + const bool state = std::strcmp(argv[2], "state") == 0; -+ CHECK(grammar || state || std::strcmp(argv[2], "penalty") == 0); ++ const bool resident = std::strcmp(argv[2], "resident") == 0; ++ CHECK(grammar || state || resident || std::strcmp(argv[2], "penalty") == 0); + CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); + require_recurrent = std::strcmp(argv[3], "recurrent") == 0; + auto config = skippy_runtime_config_default(); + config.selected_backend_device = "CPU"; ++ configure_test_gpu(config); + config.ctx_size = 512; ++ if (resident) { config.lane_count = 2; config.kv_unified = 1; } + skippy_model * model = nullptr; + skippy_error * error = nullptr; + const auto status = skippy_model_open(argv[1], &config, &model, &error); + ok(status, error); -+ if (state) { ++ if (config.n_gpu_layers > 0) { ++ CHECK(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), ++ [](const auto & item) { ++ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } ++ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( ++ ggml_backend_buffer_get_type(item.second->buffer))); ++ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; ++ })); ++ std::fprintf(stderr, "GPU ownership test: device=%s requested_layers=%d\n", config.selected_backend_device, config.n_gpu_layers); ++ } ++ if (resident) { ++ resident_prefix_ownership(model); ++ } else if (state) { + // A dense stage's page already carries its whole checkpoint, so the + // partial side payload is intentionally empty there. + CHECK(require_recurrent); @@ -9763,12 +10240,12 @@ index 000000000..30c88b490 + }); + return skippy_graph_cache_capabilities(result); + }; -+ const uint32_t dense = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | ++ const uint32_t dense = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | + SKIPPY_MEMORY_CACHE_FULL_STATE; + if (capabilities(skippy_state_kind::kv_key) != dense || + capabilities(skippy_state_kind::kv_value) != dense || -+ capabilities(skippy_state_kind::recurrent_conv) != (SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || -+ capabilities(skippy_state_kind::recurrent_ssm) != (SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || ++ capabilities(skippy_state_kind::recurrent_conv) != dense || ++ capabilities(skippy_state_kind::recurrent_ssm) != dense || + capabilities(skippy_state_kind::derived_persistent) != SKIPPY_MEMORY_CACHE_FULL_STATE) { + return false; + } @@ -9843,7 +10320,7 @@ index 000000000..30c88b490 + {}); + + if (skippy_memory_cache_capabilities(&kv) != -+ (SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || ++ (SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || + skippy_model_memory_cache_capabilities(nullptr) != 0) { + return 1; + } @@ -10426,6 +10903,8 @@ index 000000000..0fae7bbd4 +#include "../src/llama-io.h" +#include "../src/llama-memory-recurrent.h" +#include "../src/llama-model.h" ++#include "../src/skippy/state_memory.h" ++#include "skippy/state.h" + +#include "ggml-backend.h" + @@ -10512,6 +10991,13 @@ index 000000000..0fae7bbd4 + model->hparams.ssm_d_inner = 2; + + auto source = make_memory(*model); ++ const auto capabilities = skippy_memory_cache_capabilities(&source); ++ if (!(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) ++ || !(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT) ++ || (capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION)) { ++ std::fprintf(stderr, "pure recurrent memory has an incorrect resident attention contract\n"); ++ return 13; ++ } + llama_pos source_pos = 7; + llama_seq_id source_seq_id = 0; + llama_seq_id * source_seq_ids = &source_seq_id; @@ -10580,6 +11066,37 @@ index 000000000..0fae7bbd4 + return 7; + } + ++ // Immutable cache-owned bytes survive source lane removal and reuse. ++ if (!source.seq_rm(source_seq_id, -1, -1)) { return 8; } ++ const std::vector changed_r = { 91.0f, 92.0f, 93.0f, 94.0f }; ++ ggml_backend_tensor_set(source.r_l[0], changed_r.data(), 0, changed_r.size() * sizeof(float)); ++ buffer_reader second_reader(writer.data); ++ destination.state_read(second_reader, 0, LLAMA_STATE_SEQ_FLAGS_NONE); ++ const auto a_row = destination.cells[0].tail; ++ const auto b_row = destination.cells[1].tail; ++ if (a_row < 0 || b_row < 0 || a_row == b_row) { ++ std::fprintf(stderr, "restored recurrent borrowers did not receive private mutable rows\n"); ++ return 9; ++ } ++ ggml_backend_tensor_set(destination.r_l[0], changed_r.data(), ++ destination.r_l[0]->nb[1] * a_row, changed_r.size() * sizeof(float)); ++ buffer_writer preserved_b; ++ destination.state_write(preserved_b, 1, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (preserved_b.data != writer.data) { ++ std::fprintf(stderr, "diverging borrower changed another recurrent checkpoint\n"); ++ return 10; ++ } ++ // The original checkpoint can restore again after either borrower is freed. ++ if (!destination.seq_rm(0, -1, -1)) { return 11; } ++ buffer_reader third_reader(writer.data); ++ destination.state_read(third_reader, 0, LLAMA_STATE_SEQ_FLAGS_NONE); ++ buffer_writer restored_a; ++ destination.state_write(restored_a, 0, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (restored_a.data != writer.data) { ++ std::fprintf(stderr, "recurrent checkpoint changed after repeated lane recycling\n"); ++ return 12; ++ } ++ + return 0; +} diff --git a/tests/test-skippy-rerank-template.cpp b/tests/test-skippy-rerank-template.cpp diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 5bb7366cf2..885c560641 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -20,11 +20,11 @@ to touch common.h it carries the queue's ABI version, 0.1.77. include/skippy/sampling.h | 4 ++ src/CMakeLists.txt | 1 + src/skippy/logprobs.cpp | 94 ++++++++++++++++++++++++++++++++++ + src/skippy/resident_prefix.cpp | 1 + src/skippy/runtime_types.h | 2 + src/skippy/sampling.cpp | 21 +++++++- src/skippy/sampling_internal.h | 7 +++ src/skippy/session.cpp | 1 + - src/skippy/state.cpp | 1 + src/skippy/workloads.cpp | 1 + 12 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 include/skippy/logprobs.h @@ -255,6 +255,18 @@ index 000000000..43260dfc2 + *out_count = taken; + return skippy_success(out_error); +} +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +index 1b82ba6ba..42769ba7c 100644 +--- a/src/skippy/resident_prefix.cpp ++++ b/src/skippy/resident_prefix.cpp +@@ -182,6 +182,7 @@ skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, + } + session->n_past = static_cast(count); + session->token_history = std::move(history); ++ session->signal_history.clear(); + skippy_mtp_clear_session_state(session); + session->verify_checkpoints.clear(); + return skippy_success(error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h index ec9fb94b1..cd8a82f7a 100644 --- a/src/skippy/runtime_types.h @@ -342,7 +354,7 @@ diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp index a9251d2c9..13e318534 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -379,6 +379,7 @@ enum skippy_status skippy_session_reset( +@@ -376,6 +376,7 @@ enum skippy_status skippy_session_reset( session->token_history.clear(); } session->signal_history.clear(); From 284ccb9a121358fcec98102a985495847029d089 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 14:11:46 +1100 Subject: [PATCH 02/81] fix(skippy): report independent checkpoint RAM retention Make effective settings reflect that checkpoint RAM does not require disk caching and that native capabilities determine prefix budget accounting. Cover the report in the existing RAM-without-disk test. --- skippy/crates/skippy-cli/src/serve_settings/report.rs | 4 ++-- skippy/crates/skippy-cli/src/serve_settings/tests.rs | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/skippy/crates/skippy-cli/src/serve_settings/report.rs b/skippy/crates/skippy-cli/src/serve_settings/report.rs index f3b629581f..90b4da1ffa 100644 --- a/skippy/crates/skippy-cli/src/serve_settings/report.rs +++ b/skippy/crates/skippy-cli/src/serve_settings/report.rs @@ -62,8 +62,8 @@ impl ServeSettings { "sources": sources, "constraints": { "unified_kv": "required", - "ram_cache_requires_disk": true, - "prefix_budget": "retention target; one indivisible exact-state snapshot may exceed its limit", + "ram_cache_requires_disk": false, + "prefix_budget": "retention target; loaded native cache capabilities determine accounting", "capabilities": "payload/backend compatibility resolves after model load", }, }) diff --git a/skippy/crates/skippy-cli/src/serve_settings/tests.rs b/skippy/crates/skippy-cli/src/serve_settings/tests.rs index 09c7cab20b..23e1dc058f 100644 --- a/skippy/crates/skippy-cli/src/serve_settings/tests.rs +++ b/skippy/crates/skippy-cli/src/serve_settings/tests.rs @@ -878,6 +878,13 @@ fn checkpoint_ram_budget_does_not_require_disk() { stage.kv_cache.as_ref().unwrap().l2_max_bytes, 1024 * 1024 * 1024 ); + let tuning = args + .public + .settings + .tuning(args.public.openai_guardrails) + .unwrap(); + let report = args.public.settings.report(&stage, None, &tuning); + assert_eq!(report["constraints"]["ram_cache_requires_disk"], false); stage.kv_cache.as_mut().unwrap().mode = skippy_protocol::StageKvCacheMode::Disabled; assert!( args.public From dfb5de052b68198200da60164fc7f3467b40110f Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 14:15:35 +1100 Subject: [PATCH 03/81] docs: track reusable four-model KV validation jobs --- todo.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 todo.md diff --git a/todo.md b/todo.md new file mode 100644 index 0000000000..59d12253ba --- /dev/null +++ b/todo.md @@ -0,0 +1,71 @@ +# Reusable KV validation on JY + +Implement this **after the current cache and performance work**. Turn the +experiments into repeatable JY jobs that we can run whenever KV behavior changes. + +## Four-model AgentX matrix + +Run the suite on all four selected models, each using **Q4_K_M**: + +| Model | Category | GGUF | +|---|---|---| +| Qwen3-4B-Instruct-2507 | Dense attention | `Qwen3-4B-Instruct-2507-Q4_K_M.gguf` | +| Qwen3.5-4B | Hybrid dense | `Qwen3.5-4B-Q4_K_M.gguf` | +| Qwen3-Coder-30B-A3B-Instruct | Attention MoE | `Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf` | +| Qwen3.5-35B-A3B | Hybrid MoE | `Qwen3.5-35B-A3B-Q4_K_M.gguf` | + +Use the exact HF repositories, revisions, tokenizer revisions, and weight hashes +from `6c0464e5531a9ff8ceb89c068ad94cd53c71e334:skippy/evals/agentx/models.json`. +The recovered manifest has SHA-256 +`6a2b724cf32208186d80ac614e21a168bfc08ca72e55afdabc3dc39b338c9206`. +Small generated native fixtures supplement this matrix; they do not replace it. + +## Reusable jobs + +- [ ] Build matching Skippy binaries, native runtimes, and correctness tests once + per backend; reuse the verified artifacts across model jobs. +- [ ] Validate native prefix ownership with long prefixes and multiple lanes: + save, release the source, apply pressure, recycle lanes, restore, and fork. + Compare attention and recurrent state bytes, fixed-input logits, and tokens. +- [ ] Compare from controlled identical state and batch geometry. Include repeat + controls so allocation history or numerical variation cannot masquerade as a + cache bug. Do not weaken correctness gates to accept an optimization. +- [ ] Exercise cold, warm, shared-prefix, changed-tail, and A/B/C/revisit requests + at c1/c2/c4. Check reuse counts, actual shared-pool capacity, and lane isolation. +- [ ] Test cache-off controls and c1 generated-content parity. Output-token counts + and their hashes alone are not generated-token correctness evidence. +- [ ] Test the default 1 GiB checkpoint budget and an explicit larger budget, + independently of disk caching, including rejection of entries that cannot fit. +- [ ] Force persistent L3 eviction, wait for committed writes, stop cleanly, and + restart a fresh server. Verify real L3 hits, complete restoration, and content + correctness. Cover refused or failed offloads and fail-open inference. +- [ ] Compare throughput, TTFT, token latency, cache reuse, and memory against + **standard vanilla llama.cpp** on the same model and workload. Unified-KV llama + is a separate diagnostic control and must not replace the parity target. +- [ ] Retain the fixed AgentX replay as a performance check with its pinned + external client and corpus, including complete request/output accounting. + +## Execution and evidence + +- [ ] Implement typed Rust automation in the existing owning tooling, with thin + Just entrypoints and reusable JY job definitions. Reuse existing native tests, + cache-family measurement, stability checks, and process supervision. +- [ ] Make these explicit JY validation jobs; do not add the full GPU/model matrix + as an always-on local or ordinary CI requirement. +- [ ] Materialize actual settings: context per lane and total pool, concurrency, + threads, native batch/microbatch, frontend prefill chunk size/policy, KV dtypes, + flash attention, cache budgets, and disk mode. Native microbatch size does not + establish the frontend prefill chunk size. +- [ ] Verify source, model, binary, test binary, runtime leaf, ABI, patch digest, + image, client, and corpus identities before measuring. Reject stale or nested + runtime bundles and require proof of real GPU execution. +- [ ] Schedule independent jobs across equivalent available Sparks without + stacking measurements on one GPU. Current excluded nodes are `spark-000280` + (`spark-db08`) and `spark-000499` (`spark-9f06`); enforce exclusions through the + operator profile and worker admission. +- [ ] Retain raw requests/responses, resolved settings, timing and memory samples, + logs, and artifact hashes for successes and failures. Propagate child failures; + classify unsupported or missing required evidence explicitly. +- [ ] Report correctness separately from performance regressions. Document the + commands and run the reusable suite across all four models on the allowed + machines, with CUDA and Metal coverage recorded separately. From fc455131fcf5c6d42346559290f33fac34dd6f84 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 14:42:11 +1100 Subject: [PATCH 04/81] fix(skippy): admit requests against the full KV pool --- .../skippy-serving/src/frontend/admission.rs | 77 +++++++++++++++++++ .../src/frontend/generation/server.rs | 6 +- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/skippy/crates/skippy-serving/src/frontend/admission.rs b/skippy/crates/skippy-serving/src/frontend/admission.rs index d26a5470a2..6196ee3c43 100644 --- a/skippy/crates/skippy-serving/src/frontend/admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/admission.rs @@ -57,6 +57,21 @@ pub(super) struct GenerationTokenReservation { } impl GenerationTokenBudget { + /// Admission shares the loaded context's aggregate pool across its lanes. + /// Modelless runtimes may leave capacity unknown; retain the caller's + /// configured budget in that case without inferring a native allocation. + pub(super) fn for_runtime( + runtime: &crate::runtime_state::RuntimeState, + configured_tokens: usize, + ) -> Self { + let pool_tokens = runtime.kv_pool_tokens(); + Self::new(if pool_tokens == 0 { + configured_tokens + } else { + usize::try_from(pool_tokens).unwrap_or(usize::MAX) + }) + } + pub(super) fn new(ctx_size: usize) -> Self { Self { capacity_tokens: ctx_size.max(1), @@ -263,6 +278,68 @@ mod tests { time::{Duration, Instant}, }; + #[test] + fn frontend_admission_uses_loaded_aggregate_pool() { + use crate::runtime_state::RuntimeState; + use std::sync::Arc; + + let runtime = RuntimeState::new_modelless_with_capacity_for_test(4, 524_288); + let budget = Arc::new(GenerationTokenBudget::for_runtime(&runtime, 131_072)); + let requests = (0..4) + .map(|_| { + budget + .try_reserve(GenerationTokenBudgetRequest::new(94_000, 512)) + .unwrap() + .expect("four long requests fit the loaded four-lane pool") + }) + .collect::>(); + assert_eq!(budget.active_tokens(), 378_048); + drop(requests); + + let _requests = (0..4) + .map(|_| { + budget + .try_reserve(GenerationTokenBudgetRequest::new(120_000, 512)) + .unwrap() + .unwrap() + }) + .collect::>(); + assert!( + budget + .try_reserve(GenerationTokenBudgetRequest::new(94_000, 512)) + .unwrap() + .is_none(), + "aggregate admission must still stop requests that exceed the native pool" + ); + } + + #[test] + fn frontend_admission_keeps_modelless_capacity_and_unknown_fallback() { + use crate::runtime_state::RuntimeState; + use std::sync::Arc; + + let runtime = RuntimeState::new_modelless_for_test(4); + let fallback = Arc::new(GenerationTokenBudget::for_runtime(&runtime, 128)); + assert!( + fallback + .try_reserve(GenerationTokenBudgetRequest::new(129, 0)) + .is_err() + ); + let runtime = RuntimeState::new_modelless_with_capacity_for_test(4, 256); + let explicit = Arc::new(GenerationTokenBudget::for_runtime(&runtime, 128)); + assert!( + explicit + .try_reserve(GenerationTokenBudgetRequest::new(256, 0)) + .unwrap() + .is_some() + ); + assert!( + explicit + .try_reserve(GenerationTokenBudgetRequest::new(257, 0)) + .is_err() + ); + } + #[test] fn generation_token_budget_reserves_and_releases_tokens() { let budget = Arc::new(GenerationTokenBudget::new(1_024)); diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index f9b001a4e0..f290ac8ae6 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -428,6 +428,10 @@ fn embedded_openai_backend_with_state_kind( args.telemetry.emit("stage.kv_payload_selected", attrs); } let ctx_size = usize::try_from(args.config.ctx_size).unwrap_or(usize::MAX); + let generation_token_budget = { + let runtime = crate::runtime_state::panic_recovery::lock_runtime(&args.runtime); + Arc::new(GenerationTokenBudget::for_runtime(&runtime, ctx_size)) + }; let iteration_scheduler = match iteration_scheduler { Some(iteration_scheduler) => iteration_scheduler, None => IterationScheduler::new( @@ -495,7 +499,7 @@ fn embedded_openai_backend_with_state_kind( args.generation_concurrency, )), generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())), - generation_token_budget: Arc::new(GenerationTokenBudget::new(ctx_size)), + generation_token_budget, hook_policy: args.hook_policy, generation_receipt: args.generation_receipt, generation_lifecycle: args.generation_lifecycle, From 2774f4222955f7337188e99ea6c1e393028a4339 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 14:50:56 +1100 Subject: [PATCH 05/81] docs: cover admission and retained KV scaling in validation --- todo.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/todo.md b/todo.md index 59d12253ba..3e0d9c8bd1 100644 --- a/todo.md +++ b/todo.md @@ -32,6 +32,13 @@ Small generated native fixtures supplement this matrix; they do not replace it. cache bug. Do not weaken correctness gates to accept an optimization. - [ ] Exercise cold, warm, shared-prefix, changed-tail, and A/B/C/revisit requests at c1/c2/c4. Check reuse counts, actual shared-pool capacity, and lane isolation. +- [ ] Admit concurrent long prompts whose combined reservations exceed one + lane's context but fit the loaded aggregate pool. Verify actual overlap and + preserve each request's context limit; distinguish admission waits from + frontend runtime-lock waits. +- [ ] Measure identical cold work after retaining additional prefixes. Compare + attention kernel time, matrix multiplication, transfers, and mask/input work + against standard vanilla to catch costs that grow with idle physical KV cells. - [ ] Test cache-off controls and c1 generated-content parity. Output-token counts and their hashes alone are not generated-token correctness evidence. - [ ] Test the default 1 GiB checkpoint budget and an explicit larger budget, From 0ae5e10620181bf681afcf48399b3c955aec521b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 16:33:54 +1100 Subject: [PATCH 06/81] feat(ggml): add indexed KV attention for validation Reuse existing CUDA and Metal attention kernels with request-local KV indices and lengths, including quantized KV readers. Record CPU, Metal and CUDA operator validation and the blocking actual-model CUDA parity failure. This review candidate is not qualified for deployment or performance claims. --- .../docs/design/INDEXED_ATTENTION_STATUS.md | 53 + ...equest-local-KV-indices-in-flash-att.patch | 3400 +++++++++++++++++ todo.md | 24 +- 3 files changed, 3476 insertions(+), 1 deletion(-) create mode 100644 skippy/docs/design/INDEXED_ATTENTION_STATUS.md create mode 100644 skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md new file mode 100644 index 0000000000..6620aeb185 --- /dev/null +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -0,0 +1,53 @@ +# Indexed KV attention: review candidate + +Status on 2026-10-31: implementation available for review; actual-model CUDA +numerical parity fails. This candidate is not qualified for deployment or +throughput comparisons. + +## Change + +The new core patch, `0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch`, +extends the existing `FLASH_ATTN_EXT` operation with per-request physical row +indices and logical lengths. CUDA uses the existing vector, tiled, and MMA +attention implementations; Metal and CPU implement the same indexed contract. +Quantized rows are read directly without converting the complete physical pool. +Allocator ownership, persistent L3 representation, and the public Skippy ABI +are unchanged. + +The branch also includes resident prefix ownership and frontend KV admission +changes preceding this kernel work. The kernel patch is a separate commit so +reviewers can inspect it independently. + +## Validation + +- Clean replay from native upstream `620d2225cc436ab0b001e3200e590e3b286ef9ab` + produces native HEAD `3e756354af978f8a3432a22df7e1465363538ee8`, tree + `d9963c3bedb9f1d6658821784a897c149ad1bccf`, queue digest + `194c5d51170a0e9a47dbe8268f1a2422323e8088fb0cd68aa20ad52f9dd94c88`. +- Operator comparisons pass: 910 CPU, 654 Metal, and 608 CUDA. CUDA graphs are + enabled. The existing per-request NMSE limit remains `5e-4`. Cases already + unsupported by a backend's dense operator remain explicitly unsupported. +- Real Qwen3.5-4B smoke tests pass on CPU and Metal for all eight supported + same-type KV formats. Graph checks require indices, lengths, the requested + KV type, and the selected backend throughout prefill and decode. These are + execution smoke checks, not cross-path numerical parity evidence. +- The prior local native suite completed with 285 executed tests passing and + one explicitly skipped long GPU test. + +## Blocking CUDA result + +JY job `job_yg6c28ny2f5k9hn`, run `run_wkzw1rnq1ccps94`, on Spark 000137 +built and packaged this candidate and passed operator and small resident tests. +The actual Qwen3.5-4B proof imported the reference's exact canonical context, +verified all eight physical sequence layouts and active KV/recurrent bytes, +and confirmed indexed execution on CUDA for every attention layer. + +For four lanes with 32 teacher-forced decode steps, dense/dense and +indexed/indexed repeats each have zero logit delta and zero greedy differences. +Dense/indexed comparisons fail the unchanged `1e-6` full-vocabulary gate: +maximum logit delta `0.284694672`, with one greedy difference. Divergence is +already present at the first decode step; this is not only accumulated drift. +Performance runs and other-model fanout remain blocked pending diagnosis. + +The reusable four-model CUDA/Metal/CPU validation work is tracked in +[todo.md](../../../todo.md). diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch new file mode 100644 index 0000000000..0e9a27c3a3 --- /dev/null +++ b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch @@ -0,0 +1,3400 @@ +From f644ed55e3ed368fc752f8aa7b37a8829a94a7ce Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 31 Oct 2026 16:18:58 +1100 +Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention + +--- + ggml/include/ggml.h | 18 + + ggml/src/ggml-backend-meta.cpp | 5 + + ggml/src/ggml-cann/ggml-cann.cpp | 3 + + ggml/src/ggml-cpu/CMakeLists.txt | 2 + + ggml/src/ggml-cpu/attention-indexed.cpp | 121 ++++++ + ggml/src/ggml-cpu/attention-indexed.h | 7 + + ggml/src/ggml-cpu/ops.cpp | 5 + + ggml/src/ggml-cpu/spacemit/ime.cpp | 3 + + ggml/src/ggml-cuda/common.cuh | 1 + + ggml/src/ggml-cuda/fattn-common.cuh | 66 ++- + ggml/src/ggml-cuda/fattn-indexed.cuh | 45 +++ + ggml/src/ggml-cuda/fattn-mma-f16.cuh | 208 ++++++---- + ggml/src/ggml-cuda/fattn-tile.cuh | 95 ++++- + ggml/src/ggml-cuda/fattn-vec.cuh | 53 ++- + ggml/src/ggml-cuda/fattn.cu | 63 ++- + ggml/src/ggml-cuda/ggml-cuda.cu | 1 + + ggml/src/ggml-et/ggml-et.cpp | 3 + + ggml/src/ggml-hexagon/ggml-hexagon.cpp | 2 +- + .../ggml-metal/ggml-metal-attention-indexed.h | 90 +++++ + ggml/src/ggml-metal/ggml-metal-device.cpp | 12 +- + ggml/src/ggml-metal/ggml-metal-device.m | 5 + + ggml/src/ggml-metal/ggml-metal-impl.h | 10 + + ggml/src/ggml-metal/ggml-metal-ops.cpp | 62 ++- + ggml/src/ggml-metal/kernels/fa_common.metal | 144 ++++++- + .../ggml-metal/kernels/fa_vec_common.metal | 29 +- + ggml/src/ggml-opencl/ggml-opencl.cpp | 3 + + ggml/src/ggml-openvino/ggml-openvino.cpp | 3 + + ggml/src/ggml-sycl/ggml-sycl.cpp | 2 +- + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 3 + + ggml/src/ggml-webgpu/ggml-webgpu.cpp | 2 +- + ggml/src/ggml.c | 44 +- + src/CMakeLists.txt | 2 + + src/llama-graph-kv-read.cpp | 126 ++++++ + src/llama-graph.cpp | 85 ++-- + src/llama-graph.h | 21 +- + src/llama-kv-cache.h | 2 + + src/llama-kv-read.cpp | 148 +++++++ + src/llama-kv-read.h | 20 + + tests/CMakeLists.txt | 2 + + tests/test-flash-attn-indexed.cpp | 378 ++++++++++++++++++ + 40 files changed, 1687 insertions(+), 207 deletions(-) + create mode 100644 ggml/src/ggml-cpu/attention-indexed.cpp + create mode 100644 ggml/src/ggml-cpu/attention-indexed.h + create mode 100644 ggml/src/ggml-cuda/fattn-indexed.cuh + create mode 100644 ggml/src/ggml-metal/ggml-metal-attention-indexed.h + create mode 100644 src/llama-graph-kv-read.cpp + create mode 100644 src/llama-kv-read.cpp + create mode 100644 src/llama-kv-read.h + create mode 100644 tests/test-flash-attn-indexed.cpp + +diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h +index c37ba9471..315f554a7 100644 +--- a/ggml/include/ggml.h ++++ b/ggml/include/ggml.h +@@ -2499,6 +2499,24 @@ extern "C" { + float max_bias, + float logit_softcap); + ++ // Same attention operation with request-local reads from shared physical K/V. ++ // indices: I32 [logical_kv, query_rows, heads, requests], broadcast over Q. ++ // lengths: I32 [1, query_rows, heads, requests], matching indices dimensions. ++ // The F16 mask addresses logical slots; indices address physical K/V rows. ++ // Each valid index must be in [0, k->ne[1]); padding beyond lengths is -1. ++ // K/V sequence dimensions may be 1 (shared pool) or match Q. ++ GGML_API struct ggml_tensor * ggml_flash_attn_ext_indexed( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, ++ struct ggml_tensor * k, ++ struct ggml_tensor * v, ++ struct ggml_tensor * mask, ++ struct ggml_tensor * indices, ++ struct ggml_tensor * lengths, ++ float scale, ++ float max_bias, ++ float logit_softcap); ++ + GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( + struct ggml_tensor * a, + enum ggml_prec prec), +diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp +index 679d5216d..bc0407094 100644 +--- a/ggml/src/ggml-backend-meta.cpp ++++ b/ggml/src/ggml-backend-meta.cpp +@@ -153,6 +153,11 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type( + + static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + GGML_ASSERT(ggml_backend_dev_is_meta(dev)); ++ // The split-state planner does not yet partition/broadcast logical row ++ // tables alongside head-sharded attention inputs. ++ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { ++ return false; ++ } + const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; + return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), + [op](ggml_backend_dev_t simple_dev) { return ggml_backend_dev_supports_op(simple_dev, op); }); +diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp +index 28e17f3f7..b6e2d7d5e 100644 +--- a/ggml/src/ggml-cann/ggml-cann.cpp ++++ b/ggml/src/ggml-cann/ggml-cann.cpp +@@ -2664,6 +2664,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten + return true; + case GGML_OP_FLASH_ATTN_EXT: + { ++ if (op->src[5]) { ++ return false; ++ } + #ifdef ASCEND_310P + // FA not support on 310p device + return false; +diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt +index d347757e1..d817dca43 100644 +--- a/ggml/src/ggml-cpu/CMakeLists.txt ++++ b/ggml/src/ggml-cpu/CMakeLists.txt +@@ -56,6 +56,8 @@ function(ggml_add_cpu_backend_variant_impl tag_name) + ggml-cpu/vec.cpp + ggml-cpu/ops.h + ggml-cpu/ops.cpp ++ ggml-cpu/attention-indexed.cpp ++ ggml-cpu/attention-indexed.h + ) + + target_compile_features(${GGML_CPU_NAME} PRIVATE c_std_11 cxx_std_17) +diff --git a/ggml/src/ggml-cpu/attention-indexed.cpp b/ggml/src/ggml-cpu/attention-indexed.cpp +new file mode 100644 +index 000000000..0f62a5185 +--- /dev/null ++++ b/ggml/src/ggml-cpu/attention-indexed.cpp +@@ -0,0 +1,121 @@ ++#include "attention-indexed.h" ++ ++#include "ggml-cpu.h" ++#include "ggml-cpu-impl.h" ++#include "ggml-impl.h" ++#include "vec.h" ++ ++#include ++#include ++#include ++#include ++ ++// CPU reference for the existing attention op's optional logical read tables. ++// K/V remain in their shared physical storage; only row addresses are indirect. ++void ggml_compute_forward_flash_attn_indexed( ++ const ggml_compute_params * params, ggml_tensor * dst) { ++ const auto * q = dst->src[0]; ++ const auto * k = dst->src[1]; ++ const auto * v = dst->src[2]; ++ const auto * mask = dst->src[3]; ++ const auto * sinks = dst->src[4]; ++ const auto * indices = dst->src[5]; ++ const auto * lengths = dst->src[6]; ++ const int64_t dk = q->ne[0]; ++ const int64_t dv = v->ne[0]; ++ const auto * kt = ggml_get_type_traits_cpu(k->type); ++ const auto * qt = ggml_get_type_traits_cpu(kt->vec_dot_type); ++ const auto * vt = ggml_get_type_traits(v->type); ++ GGML_ASSERT(q->type == GGML_TYPE_F32 && kt->vec_dot && qt->from_float); ++ GGML_ASSERT(v->type == GGML_TYPE_F32 || vt->to_float); ++ ++ float scale, max_bias, softcap; ++ memcpy(&scale, dst->op_params, sizeof(float)); ++ memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); ++ memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(float)); ++ if (softcap != 0.0f) { ++ scale /= softcap; ++ } ++ const uint32_t head_power = 1u << (uint32_t) std::floor(std::log2(q->ne[2])); ++ const float m0 = std::pow(2.0f, -max_bias / head_power); ++ const float m1 = std::pow(2.0f, -(max_bias / 2.0f) / head_power); ++ std::vector converted_q(dk); ++ std::vector converted_v(dv); ++ std::vector accum(dv); ++ ++ const int64_t rows = q->ne[1] * q->ne[2] * q->ne[3]; ++ for (int64_t row = params->ith; row < rows; row += params->nth) { ++ const int64_t request = row / (q->ne[1] * q->ne[2]); ++ const int64_t head = (row / q->ne[1]) % q->ne[2]; ++ const int64_t query = row % q->ne[1]; ++ const auto * ids = (const int32_t *) ((const char *) indices->data + ++ (query % indices->ne[1]) * indices->nb[1] + ++ (head % indices->ne[2]) * indices->nb[2] + ++ (request % indices->ne[3]) * indices->nb[3]); ++ const int32_t count = *(const int32_t *) ((const char *) lengths->data + ++ (query % lengths->ne[1]) * lengths->nb[1] + ++ (head % lengths->ne[2]) * lengths->nb[2] + ++ (request % lengths->ne[3]) * lengths->nb[3]); ++ GGML_ASSERT(count >= 0 && count <= indices->ne[0]); ++ const auto * pm = mask ? (const ggml_fp16_t *) ((const char *) mask->data + ++ query * mask->nb[1] + (head % mask->ne[2]) * mask->nb[2] + ++ (request % mask->ne[3]) * mask->nb[3]) : nullptr; ++ const auto * pq = (const float *) ((const char *) q->data + query * q->nb[1] + ++ head * q->nb[2] + request * q->nb[3]); ++ qt->from_float(pq, converted_q.data(), dk); ++ const float slope = max_bias > 0 ? (head < head_power ? ++ std::pow(m0, head + 1) : std::pow(m1, 2 * (head - head_power) + 1)) : 1.0f; ++ const size_t k_offset = (head / (q->ne[2] / k->ne[2])) * k->nb[2] + ++ (request / (q->ne[3] / k->ne[3])) * k->nb[3]; ++ const size_t v_offset = (head / (q->ne[2] / v->ne[2])) * v->nb[2] + ++ (request / (q->ne[3] / v->ne[3])) * v->nb[3]; ++ std::fill(accum.begin(), accum.end(), 0.0f); ++ float maximum = -INFINITY; ++ float sum = 0.0f; ++ for (int32_t slot = 0; slot < count; ++slot) { ++ const int32_t physical = ids[slot]; ++ GGML_ASSERT(physical >= 0 && physical < k->ne[1] && physical < v->ne[1]); ++ const float bias = pm ? slope * GGML_FP16_TO_FP32(pm[slot]) : 0.0f; ++ if (bias == -INFINITY) { ++ continue; ++ } ++ float score; ++ const char * pk = (const char *) k->data + physical * k->nb[1] + k_offset; ++ kt->vec_dot(dk, &score, 0, pk, 0, converted_q.data(), 0, 1); ++ score *= scale; ++ if (softcap != 0) { ++ score = softcap * std::tanh(score); ++ } ++ score += bias; ++ const float next_max = std::max(maximum, score); ++ const float old_scale = std::exp(maximum - next_max); ++ const float weight = std::exp(score - next_max); ++ const char * pv = (const char *) v->data + physical * v->nb[1] + v_offset; ++ const float * values = (const float *) pv; ++ if (v->type != GGML_TYPE_F32) { ++ vt->to_float(pv, converted_v.data(), dv); ++ values = converted_v.data(); ++ } ++ for (int64_t d = 0; d < dv; ++d) { ++ accum[d] = accum[d] * old_scale + values[d] * weight; ++ } ++ sum = sum * old_scale + weight; ++ maximum = next_max; ++ } ++ if (sinks && count > 0) { ++ const float sink = ((const float *) sinks->data)[head]; ++ const float next_max = std::max(maximum, sink); ++ const float old_scale = std::exp(maximum - next_max); ++ for (float & value : accum) { ++ value *= old_scale; ++ } ++ sum = sum * old_scale + std::exp(sink - next_max); ++ } ++ const float inverse = sum > 0 ? 1.0f / sum : 0.0f; ++ auto * output = (float *) ((char *) dst->data + query * dst->nb[2] + ++ head * dst->nb[1] + request * dst->nb[3]); ++ for (int64_t d = 0; d < dv; ++d) { ++ output[d] = accum[d] * inverse; ++ } ++ } ++} +diff --git a/ggml/src/ggml-cpu/attention-indexed.h b/ggml/src/ggml-cpu/attention-indexed.h +new file mode 100644 +index 000000000..675c343d5 +--- /dev/null ++++ b/ggml/src/ggml-cpu/attention-indexed.h +@@ -0,0 +1,7 @@ ++#pragma once ++ ++struct ggml_compute_params; ++struct ggml_tensor; ++ ++void ggml_compute_forward_flash_attn_indexed( ++ const ggml_compute_params * params, ggml_tensor * dst); +diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp +index 7a73e138e..6dacbd226 100644 +--- a/ggml/src/ggml-cpu/ops.cpp ++++ b/ggml/src/ggml-cpu/ops.cpp +@@ -1,4 +1,5 @@ + #include "ops.h" ++#include "attention-indexed.h" + + #include "ggml-cpu.h" + #include "ggml-impl.h" +@@ -9654,6 +9655,10 @@ static void ggml_compute_forward_flash_attn_ext_f16( + void ggml_compute_forward_flash_attn_ext( + const ggml_compute_params * params, + ggml_tensor * dst) { ++ if (dst->src[5]) { ++ ggml_compute_forward_flash_attn_indexed(params, dst); ++ return; ++ } + switch (dst->op_params[3]) { + case GGML_PREC_DEFAULT: + case GGML_PREC_F32: +diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp +index 81e86b9dd..294d75a23 100644 +--- a/ggml/src/ggml-cpu/spacemit/ime.cpp ++++ b/ggml/src/ggml-cpu/spacemit/ime.cpp +@@ -1626,6 +1626,9 @@ class extra_buffer_type : ggml::cpu::extra_buffer_type { + } + + ggml::cpu::tensor_traits * get_tensor_traits(const ggml_tensor * op) override { ++ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { ++ return nullptr; ++ } + switch (op->op) { + case GGML_OP_MUL_MAT: + case GGML_OP_MUL_MAT_ID: +diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh +index fea1cf9c4..bb8aba163 100644 +--- a/ggml/src/ggml-cuda/common.cuh ++++ b/ggml/src/ggml-cuda/common.cuh +@@ -1282,6 +1282,7 @@ struct ggml_cuda_graph { + struct node_properties { + ggml_tensor node; + void * node_src_data_ptrs[GGML_MAX_SRC]; ++ ggml_type node_src_types[GGML_MAX_SRC]; + int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS]; + size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS]; + }; +diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh +index 41d948335..dd38e078e 100644 +--- a/ggml/src/ggml-cuda/fattn-common.cuh ++++ b/ggml/src/ggml-cuda/fattn-common.cuh +@@ -3,6 +3,7 @@ + #include "common.cuh" + #include "convert.cuh" + #include "vecdotq.cuh" ++#include "fattn-indexed.cuh" + + #include + +@@ -18,6 +19,19 @@ + // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . + #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) + ++// Optional request-local logical-to-physical rows. The dense/null descriptor ++// retains the original FA path; indexed metadata never selects sparse mask scan. ++struct ggml_cuda_fattn_indexed { ++ const int32_t * indices = nullptr; ++ const int32_t * lengths = nullptr; ++ int32_t physical_rows = 0; ++ int32_t sequences = 0; ++ int64_t index_stride = 0; ++ int64_t length_stride = 0; ++ ggml_type type_K = GGML_TYPE_F16; ++ ggml_type type_V = GGML_TYPE_F16; ++}; ++ + typedef void (* fattn_kernel_t)( + const char * __restrict__ Q, + const char * __restrict__ K, +@@ -39,7 +53,8 @@ typedef void (* fattn_kernel_t)( + const int32_t nb11, const int32_t nb12, const int64_t nb13, + const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t ne31, const int32_t ne32, const int32_t ne33, +- const int32_t nb31, const int32_t nb32, const int64_t nb33); ++ const int32_t nb31, const int32_t nb32, const int64_t nb33, ++ const ggml_cuda_fattn_indexed indexed); + + typedef float (*vec_dot_KQ_t)( + const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); +@@ -737,7 +752,8 @@ static __global__ void flash_attn_stream_k_fixup_uniform( + const int blocks_per_tile, + const uint3 fd_iter_j_z_ne12, + const uint3 fd_iter_j_z, +- const uint3 fd_iter_j) { ++ const uint3 fd_iter_j, ++ const ggml_cuda_fattn_indexed indexed) { + constexpr int ncols = ncols1*ncols2; + ggml_cuda_pdl_lc(); + float * GGML_CUDA_RESTRICT dst = dst_ptr; +@@ -805,7 +821,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform( + } + + // Write back final result: +- *dst = dst_val / rowsum; ++ *dst = indexed.indices && rowsum == 0.0f ? 0.0f : dst_val / rowsum; + } + + // General fixup kernel for the case where the number of blocks per tile is not uniform across tiles +@@ -821,7 +837,8 @@ static __global__ void flash_attn_stream_k_fixup_general( + const uint3 fd_iter_k_j_z_ne12, + const uint3 fd_iter_k_j_z, + const uint3 fd_iter_k_j, +- const uint3 fd_iter_k) { ++ const uint3 fd_iter_k, ++ const ggml_cuda_fattn_indexed indexed) { + float * GGML_CUDA_RESTRICT dst = dst_ptr; + const float2 * GGML_CUDA_RESTRICT dst_fixup = dst_fixup_ptr; + constexpr int ncols = ncols1*ncols2; +@@ -916,7 +933,7 @@ static __global__ void flash_attn_stream_k_fixup_general( + } + + // Write back final result: +- *dst = dst_val / rowsum; ++ *dst = indexed.indices && rowsum == 0.0f ? 0.0f : dst_val / rowsum; + } + + template // D == head size +@@ -925,7 +942,8 @@ static __global__ void flash_attn_combine_results( + const float * VKQ_parts_ptr, + const float2 * VKQ_meta_ptr, + float * dst_ptr, +- const int parallel_blocks) { ++ const int parallel_blocks, ++ const ggml_cuda_fattn_indexed indexed) { + ggml_cuda_pdl_lc(); + const float * GGML_CUDA_RESTRICT VKQ_parts = VKQ_parts_ptr; + const float2 * GGML_CUDA_RESTRICT VKQ_meta = VKQ_meta_ptr; +@@ -974,7 +992,7 @@ static __global__ void flash_attn_combine_results( + VKQ_denominator += KQ_max_scale * meta[l].y; + } + +- dst[tid] = VKQ_numerator / VKQ_denominator; ++ dst[tid] = indexed.indices && VKQ_denominator == 0.0f ? 0.0f : VKQ_numerator / VKQ_denominator; + } + + template +@@ -993,6 +1011,21 @@ void launch_fattn( + + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; ++ const ggml_tensor * row_indices = dst->src[5]; ++ const ggml_tensor * row_lengths = dst->src[6]; ++ ggml_cuda_fattn_indexed indexed; ++ if (row_indices) { ++ GGML_ASSERT(row_lengths && !use_sparse); ++ GGML_ASSERT(row_indices->ne[1] == 1 && row_indices->ne[2] == 1); ++ indexed.indices = (const int32_t *) row_indices->data; ++ indexed.lengths = (const int32_t *) row_lengths->data; ++ indexed.physical_rows = K->ne[1]; ++ indexed.type_K = K->type; ++ indexed.type_V = V->type; ++ indexed.sequences = row_indices->ne[3]; ++ indexed.index_stride = row_indices->nb[3] / sizeof(int32_t); ++ indexed.length_stride = row_lengths->nb[3] / sizeof(int32_t); ++ } + + ggml_tensor * KQV = dst; + +@@ -1012,7 +1045,7 @@ void launch_fattn( + const int nsm = ggml_cuda_info().devices[id].nsm; + + const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra = +- ggml_cuda_flash_attn_ext_get_f16_extra_data(KQV, need_f16_K, need_f16_V); ++ ggml_cuda_flash_attn_ext_get_f16_extra_data(KQV, need_f16_K && !row_indices, need_f16_V && !row_indices); + + ggml_cuda_pool_alloc KV_max(pool); + ggml_cuda_pool_alloc dst_tmp(pool); +@@ -1028,7 +1061,7 @@ void launch_fattn( + size_t nb22 = V->nb[2]; + size_t nb23 = V->nb[3]; + +- if (need_f16_K && K->type != GGML_TYPE_F16) { ++ if (!row_indices && need_f16_K && K->type != GGML_TYPE_F16) { + const size_t bs = ggml_blck_size(K->type); + const size_t ts = ggml_type_size(K->type); + +@@ -1056,7 +1089,7 @@ void launch_fattn( + K_data = (char *) K_f16; + } + +- if (need_f16_V && V->type != GGML_TYPE_F16) { ++ if (!row_indices && need_f16_V && V->type != GGML_TYPE_F16) { + if (V_is_K_view) { + V_data = K_data; + nb21 = nb11; +@@ -1114,7 +1147,7 @@ void launch_fattn( + // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. + // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or + // multiple sequences of possibly different lengths. +- const bool scan_mask = !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); ++ const bool scan_mask = !row_indices && !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); + if (scan_mask) { + const int64_t s31 = mask->nb[1] / sizeof(half2); + const int64_t s33 = mask->nb[3] / sizeof(half2); +@@ -1138,7 +1171,7 @@ void launch_fattn( + GGML_ASSERT(max_blocks_per_sm > 0); + int parallel_blocks = max_blocks_per_sm; + +- const int64_t n_kv = use_sparse ? n_kv_max : K->ne[1]; ++ const int64_t n_kv = row_indices ? row_indices->ne[0] : (use_sparse ? n_kv_max : K->ne[1]); + const int ntiles_KV = (n_kv + nbatch_fa - 1) / nbatch_fa; // Max. number of parallel blocks limited by KV cache length. + + dim3 blocks_num; +@@ -1261,7 +1294,8 @@ void launch_fattn( + K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, + nb21, nb22, nb23, + mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, +- mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 ++ mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, ++ indexed + ); + CUDA_CHECK(cudaGetLastError()); + +@@ -1282,7 +1316,7 @@ void launch_fattn( + ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_uniform, launch_params, + (float *) KQV->data, dst_tmp_meta.ptr, + Q->ne[1], Q->ne[2], K->ne[2], nblocks_sk, +- gqa_ratio, bpt, fd0, fd1, fd2); ++ gqa_ratio, bpt, fd0, fd1, fd2, indexed); + } else if (ntiles_dst % blocks_num.x != 0) { + // General fixup for the cases where nblocks_stream_k < ntiles_dst. + const int total_work = ntiles_KV * ntiles_dst; +@@ -1299,7 +1333,7 @@ void launch_fattn( + ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_general, launch_params, + (float *) KQV->data, dst_tmp_meta.ptr, + Q->ne[1], Q->ne[2], gqa_ratio, total_work, +- fd_k_j_z_ne12, fd_k_j_z, fd_k_j, fd_k); ++ fd_k_j_z_ne12, fd_k_j_z, fd_k_j, fd_k, indexed); + } + } else if (parallel_blocks > 1) { + const dim3 block_dim_combine(DV, 1, 1); +@@ -1308,7 +1342,7 @@ void launch_fattn( + + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream); + ggml_cuda_kernel_launch(flash_attn_combine_results, launch_params, +- dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks); ++ dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks, indexed); + } + CUDA_CHECK(cudaGetLastError()); + } +diff --git a/ggml/src/ggml-cuda/fattn-indexed.cuh b/ggml/src/ggml-cuda/fattn-indexed.cuh +new file mode 100644 +index 000000000..c1d2fafdc +--- /dev/null ++++ b/ggml/src/ggml-cuda/fattn-indexed.cuh +@@ -0,0 +1,45 @@ ++#pragma once ++ ++#include "dequantize.cuh" ++ ++// A physical head view. Quantized row strides are byte strides (not half2 ++// strides: e.g. a 96-element Q4_0 row occupies 54 bytes). ++struct ggml_cuda_fattn_row { ++ const char * data = nullptr; ++ int64_t stride = 0; ++ ggml_type type = GGML_TYPE_F16; ++}; ++ ++static __device__ __forceinline__ half ggml_cuda_fattn_read_half( ++ const ggml_cuda_fattn_row row, const int physical, const int element) { ++ const char * src = row.data + int64_t(physical)*row.stride; ++ if (row.type == GGML_TYPE_F16) { ++ return ((const half *) src)[element]; ++ } ++ if (row.type == GGML_TYPE_F32) { ++ return __float2half(((const float *) src)[element]); ++ } ++ if (row.type == GGML_TYPE_BF16) { ++ const uint32_t bits = uint32_t(((const uint16_t *) src)[element]) << 16; ++ return __float2half(__uint_as_float(bits)); ++ } ++ float2 value; ++ const int block = element / 32; ++ const int offset = element % 32; ++ switch (row.type) { ++ case GGML_TYPE_Q4_0: dequantize_q4_0(src, block, offset % 16, value); break; ++ case GGML_TYPE_Q4_1: dequantize_q4_1(src, block, offset % 16, value); break; ++ case GGML_TYPE_Q5_0: dequantize_q5_0(src, block, offset % 16, value); break; ++ case GGML_TYPE_Q5_1: dequantize_q5_1(src, block, offset % 16, value); break; ++ case GGML_TYPE_Q8_0: dequantize_q8_0(src, block, offset & ~1, value); break; ++ default: return __float2half(0.0f); // Rejected by host admission. ++ } ++ return __float2half(row.type == GGML_TYPE_Q8_0 ? ++ (offset & 1 ? value.y : value.x) : (offset >= 16 ? value.y : value.x)); ++} ++ ++static __device__ __forceinline__ half2 ggml_cuda_fattn_read_half2( ++ const ggml_cuda_fattn_row row, const int physical, const int element) { ++ return __halves2half2(ggml_cuda_fattn_read_half(row, physical, element), ++ ggml_cuda_fattn_read_half(row, physical, element + 1)); ++} +diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh +index 296aa2b34..a12a21093 100644 +--- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh ++++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh +@@ -383,7 +383,25 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages( + template + static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV, +- const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { ++ const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices, ++ const int physical_rows, const ggml_cuda_fattn_row row = {}) { ++ // Decode only the selected physical rows into the original MMA shared tile. ++ // The F16 branch below retains its original vectorized/cp.async loads. ++ if (row.data && row.type != GGML_TYPE_F16) { ++ const int element0 = int(((const char *) KV - row.data) / sizeof(half)); ++ constexpr int warp_size = ggml_cuda_get_physical_warp_size(); ++ const int tid = threadIdx.y*warp_size + threadIdx.x; ++ for (int x = tid; x < nbatch_fa*D2; x += nwarps*warp_size) { ++ const int i = x / D2; ++ const int k = x % D2; ++ const int logical = k_VKQ_0 + i; ++ const int physical = i < i_sup ? (indices ? indices[logical] : logical) : -1; ++ const half2 value = physical >= 0 && physical < physical_rows ? ++ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*k) : make_half2(0.0f, 0.0f); ++ *swizzle(tile_KV, i*stride_tile + k, i) = value; ++ } ++ return; ++ } + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + // K/V data is loaded with decreasing granularity for D for better memory bandwidth. + // The minimum granularity is 16 bytes. +@@ -420,6 +438,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + // padded slots gather row 0, the -inf mask removes their contribution + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; + i_KV = index >= 0 ? index : 0; ++ } else if (indices) { ++ const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; ++ i_KV = index >= 0 && index < physical_rows ? index : -1; + } else { + i_KV = k_VKQ_0 + i; + } +@@ -428,7 +449,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { + const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); + +- cp_async_cg_16(tile_KV_32 + swizzle(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk); ++ if (i_KV >= 0) { ++ cp_async_cg_16(tile_KV_32 + swizzle(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk); ++ } else { ++ auto * target = swizzle(tile_KV, i*stride_tile + k*h2_per_chunk, i); ++ *reinterpret_cast(target) = make_uint4(0, 0, 0, 0); ++ } + } + } + }; +@@ -467,6 +493,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + if constexpr (use_sparse) { + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; + src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; ++ } else if (indices) { ++ const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; ++ src = index >= 0 && index < physical_rows ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; + } else { + src = !oob_check || i < i_sup ? KV + int64_t(k_VKQ_0 + i)*stride_KV + k*h2_per_chunk : zero; + } +@@ -600,7 +629,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + float * const __restrict__ KQ_rowsum, + const int jt, + const int kb0, +- const int k_VKQ_sup) { ++ const int k_VKQ_sup, ++ const int physical_rows, ++ const int logical_rows, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V) { + #if defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int ncols = ncols1 * ncols2; +@@ -634,7 +665,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + cp_async_wait_all(); + __syncthreads(); + flash_attn_ext_f16_load_tile +- (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, nullptr); ++ (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_V); + } else { + // the sparse mask values are gathered per element, always load them synchronously + constexpr bool use_cp_async = nstages == 1 && !use_sparse; +@@ -654,7 +685,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + const int k0_diff = k0_stop - k0_start; + constexpr bool use_cp_async = nstages == 1; + flash_attn_ext_f16_load_tile +- (K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices); ++ (K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_K); + if (use_cp_async) { + cp_async_wait_all(); + } +@@ -991,7 +1022,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + (mask_h, tile_mask, stride_mask, k_VKQ_0 + nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); + } + flash_attn_ext_f16_load_tile +- (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, nullptr); ++ (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, ++ indices && !use_sparse ? min(nbatch_fa, max(0, logical_rows - k_VKQ_0 - nbatch_fa)) : k_VKQ_sup, ++ indices, physical_rows, row_K); + } + } + +@@ -1007,7 +1040,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + if (!V_is_K_view || i0_stop > 2*nbatch_K2) { + constexpr bool use_cp_async = nstages == 1; + flash_attn_ext_f16_load_tile +- (V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices); ++ (V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_V); + if (use_cp_async) { + cp_async_wait_all(); + } +@@ -1066,7 +1099,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + scale, slope, logit_softcap, ne01, ne02, + stride_K, stride_V, stride_mask, + tile_Q, tile_K, tile_V, tile_mask, +- Q_B, VKQ_C, KQ_max, KQ_rowsum, kb0); ++ Q_B, VKQ_C, KQ_max, KQ_rowsum, kb0, physical_rows, logical_rows, row_K, row_V); + NO_DEVICE_CODE; + #endif // defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) + } +@@ -1211,7 +1244,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + const int jt, + const int zt_gqa, + const int kb0_start, +- const int kb0_stop) { ++ const int kb0_stop, ++ const int physical_rows, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V) { + #if defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) + //In this kernel Q, K, V are matrices while i, j, k are matrix indices. + +@@ -1331,62 +1365,66 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + + int kb0 = kb0_start; + +- // Preload mask and K data for first iteration when using cp_async with multiple stages: +- if constexpr (nstages > 1) { +- static_assert(!use_sparse, "sparse gather not implemented for multi-stage loading"); +- static_assert(nbatch_K2 == DKQ/2, "batching not implemented for multi-stage pipeline"); +- constexpr bool use_cp_async = true; +- constexpr bool oob_check = false; +- constexpr int k_VKQ_sup = nbatch_fa; +- if (ncols2 > 1 || mask_h) { +- flash_attn_ext_f16_load_mask +- (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); ++ // Empty request-local intervals still execute the original output/fixup ++ // epilogue, but must not issue an unconditional final K/V iteration. ++ if (kb0_start < kb0_stop) { ++ // Preload mask and K data for first iteration when using cp_async with multiple stages: ++ if constexpr (nstages > 1) { ++ static_assert(!use_sparse, "sparse gather not implemented for multi-stage loading"); ++ static_assert(nbatch_K2 == DKQ/2, "batching not implemented for multi-stage pipeline"); ++ constexpr bool use_cp_async = true; ++ constexpr bool oob_check = false; ++ const int k_VKQ_sup = indices && !use_sparse ? min(nbatch_fa, max(0, ne11 - kb0*nbatch_fa)) : nbatch_fa; ++ if (ncols2 > 1 || mask_h) { ++ flash_attn_ext_f16_load_mask ++ (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); ++ } ++ flash_attn_ext_f16_load_tile ++ (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, indices, physical_rows, row_K); + } +- flash_attn_ext_f16_load_tile +- (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, nullptr); +- } + +- // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. +- if constexpr (ncols2 == 1 || use_sparse) { +- constexpr bool oob_check = true; +- for (; kb0 < kb0_stop-1; ++kb0) { +- constexpr bool last_iter = false; +- constexpr int k_VKQ_sup = nbatch_fa; ++ // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. ++ if constexpr (ncols2 == 1 || use_sparse) { ++ constexpr bool oob_check = true; ++ for (; kb0 < kb0_stop-1; ++kb0) { ++ constexpr bool last_iter = false; ++ constexpr int k_VKQ_sup = nbatch_fa; ++ flash_attn_ext_f16_iter ++ ++ (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ++ ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, ++ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); ++ } ++ constexpr bool last_iter = true; ++ const int k_VKQ_sup = ne11 - kb0*nbatch_fa; + flash_attn_ext_f16_iter + ++ T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ> + (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, + ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, +- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); +- } +- constexpr bool last_iter = true; +- const int k_VKQ_sup = ne11 - kb0*nbatch_fa; +- flash_attn_ext_f16_iter +- +- (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, +- ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, +- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); +- } else { +- constexpr bool oob_check = false; +- for (; kb0 < kb0_stop-1; ++kb0) { +- constexpr bool last_iter = false; +- constexpr int k_VKQ_sup = nbatch_fa; ++ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); ++ } else { ++ constexpr bool oob_check = false; ++ for (; kb0 < kb0_stop-1; ++kb0) { ++ constexpr bool last_iter = false; ++ constexpr int k_VKQ_sup = nbatch_fa; ++ flash_attn_ext_f16_iter ++ ++ (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ++ ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, ++ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); ++ } ++ constexpr bool last_iter = true; ++ const int k_VKQ_sup = indices && !use_sparse ? min(nbatch_fa, max(0, ne11 - kb0*nbatch_fa)) : nbatch_fa; + flash_attn_ext_f16_iter + + (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, + ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, +- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); ++ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); + } +- constexpr bool last_iter = true; +- constexpr int k_VKQ_sup = nbatch_fa; +- flash_attn_ext_f16_iter +- +- (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, +- ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, +- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); + } + + // With multi-stage loading there is no __syncthreads at the end of the iter, +@@ -1426,7 +1464,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + // If attention sinks are used, potentially re-scale if KQ_max is small. + // Also add the sink as a value to KQ_rowsum, this is done after synchronization of KQ_rowsum + // so it's being done unconditionally for every thread. +- if (!is_fixup && (np == 1 || threadIdx.y % np == 0) && sinks_f) { ++ if (!is_fixup && (np == 1 || threadIdx.y % np == 0) && sinks_f && ++ (physical_rows == INT32_MAX || ne11 != 0)) { + float KQ_max_scale[cols_per_thread]; + #pragma unroll + for (int col = 0; col < cols_per_thread; ++col) { +@@ -1759,8 +1798,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + + if (!needs_fixup && !is_fixup) { + const float KQ_rowsum_j = meta_j[1]; +- dstk_val.x /= KQ_rowsum_j; +- dstk_val.y /= KQ_rowsum_j; ++ if (physical_rows != INT32_MAX && KQ_rowsum_j == 0.0f) { ++ dstk_val = make_float2(0.0f, 0.0f); ++ } else { ++ dstk_val.x /= KQ_rowsum_j; ++ dstk_val.y /= KQ_rowsum_j; ++ } + } + + if (is_fixup) { +@@ -1780,7 +1823,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dstk_fixup, + scale, slope, logit_softcap, ne01, ne02, gqa_ratio, + stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, +- jt, kb0_start, kb0_stop); ++ jt, kb0_start, kb0_stop, physical_rows, row_K, row_V); + NO_DEVICE_CODE; + #endif // defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) + } +@@ -1816,7 +1859,8 @@ static __global__ void flash_attn_ext_f16( + const int32_t nb11, const int32_t nb12, const int64_t nb13, + const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t ne31, const int32_t ne32, const int32_t ne33, +- const int32_t nb31, const int32_t nb32, const int64_t nb33) { ++ const int32_t nb31, const int32_t nb32, const int64_t nb33, ++ const ggml_cuda_fattn_indexed indexed) { + ggml_cuda_pdl_sync(); // TODO optimize placement + #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) + const char * GGML_CUDA_RESTRICT Q = Q_ptr; +@@ -1917,14 +1961,20 @@ static __global__ void flash_attn_ext_f16( + const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. + + const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); +- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); +- const half * mask_h = ncols2 == 1 && !mask ? nullptr : ++ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; ++ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*z_KV); ++ const half * mask_h = !mask ? nullptr : + (const half *) (mask + nb33*(sequence % ne33)); + float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); + +- const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); ++ const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*kv_sequence + nb22*z_KV); ++ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; ++ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; + const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; +- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; ++ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; ++ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : ++ (indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr); ++ const int live_n_kv = indexed.indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; + + const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + +@@ -1933,17 +1983,24 @@ static __global__ void flash_attn_ext_f16( + } else if (KV_max) { + kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); + } ++ if (indexed.indices) { ++ kb0_stop = min(kb0_stop, (live_n_kv + nbatch_fa - 1) / nbatch_fa); ++ } + constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. + if (kb0_start == 0) { + constexpr bool needs_fixup = false; // CUDA block is working on an entire tile. + flash_attn_ext_f16_process_tile + (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, +- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); ++ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, ++ indexed.indices ? indexed.physical_rows : INT32_MAX, ++ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); + } else { + constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile. + flash_attn_ext_f16_process_tile + (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, +- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); ++ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, ++ indexed.indices ? indexed.physical_rows : INT32_MAX, ++ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); + } + + kbc += iter_k; +@@ -1966,14 +2023,20 @@ static __global__ void flash_attn_ext_f16( + const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. + + const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); +- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); +- const half * mask_h = ncols2 == 1 && !mask ? nullptr : ++ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; ++ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*z_KV); ++ const half * mask_h = !mask ? nullptr : + (const half *) (mask + nb33*(sequence % ne33)); + float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); + +- const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); ++ const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*kv_sequence + nb22*z_KV); ++ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; ++ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; + const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; +- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; ++ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; ++ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : ++ (indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr); ++ const int live_n_kv = indexed.indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; + + const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + +@@ -1982,12 +2045,17 @@ static __global__ void flash_attn_ext_f16( + } else if (KV_max) { + kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); + } ++ if (indexed.indices) { ++ kb0_stop = min(kb0_stop, (live_n_kv + nbatch_fa - 1) / nbatch_fa); ++ } + + constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. + constexpr bool needs_fixup = false; + flash_attn_ext_f16_process_tile + (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, +- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); ++ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, ++ indexed.indices ? indexed.physical_rows : INT32_MAX, ++ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); + #else + GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, + max_bias, m0, m1, n_head_log2, logit_softcap, +@@ -1997,7 +2065,7 @@ static __global__ void flash_attn_ext_f16( + nb11, nb12, nb13, + nb21, nb22, nb23, + ne31, ne32, ne33, +- nb31, nb32, nb33); ++ nb31, nb32, nb33, indexed); + NO_DEVICE_CODE; + #endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) + } +diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh +index b5ea915e1..8a1474017 100644 +--- a/ggml/src/ggml-cuda/fattn-tile.cuh ++++ b/ggml/src/ggml-cuda/fattn-tile.cuh +@@ -376,7 +376,23 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, + // TODO: deduplicate with mma-f16 + template + static __device__ __forceinline__ void flash_attn_tile_load_tile( +- const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { ++ const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, ++ const ggml_cuda_fattn_row row = {}, const int32_t * indices = nullptr, ++ const int logical0 = 0, const int element0 = 0, const int physical_rows = 0) { ++ if (indices) { ++ if constexpr (J >= 2) { ++ const int tid = threadIdx.y*warp_size + threadIdx.x; ++ for (int x = tid; x < I*(J/2); x += nwarps*warp_size) { ++ const int i = x / (J/2); ++ const int j = x % (J/2); ++ const int physical = i < i_sup ? indices[logical0 + i] : -1; ++ const half2 value = physical >= 0 && physical < physical_rows ? ++ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*j) : make_half2(0.0f, 0.0f); ++ tile_KV[i*(J/2 + J_padding) + j] = value; ++ } ++ } ++ return; ++ } + constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_ne = cpy_nb / 4; + +@@ -426,7 +442,25 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( + + template + static __device__ __forceinline__ void flash_attn_tile_load_tile( +- const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { ++ const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, ++ const ggml_cuda_fattn_row row = {}, const int32_t * indices = nullptr, ++ const int logical0 = 0, const int element0 = 0, const int physical_rows = 0) { ++ if (indices) { ++ if constexpr (J >= 2) { ++ const int tid = threadIdx.y*warp_size + threadIdx.x; ++ for (int x = tid; x < I*(J/2); x += nwarps*warp_size) { ++ const int i = x / (J/2); ++ const int j = x % (J/2); ++ const int physical = i < i_sup ? indices[logical0 + i] : -1; ++ const half2 value = physical >= 0 && physical < physical_rows ? ++ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*j) : make_half2(0.0f, 0.0f); ++ const float2 f = __half22float2(value); ++ tile_KV[i*(J + J_padding) + 2*j] = f.x; ++ tile_KV[i*(J + J_padding) + 2*j + 1] = f.y; ++ } ++ } ++ return; ++ } + constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_ne = cpy_nb / 4; + +@@ -490,7 +524,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( + const int k_VKQ_0, + const int k_VKQ_sup, + const int k_KQ_0, +- float * KQ_acc) { ++ float * KQ_acc, const ggml_cuda_fattn_row row_K, const int32_t * indices, const int physical_rows) { + constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_ne = cpy_nb / 4; + +@@ -499,7 +533,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( + constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column + + flash_attn_tile_load_tile +- (K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup); ++ (indices ? K_h2 : K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, row_K, indices, k_VKQ_0, k_KQ_0, physical_rows); + __syncthreads(); + + #ifdef FAST_FP16_AVAILABLE +@@ -575,7 +609,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( + T_acc * const VKQ, + const int k_VKQ_0, + const int k_VKQ_max, +- const int col_Q_0) { ++ const int col_Q_0, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V, ++ const int32_t * indices, const int physical_rows) { + constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_ne = cpy_nb / 4; + +@@ -608,12 +643,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter( + #pragma unroll + for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) { + flash_attn_tile_iter_KQ( +- Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); ++ Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, row_K, indices, physical_rows); + } + if (nbatch_K_last > 0) { + constexpr int k_KQ_0 = DKQ - nbatch_K_last; + flash_attn_tile_iter_KQ( +- Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); ++ Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, row_K, indices, physical_rows); + } + + // Apply logit softcap + mask, update KQ_max: +@@ -719,7 +754,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( + #pragma unroll + for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { + flash_attn_tile_load_tile +- (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); ++ (indices ? V_h2 : V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0, row_V, indices, k_VKQ_0 + k0, 0, physical_rows); + __syncthreads(); + + #ifdef FAST_FP16_AVAILABLE +@@ -811,7 +846,9 @@ static __global__ void flash_attn_tile( + const int32_t nb11, const int32_t nb12, const int64_t nb13, + const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t ne31, const int32_t ne32, const int32_t ne33, +- const int32_t nb31, const int32_t nb32, const int64_t nb33) { ++ const int32_t nb31, const int32_t nb32, const int64_t nb33, ++ const ggml_cuda_fattn_indexed indexed) { ++ + #ifdef FLASH_ATTN_AVAILABLE + const char * GGML_CUDA_RESTRICT Q = Q_ptr; + const char * GGML_CUDA_RESTRICT K = K_ptr; +@@ -833,7 +870,7 @@ static __global__ void flash_attn_tile( + nb11, nb12, nb13, + nb21, nb22, nb23, + ne31, ne32, ne33, +- nb31, nb32, nb33); ++ nb31, nb32, nb33, indexed); + NO_DEVICE_CODE; + return; + } +@@ -854,11 +891,17 @@ static __global__ void flash_attn_tile( + const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) + const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. + const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); +- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio)); +- const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape ++ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; ++ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*(head0 / gqa_ratio)); ++ const half2 * V_h2 = (const half2 *) (V + nb23*kv_sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape + + const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33)) : nullptr; + ++ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; ++ const int32_t * indices = indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr; ++ const int live_n_kv = indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; ++ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; ++ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; + const int stride_K2 = nb11 / sizeof(half2); + const int stride_V2 = nb21 / sizeof(half2); + const int stride_mask = nb31 / sizeof(half); +@@ -951,22 +994,22 @@ static __global__ void flash_attn_tile( + __syncthreads(); + + // Main loop over KV cache: +- const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; +- if (ncols2 == 1) { ++ const int k_VKQ_max = indices ? live_n_kv : (KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11); ++ if (ncols2 == 1 || indices) { + // Branch with out-of-bounds checks. + int k_VKQ_0 = blockIdx.y*nbatch_fa; + while (k_VKQ_0 < k_VKQ_max - nbatch_fa) { + constexpr bool oob_check = false; + flash_attn_tile_iter + (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, +- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); ++ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); + k_VKQ_0 += gridDim.y*nbatch_fa; + } + if (k_VKQ_0 < k_VKQ_max) { + constexpr bool oob_check = true; + flash_attn_tile_iter + (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, +- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); ++ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); + } + } else { + // Branch without out-of-bounds checks. +@@ -974,7 +1017,7 @@ static __global__ void flash_attn_tile( + constexpr bool oob_check = false; + flash_attn_tile_iter + (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, +- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); ++ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); + } + } + +@@ -1050,7 +1093,7 @@ static __global__ void flash_attn_tile( + } + + // Attention sink: adjust KQ max and sum only for the first of all parallel blocks: +- if (sinks && blockIdx.y == 0) { ++ if (sinks && blockIdx.y == 0 && (!indices || live_n_kv != 0)) { + #pragma unroll + for (int jc0 = 0; jc0 < cpw; ++jc0) { + const int jc = jc0 + (threadIdx.y/np)*cpw; +@@ -1091,7 +1134,7 @@ static __global__ void flash_attn_tile( + return; + } + +- const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f; ++ const float scale = indices && KQ_sum[jc0] == 0.0f ? 0.0f : (gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f); + + const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y; + +@@ -1140,7 +1183,7 @@ static __global__ void flash_attn_tile( + nb11, nb12, nb13, + nb21, nb22, nb23, + ne31, ne32, ne33, +- nb31, nb32, nb33); ++ nb31, nb32, nb33, indexed); + NO_DEVICE_CODE; + #endif // FLASH_ATTN_AVAILABLE + } +@@ -1221,7 +1264,9 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm + } + + if constexpr (ncols2 <= 2) { +- constexpr int cols_per_block = 2; ++ // The wide indexed nonalias path has a valid four-column config, ++ // including when only one request query is live. ++ constexpr int cols_per_block = DKQ == 576 ? 4 : 2; + const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; + const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); + fattn_kernel_t fattn_kernel = flash_attn_tile; +@@ -1250,7 +1295,7 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm + // However, for DKQ == 576, DV == 512 only the kernel variant with GQA optimizations is implemented. + const bool nvidia = GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[ggml_cuda_get_device()].cc); + const int gqa_limit = nvidia && gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX; +- const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; + + if constexpr (DKQ == 320) { + // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. +@@ -1272,6 +1317,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm + } + + if constexpr (DKQ == 576) { ++ if (dst->src[5]) { ++ // Independent V pools cannot use the MLA K-tile alias. Group one ++ // head at a time so every admitted GQA ratio (including two) works. ++ launch_fattn_tile_switch_ncols1(ctx, dst); ++ return; ++ } + if (use_gqa_opt && gqa_ratio % 16 == 0) { + launch_fattn_tile_switch_ncols1(ctx, dst); + return; +diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh +index 57a285565..596165504 100644 +--- a/ggml/src/ggml-cuda/fattn-vec.cuh ++++ b/ggml/src/ggml-cuda/fattn-vec.cuh +@@ -39,7 +39,9 @@ static __global__ void flash_attn_ext_vec( + const int32_t nb11, const int32_t nb12, const int64_t nb13, + const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t ne31, const int32_t ne32, const int32_t ne33, +- const int32_t nb31, const int32_t nb32, const int64_t nb33) { ++ const int32_t nb31, const int32_t nb32, const int64_t nb33, ++ const ggml_cuda_fattn_indexed indexed) { ++ + ggml_cuda_pdl_lc(); + #ifdef FLASH_ATTN_AVAILABLE + const char * GGML_CUDA_RESTRICT Q = Q_ptr; +@@ -61,7 +63,7 @@ static __global__ void flash_attn_ext_vec( + nb11, nb12, nb13, + nb21, nb22, nb23, + ne31, ne32, ne33, +- nb31, nb32, nb33); ++ nb31, nb32, nb33, indexed); + NO_DEVICE_CODE; + return; + } +@@ -107,10 +109,10 @@ static __global__ void flash_attn_ext_vec( + const int head = blockIdx.z - sequence*ne02; + const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. + Q += nb03*sequence + nb02* head + nb01*ic0; +- K += nb13*sequence + nb12*(head / gqa_ratio); +- V += nb23*sequence + nb22*(head / gqa_ratio); ++ K += nb13*(indexed.indices ? sequence % ne13 : sequence) + nb12*(head / gqa_ratio); ++ V += nb23*(indexed.indices ? sequence % ne13 : sequence) + nb22*(head / gqa_ratio); + +- const half * maskh = (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0); ++ const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0) : nullptr; + + const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); + +@@ -247,13 +249,16 @@ static __global__ void flash_attn_ext_vec( + #endif // V_DOT2_F32_F16_AVAILABLE + } + +- const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; +- K += blockIdx.y*nthreads * nb11; +- V += blockIdx.y*nthreads * nb21; +- maskh += blockIdx.y*nthreads; ++ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; ++ const int32_t * indices = indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr; ++ const int live_n_kv = indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; ++ const int k_VKQ_max = indices ? live_n_kv : (KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11); ++ K += indices ? 0 : blockIdx.y*nthreads * nb11; ++ V += indices ? 0 : blockIdx.y*nthreads * nb21; ++ maskh = mask ? maskh + blockIdx.y*nthreads : nullptr; + for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, + // Increment pointers after each loop: +- K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { ++ K += indices ? 0 : gridDim.y*nthreads*nb11, V += indices ? 0 : gridDim.y*nthreads*nb21, maskh = mask ? maskh + gridDim.y*nthreads : nullptr) { + + // Calculate KQ tile and keep track of new maximum KQ values: + float KQ_reg[ncols]; // KQ in registers. +@@ -270,7 +275,9 @@ static __global__ void flash_attn_ext_vec( + + #pragma unroll + for (int j = 0; j < ncols; ++j) { +- float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); ++ const int physical = indices ? (k_VKQ_0 + i_KQ < live_n_kv ? indices[k_VKQ_0 + i_KQ] : -1) : i_KQ; ++ const bool valid = !indices || (physical >= 0 && physical < indexed.physical_rows); ++ float sum = valid ? vec_dot_KQ(K + int64_t(physical)*nb11, Q_reg[j], Q_i32[j], Q_ds[j]) : 0.0f; + sum = warp_reduce_sum(sum); + + if (use_logit_softcap) { +@@ -281,6 +288,9 @@ static __global__ void flash_attn_ext_vec( + sum += slope*__half2float(maskh[j*ne11 + i_KQ]); + } + ++ if (!valid) { ++ sum = -INFINITY; ++ } + KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); + + if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { +@@ -322,6 +332,9 @@ static __global__ void flash_attn_ext_vec( + #pragma unroll + for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { + const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); ++ const int physical = indices ? (k_VKQ_0 + k < live_n_kv ? indices[k_VKQ_0 + k] : -1) : k; ++ const bool valid = !indices || (physical >= 0 && physical < indexed.physical_rows); ++ const char * V_row = valid ? V + int64_t(physical)*nb21 : V; + + #ifdef V_DOT2_F32_F16_AVAILABLE + half2 KQ_k[ncols]; +@@ -331,17 +344,17 @@ static __global__ void flash_attn_ext_vec( + } + #pragma unroll + for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { +- half2 tmp[V_rows_per_thread/2]; ++ half2 tmp[V_rows_per_thread/2] = {}; + if constexpr (type_V == GGML_TYPE_BF16) { +- float2 tmp_f[V_rows_per_thread/2]; +- dequantize_V(V + k*nb21, tmp_f, ++ float2 tmp_f[V_rows_per_thread/2] = {}; ++ if (valid) dequantize_V(V_row, tmp_f, + 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); + #pragma unroll + for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { + tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); + } + } else { +- dequantize_V(V + k*nb21, tmp, ++ if (valid) dequantize_V(V_row, tmp, + 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); + } + #pragma unroll +@@ -360,8 +373,8 @@ static __global__ void flash_attn_ext_vec( + } + #pragma unroll + for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { +- float2 tmp[V_rows_per_thread/2]; +- dequantize_V(V + k*nb21, tmp, ++ float2 tmp[V_rows_per_thread/2] = {}; ++ if (valid) dequantize_V(V_row, tmp, + 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); + #pragma unroll + for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { +@@ -376,7 +389,7 @@ static __global__ void flash_attn_ext_vec( + } + } + +- if (sinks && blockIdx.y == 0) { ++ if (sinks && blockIdx.y == 0 && (!indices || live_n_kv != 0)) { + const float sink = ((const float *) sinks)[head]; + + #pragma unroll +@@ -496,7 +509,7 @@ static __global__ void flash_attn_ext_vec( + } + } + if (gridDim.y == 1) { +- dst_val /= KQ_sum[j_VKQ]; ++ dst_val = indices && KQ_sum[j_VKQ] == 0.0f ? 0.0f : dst_val / KQ_sum[j_VKQ]; + } + dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val; + } +@@ -520,7 +533,7 @@ static __global__ void flash_attn_ext_vec( + nb11, nb12, nb13, + nb21, nb22, nb23, + ne31, ne32, ne33, +- nb31, nb32, nb33); ++ nb31, nb32, nb33, indexed); + NO_DEVICE_CODE; + #endif // FLASH_ATTN_AVAILABLE + } +diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu +index 5fa3e5308..3825a51f1 100644 +--- a/ggml/src/ggml-cuda/fattn.cu ++++ b/ggml/src/ggml-cuda/fattn.cu +@@ -130,6 +130,9 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ + GGML_UNUSED_VARS(cc, dst, ncols1, ncols2); + return false; + #else ++ if (dst->src[5]) { ++ return false; // Explicit logical rows bypass mask-derived sparse lists. ++ } + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * mask = dst->src[3]; +@@ -204,7 +207,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con + + // Edge cases like no mask, ALiBi, unpadded K/V, or misaligned addresses for large data transfers + // are put into the template specialization without GQA optimizations. +- bool use_gqa_opt = mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ bool use_gqa_opt = mask && max_bias == 0.0f && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; + for (const ggml_tensor * t : {Q, K, V, mask}) { + if (t == nullptr || ggml_is_quantized(t->type)) { + continue; +@@ -537,6 +540,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { + } + } + ++// The 576/512 MMA specialization reuses the K tile for V. Shape alone does ++// not establish this alias: indexed FA also admits independent physical pools. ++static bool ggml_cuda_fattn_v_aliases_k(const ggml_tensor * K, const ggml_tensor * V) { ++ const bool same_view = V->view_src && ++ ((V->view_src == K && V->view_offs == 0) || ++ (K->view_src && V->view_src == K->view_src && V->view_offs == K->view_offs)); ++ const bool same_data = K->data && V->data && K->data == V->data; ++ if (K->data && V->data && !same_data) { ++ return false; ++ } ++ if ((!same_view && !same_data) || K->type != V->type || V->ne[0] > K->ne[0]) { ++ return false; ++ } ++ for (int i = 0; i < GGML_MAX_DIMS; ++i) { ++ if (K->nb[i] != V->nb[i] || (i != 0 && K->ne[i] != V->ne[i])) { ++ return false; ++ } ++ } ++ return true; ++} ++ + static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { + #ifndef FLASH_ATTN_AVAILABLE + GGML_UNUSED(device); GGML_UNUSED(dst); +@@ -557,7 +581,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const + + // The effective batch size for the kernel can be increased by gqa_ratio. + // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded, +- bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; + for (const ggml_tensor * t : {Q, K, V, mask}) { + if (t == nullptr || ggml_is_quantized(t->type)) { + continue; +@@ -629,9 +653,40 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const + return BEST_FATTN_KERNEL_NONE; + } + ++ if (const ggml_tensor * indices = dst->src[5]) { ++ const ggml_tensor * lengths = dst->src[6]; ++ // Indexed tile/MMA readers decode selected rows directly into shared ++ // tiles, supporting the same mixed KV types without pool conversion. ++ if (!lengths || indices->type != GGML_TYPE_I32 || lengths->type != GGML_TYPE_I32 || ++ !ggml_is_contiguous(indices) || !ggml_is_contiguous(lengths) || ++ indices->ne[0] <= 0 || indices->ne[0] > INT32_MAX || ++ indices->ne[0] % FATTN_KQ_STRIDE != 0 || ++ indices->ne[1] != 1 || indices->ne[2] != 1 || indices->ne[3] <= 0 || ++ lengths->ne[0] != 1 || lengths->ne[1] != 1 || lengths->ne[2] != 1 || ++ lengths->ne[3] != indices->ne[3] || Q->ne[3] % indices->ne[3] != 0 || ++ (mask && mask->ne[0] != indices->ne[0]) || K->ne[1] > INT32_MAX || ++ K->ne[3] != V->ne[3] || Q->ne[3] % K->ne[3] != 0) { ++ return BEST_FATTN_KERNEL_NONE; ++ } ++ if (Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && Q->ne[1] <= 2 && ++ (ggml_is_quantized(K->type) || ggml_is_quantized(V->type)) && ++ K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && ++ ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr) { ++ return BEST_FATTN_KERNEL_VEC; ++ } ++ if (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V)) { ++ return BEST_FATTN_KERNEL_TILE; ++ } ++ if ((turing_mma_available(cc) || volta_mma_available(cc) || amd_mfma_available(cc) || amd_wmma_available(cc)) && ++ Q->ne[0] != 40 && Q->ne[0] != 72) { ++ return BEST_FATTN_KERNEL_MMA_F16; ++ } ++ return BEST_FATTN_KERNEL_TILE; ++ } ++ + // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes: + // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. +- const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; + + // If Turing tensor cores are available, use them: + if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { +@@ -749,7 +804,7 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d + } + + const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra = +- ggml_cuda_flash_attn_ext_get_f16_extra_data(dst, need_f16_K, need_f16_V); ++ ggml_cuda_flash_attn_ext_get_f16_extra_data(dst, need_f16_K && !dst->src[5], need_f16_V && !dst->src[5]); + + return f16_extra.end - (uintptr_t) dst->data; + } +diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu +index aeeb7ee27..09813eb41 100644 +--- a/ggml/src/ggml-cuda/ggml-cuda.cu ++++ b/ggml/src/ggml-cuda/ggml-cuda.cu +@@ -2760,6 +2760,7 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (cgraph->nodes[i]->src[j]) { + prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data; ++ prop.node_src_types[j] = cgraph->nodes[i]->src[j]->type; + memcpy(prop.node_src_ne[j], cgraph->nodes[i]->src[j]->ne, sizeof(prop.node_src_ne[j])); + memcpy(prop.node_src_nb[j], cgraph->nodes[i]->src[j]->nb, sizeof(prop.node_src_nb[j])); + } +diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp +index 54a6d166d..d3677ac92 100644 +--- a/ggml/src/ggml-et/ggml-et.cpp ++++ b/ggml/src/ggml-et/ggml-et.cpp +@@ -1268,6 +1268,9 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm + (op->src[1]->ne[1] % op->src[4]->ne[1] == 0); + break; + case GGML_OP_FLASH_ATTN_EXT: ++ if (op->src[5]) { ++ return false; ++ } + if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && + (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && + (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && +diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp +index 08c15ff78..bbda6f992 100644 +--- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp ++++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp +@@ -9500,7 +9500,7 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons + break; + + case GGML_OP_FLASH_ATTN_EXT: +- supp = ggml_hexagon_supported_flash_attn_ext(sess, op); ++ supp = !op->src[5] && ggml_hexagon_supported_flash_attn_ext(sess, op); + break; + + case GGML_OP_SET_ROWS: +diff --git a/ggml/src/ggml-metal/ggml-metal-attention-indexed.h b/ggml/src/ggml-metal/ggml-metal-attention-indexed.h +new file mode 100644 +index 000000000..04445aada +--- /dev/null ++++ b/ggml/src/ggml-metal/ggml-metal-attention-indexed.h +@@ -0,0 +1,90 @@ ++#pragma once ++ ++#include "ggml.h" ++#include "ggml-metal-impl.h" ++ ++// Request-local physical row lists use the existing attention gather kernels. ++// Keep their admission independent from the mask-scanning sparse hint limits. ++static inline bool ggml_metal_flash_attn_indexed_supported(const struct ggml_tensor * op) { ++ const struct ggml_tensor * indices = op->src[5]; ++ const struct ggml_tensor * lengths = op->src[6]; ++ if (!indices || !lengths || indices->type != GGML_TYPE_I32 || lengths->type != GGML_TYPE_I32 || ++ indices->nb[0] != sizeof(int32_t) || lengths->ne[0] != 1 || ++ op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != op->src[2]->type || ++ op->src[0]->ne[1] >= 65536 || op->src[0]->ne[3] >= 65536 || ++ indices->ne[0] <= 0 || indices->ne[0] > INT32_MAX || op->src[1]->ne[1] > INT32_MAX) { ++ return false; ++ } ++ for (int dim = 1; dim < 4; ++dim) { ++ if (indices->ne[dim] <= 0 || lengths->ne[dim] != indices->ne[dim] || ++ op->src[0]->ne[dim] % indices->ne[dim] != 0) { ++ return false; ++ } ++ } ++ const int64_t dk = op->src[1]->ne[0]; ++ const int64_t dv = op->src[2]->ne[0]; ++ const bool shape = ((dk == 32 || dk == 40 || dk == 48 || dk == 64 || dk == 72 || ++ dk == 80 || dk == 112) && dv == dk) || ++ (dk == 96 && (dv == 96 || dv == 64)) || (dk == 128 && (dv == 128 || dv == 96)) || ++ (dk == 192 && (dv == 192 || dv == 128)) || (dk == 256 && dv == 256) || ++ (dk == 320 && dv == 256) || (dk == 512 && dv == 512) || (dk == 576 && dv == 512); ++ if (!shape || (dk % 32 != 0 && (indices->ne[1] != 1 || indices->ne[2] != 1))) { ++ return false; ++ } ++ switch (op->src[1]->type) { ++ case GGML_TYPE_F32: ++ case GGML_TYPE_F16: ++ case GGML_TYPE_BF16: ++ case GGML_TYPE_Q4_0: ++ case GGML_TYPE_Q4_1: ++ case GGML_TYPE_Q5_0: ++ case GGML_TYPE_Q5_1: ++ case GGML_TYPE_Q8_0: ++ return true; ++ default: ++ return false; ++ } ++} ++ ++// Canonical request lists share one logical K/V order across the query tile. ++// Reuse the existing typed matrix kernel for prefill instead of scalarizing it. ++static inline bool ggml_metal_flash_attn_indexed_use_mma(const struct ggml_tensor * op) { ++ return op->src[5] && (op->src[0]->ne[1] >= 20 || op->src[1]->ne[0] % 32 != 0) && ++ op->src[5]->ne[1] == 1 && op->src[5]->ne[2] == 1; ++} ++ ++static inline void ggml_metal_flash_attn_indexed_args( ++ const struct ggml_tensor * op, ggml_metal_kargs_flash_attn_ext_vec * args) { ++ if (!op->src[5]) { ++ return; ++ } ++ args->n_kv_physical = (int32_t) op->src[1]->ne[1]; ++ args->n_kv_indices = (int32_t) op->src[5]->ne[0]; ++ args->ne51 = (int32_t) op->src[5]->ne[1]; ++ args->ne52 = (int32_t) op->src[5]->ne[2]; ++ args->ne53 = (int32_t) op->src[5]->ne[3]; ++ args->nb51 = op->src[5]->nb[1]; ++ args->nb52 = op->src[5]->nb[2]; ++ args->nb53 = op->src[5]->nb[3]; ++ args->nb61 = op->src[6]->nb[1]; ++ args->nb62 = op->src[6]->nb[2]; ++ args->nb63 = op->src[6]->nb[3]; ++} ++ ++static inline void ggml_metal_flash_attn_indexed_mma_args( ++ const struct ggml_tensor * op, ggml_metal_kargs_flash_attn_ext * args) { ++ if (!op->src[5]) { ++ return; ++ } ++ args->n_kv_physical = (int32_t) op->src[1]->ne[1]; ++ args->n_kv_indices = (int32_t) op->src[5]->ne[0]; ++ args->ne51 = (int32_t) op->src[5]->ne[1]; ++ args->ne52 = (int32_t) op->src[5]->ne[2]; ++ args->ne53 = (int32_t) op->src[5]->ne[3]; ++ args->nb51 = op->src[5]->nb[1]; ++ args->nb52 = op->src[5]->nb[2]; ++ args->nb53 = op->src[5]->nb[3]; ++ args->nb61 = op->src[6]->nb[1]; ++ args->nb62 = op->src[6]->nb[2]; ++ args->nb63 = op->src[6]->nb[3]; ++} +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index 2c7972b0a..b0e66a08a 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -1902,6 +1902,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( + int32_t ns20) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ const bool has_indices = op->src[5] != nullptr; ++ + char base[256]; + char name[256]; + +@@ -1919,7 +1921,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( + dk, + dv); + +- snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_ns10=%d_ns20=%d_nsg=%d", ++ snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_indexed=%d_ns10=%d_ns20=%d_nsg=%d", + base, + has_mask, + has_sinks, +@@ -1927,6 +1929,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( + has_scap, + has_kvpad, + bc_mask, ++ has_indices, + ns10, + ns20, + nsg); +@@ -1940,6 +1943,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( + ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT + 2); + ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT + 3); + ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT + 4); ++ ggml_metal_cv_set_bool(cv, has_indices, FC_FLASH_ATTN_EXT + 5); + + ggml_metal_cv_set_bool(cv, bc_mask, FC_FLASH_ATTN_EXT + 10); + +@@ -1993,6 +1997,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + int32_t ns20) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ const bool has_indices = op->src[5] != nullptr; ++ + char base[256]; + char name[256]; + +@@ -2013,7 +2019,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + dv, + qne_suffix); + +- snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", ++ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_indexed=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", + base, + has_mask, + has_sinks, +@@ -2021,6 +2027,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + has_scap, + has_kvpad, + has_sparse, ++ has_indices, + ns10, + ns20, + nsg, nwg); +@@ -2035,6 +2042,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_VEC + 3); + ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); + ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); ++ ggml_metal_cv_set_bool(cv, has_indices, FC_FLASH_ATTN_EXT_VEC + 6); + + ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); + ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); +diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m +index 5b23ddf7f..b1171f6ae 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.m ++++ b/ggml/src/ggml-metal/ggml-metal-device.m +@@ -5,6 +5,7 @@ + #import "ggml-backend-impl.h" + #import "ggml-metal-impl.h" + #import "ggml-metal-common.h" ++#import "ggml-metal-attention-indexed.h" + + #include + +@@ -1887,6 +1888,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te + case GGML_OP_ROLL: + return ggml_is_contiguous(op->src[0]); + case GGML_OP_FLASH_ATTN_EXT: ++ if (op->src[5]) { ++ return ggml_metal_flash_attn_indexed_supported(op) && has_simdgroup_mm && ++ (op->src[1]->type != GGML_TYPE_BF16 || has_bfloat); ++ } + // for new head sizes, add checks here + if (op->src[0]->ne[0] != 32 && + op->src[0]->ne[0] != 40 && +diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h +index d151a600d..a7fc56741 100644 +--- a/ggml/src/ggml-metal/ggml-metal-impl.h ++++ b/ggml/src/ggml-metal/ggml-metal-impl.h +@@ -445,6 +445,11 @@ typedef struct { + float m1; + int32_t n_head_log2; + float logit_softcap; ++ int32_t n_kv_physical; ++ int32_t n_kv_indices; ++ int32_t ne51, ne52, ne53; ++ uint64_t nb51, nb52, nb53; ++ uint64_t nb61, nb62, nb63; + } ggml_metal_kargs_flash_attn_ext; + + typedef struct { +@@ -481,6 +486,11 @@ typedef struct { + int32_t n_head_log2; + float logit_softcap; + int32_t n_kv_max_padded; ++ int32_t n_kv_physical; ++ int32_t n_kv_indices; ++ int32_t ne51, ne52, ne53; ++ uint64_t nb51, nb52, nb53; ++ uint64_t nb61, nb62, nb63; + } ggml_metal_kargs_flash_attn_ext_vec; + + typedef struct { +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index 53c981618..c983946dd 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -9,6 +9,7 @@ + #include "ggml-metal-device.h" + #include "ggml-metal-fusion.h" + #include "ggml-metal-tuning.h" ++#include "ggml-metal-attention-indexed.h" + + #include + #include +@@ -3094,6 +3095,10 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) { + bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return !ggml_metal_flash_attn_indexed_use_mma(op); ++ } ++ + const int64_t ne00 = op->src[0]->ne[0]; // head size + const int64_t ne01 = op->src[0]->ne[1]; // batch size + +@@ -3106,6 +3111,10 @@ bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { + static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return false; ++ } ++ + // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial + // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 + // TODO: tune per device +@@ -3174,6 +3183,11 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool + static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ GGML_ASSERT(ggml_metal_flash_attn_indexed_supported(op)); ++ return (int) op->src[5]->ne[0]; ++ } ++ + int32_t n_kv_max = 0; + memcpy(&n_kv_max, ((const int32_t *) op->op_params) + 4, sizeof(n_kv_max)); + +@@ -3253,6 +3267,10 @@ static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) + size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return 0; ++ } ++ + GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); + GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); + GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); +@@ -3311,6 +3329,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { + size_t ggml_metal_op_flash_attn_ext_extra_blk(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return 0; ++ } ++ + GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); + //GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); + //GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); +@@ -3379,6 +3401,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { + size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return 0; ++ } ++ + // note: always reserve the temp buffer to avoid graph reallocations + //if (!ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { + // return 0; +@@ -3404,6 +3430,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { + size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ if (op->src[5]) { ++ return 0; ++ } ++ + GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne); + + const int n_kv_max = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op); +@@ -3496,6 +3526,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + // sparse path: gather the finite mask entries into index lists and run the vec kernels over them + const int n_kv_max_sparse = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op); ++ const bool use_indexed = op->src[5] != nullptr; ++ const bool use_indexed_mma = ggml_metal_flash_attn_indexed_use_mma(op); + const bool use_sparse = n_kv_max_sparse > 0; + const int n_kv_max_padded = use_sparse ? GGML_PAD(n_kv_max_sparse, OP_FLASH_ATTN_EXT_VEC_NCPSG) : 0; + +@@ -3676,6 +3708,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.m1 =*/ m1, + /*.n_head_log2 =*/ n_head_log2, + /*.logit_softcap =*/ logit_softcap, ++ /* indexed physical/list bounds and broadcast strides */ ++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }; + + // shared memory layout: queries (16-bit), scores (float), probabilities (16-bit), row scale (float), rescale flag (int) +@@ -3699,7 +3733,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0); + + ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, ne02, ne03, 32, nsg, 1); +- } else if (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op)) { ++ } else if (use_indexed_mma || (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op))) { + // half8x8 kernel + const int nqptg = OP_FLASH_ATTN_EXT_NQPSG; // queries per threadgroup + const int ncpsg = OP_FLASH_ATTN_EXT_NCPSG; // cache values per simdgroup +@@ -3710,7 +3744,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + bool need_sync = false; + +- const bool has_kvpad = ne11 % ncpsg != 0; ++ const bool has_kvpad = !use_indexed && ne11 % ncpsg != 0; + + if (has_kvpad) { + assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); +@@ -3750,7 +3784,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + need_sync = true; + } + +- if (has_mask) { ++ if (has_mask && !use_indexed) { + assert(ggml_metal_op_flash_attn_ext_extra_blk(op) != 0); + + ggml_metal_kargs_flash_attn_ext_blk args0 = { +@@ -3783,7 +3817,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_metal_op_concurrency_reset(ctx); + } + +- const int is_q = !use_kv_f16 && ggml_is_quantized(op->src[1]->type) ? 1 : 0; ++ const int is_q = use_indexed || (!use_kv_f16 && ggml_is_quantized(op->src[1]->type)) ? 1 : 0; + + // shared memory layout (halfs unless noted): + // queries/attn/result: Q*(DK + 2*PAD2(DV,64) + 4*C) +@@ -3797,6 +3831,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + // simdgroups per threadgroup (a.k.a. warps) + int32_t nsg = ne00 >= 512 ? 8 : 4; ++ while (use_indexed && nsg > 1 && fa_smem(nsg) > props_dev->max_theadgroup_memory_size) { ++ nsg /= 2; ++ } + + const size_t smem = fa_smem(nsg); + +@@ -3810,7 +3847,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.nb01 =*/ nb01, + /*.nb02 =*/ nb02, + /*.nb03 =*/ nb03, +- /*.ne11 =*/ ne11, ++ /*.ne11 =*/ use_indexed ? n_kv_max_padded : ne11, + /*.ne_12_2 =*/ ne12, + /*.ne_12_3 =*/ ne13, + /*.ns10 =*/ ns10, +@@ -3836,8 +3873,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.m1 =*/ m1, + /*.n_head_log2 =*/ n_head_log2, + /*.logit_softcap =*/ logit_softcap, ++ /* indexed physical/list bounds and broadcast strides */ ++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }; + ++ ggml_metal_flash_attn_indexed_mma_args(op, &args); ++ + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20); + + ggml_metal_encoder_set_pipeline(enc, pipeline); +@@ -3850,6 +3891,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_metal_encoder_set_buffer (enc, bid_pad, 6); + ggml_metal_encoder_set_buffer (enc, bid_blk, 7); + ggml_metal_encoder_set_buffer (enc, bid_dst, 8); ++ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[5]) : bid_src0, 9); ++ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[6]) : bid_src0, 10); + + GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size); + +@@ -3880,7 +3923,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + const bool has_kvpad = !use_sparse && ne11 % ncpsg != 0; + +- if (use_sparse) { ++ if (use_sparse && !use_indexed) { + assert(ggml_metal_op_flash_attn_ext_extra_idx(op) != 0); + + GGML_ASSERT(ne30 == ne11); +@@ -4046,8 +4089,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.n_head_log2 =*/ n_head_log2, + /*.logit_softcap =*/ logit_softcap, + /*.n_kv_max_padded =*/ n_kv_max_padded, ++ /* indexed physical/list bounds and broadcast strides */ ++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }; + ++ ggml_metal_flash_attn_indexed_args(op, &args); ++ + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); + + GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); +@@ -4059,7 +4106,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_metal_encoder_set_buffer (enc, bid_v, 3); + ggml_metal_encoder_set_buffer (enc, bid_src3, 4); + ggml_metal_encoder_set_buffer (enc, bid_src4, 5); +- ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : bid_src0, 8); ++ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[5]) : (use_sparse ? bid_idx : bid_src0), 8); ++ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[6]) : bid_src0, 9); + + const size_t smem = fa_vec_smem(nsg, nqptg); + +diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal +index 5e08bf85f..f92f945b5 100644 +--- a/ggml/src/ggml-metal/kernels/fa_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_common.metal +@@ -3,6 +3,7 @@ constant bool FC_flash_attn_ext_has_sinks [[function_constant(FC_FLASH_ATTN_EXT + constant bool FC_flash_attn_ext_has_bias [[function_constant(FC_FLASH_ATTN_EXT + 2)]]; + constant bool FC_flash_attn_ext_has_scap [[function_constant(FC_FLASH_ATTN_EXT + 3)]]; + constant bool FC_flash_attn_ext_has_kvpad [[function_constant(FC_FLASH_ATTN_EXT + 4)]]; ++constant bool FC_flash_attn_ext_has_indices [[function_constant(FC_FLASH_ATTN_EXT + 5)]]; + + constant bool FC_flash_attn_ext_bc_mask [[function_constant(FC_FLASH_ATTN_EXT + 10)]]; + +@@ -14,6 +15,18 @@ constant int32_t FC_flash_attn_ext_ns10 [[function_constant(FC_FLASH_ATTN_EXT + + constant int32_t FC_flash_attn_ext_ns20 [[function_constant(FC_FLASH_ATTN_EXT + 21)]]; + constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + 22)]]; + ++// The physical pool may be interleaved, shared, or recycled. The list remains ++// in logical token order so mask columns and causality retain their meaning. ++static inline int flash_attn_ext_indexed_physical( ++ constant ggml_metal_kargs_flash_attn_ext & args, ++ device const int * indices, int count, int logical) { ++ if (logical < 0 || logical >= count) { ++ return -1; ++ } ++ const int physical = indices[logical]; ++ return physical >= 0 && physical < args.n_kv_physical ? physical : -1; ++} ++ + // ref: https://arxiv.org/pdf/2307.08691.pdf + template< + typename q_t, // query types in shared memory +@@ -54,6 +67,8 @@ void kernel_flash_attn_ext_impl( + device const char * pad, + device const char * blk, + device char * dst, ++ device const char * indices, ++ device const char * lengths, + threadgroup half * shmem_f16, + uint3 tgpig, + ushort tiisg, +@@ -118,7 +133,7 @@ void kernel_flash_attn_ext_impl( + pm2[jj] = (device const half2 *) ((device const char *) mask + (iq1 + j)*args.nb31 + (iq2%args.ne32)*args.nb32 + (iq3%args.ne33)*args.nb33); + } + +- { ++ if (!FC_flash_attn_ext_has_indices) { + const int32_t nblk1 = ((args.ne01 + Q - 1)/Q); + const int32_t nblk0 = ((args.ne11 + C - 1)/C); + +@@ -182,11 +197,20 @@ void kernel_flash_attn_ext_impl( + slope = pow(base, exph); + } + ++ device const int * pidx = nullptr; ++ int n_kv = args.ne11; ++ if (FC_flash_attn_ext_has_indices) { ++ const int i3 = iq3%args.ne53; ++ pidx = (device const int *) (indices + i3*args.nb53); ++ const int count = *((device const int *) (lengths + i3*args.nb63)); ++ n_kv = clamp(count, 0, args.n_kv_indices); ++ } ++ + // loop over the KV cache + // each simdgroup handles blocks of Q rows and C columns + for (int ic0 = 0; ; ++ic0) { + int ic = ic0*C; +- if (ic >= args.ne11) { ++ if (ic >= n_kv) { + break; + } + +@@ -231,7 +255,22 @@ void kernel_flash_attn_ext_impl( + char blk_cur = 1; + + // read the mask into shared mem +- if (FC_flash_attn_ext_has_mask) { ++ if (FC_flash_attn_ext_has_indices) { ++ FOR_UNROLL (short jj = 0; jj < NQ; ++jj) { ++ const short j = jj*NSG + sgitg; ++ half2 values(-MAXHALF, -MAXHALF); ++ FOR_UNROLL (short col = 0; col < 2; ++col) { ++ const int logical = ic + 2*tiisg + col; ++ if ((iq1 + j) < args.ne01 && ++ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) >= 0) { ++ values[col] = FC_flash_attn_ext_has_mask ? ++ ((device const half *) pm2[jj])[2*tiisg + col] : 0.0h; ++ } ++ } ++ sm2[j*SH + tiisg] = values; ++ pm2[jj] += NW; ++ } ++ } else if (FC_flash_attn_ext_has_mask) { + blk_cur = blk[ic0]; + + if (blk_cur == 0) { +@@ -286,7 +325,31 @@ void kernel_flash_attn_ext_impl( + + // Q*K^T + // this is compile-time check, so it does not have runtime overhead +- if (is_same::value) { ++ if (is_same::value && FC_flash_attn_ext_has_indices) { ++ // Gather an 8x8 tile before the existing MMA. This also covers ++ // non-quantized heads not divisible by 16 without truncation. ++ const short col = tiisg%8; ++ const short row = tiisg/8; ++ for (short cc = sgitg; cc < C/8; cc += NSG) { ++ qk8x8_t mqk = make_filled_simdgroup_matrix((qk_t) 0.0f); ++ for (short block = 0; block < DK8; ++block) { ++ FOR_UNROLL (short part = 0; part < 2; ++part) { ++ const short r = row + 4*part; ++ const int physical = flash_attn_ext_indexed_physical(args, pidx, n_kv, ic + 8*cc + r); ++ sk[8*r + col] = physical < 0 ? k_t(0) : ++ ((device const k_t *) (k + physical*args.nb11))[8*block + col]; ++ } ++ simdgroup_barrier(mem_flags::mem_threadgroup); ++ k8x8_t mk; ++ q8x8_t mq; ++ simdgroup_load(mk, sk, 8, 0, true); ++ simdgroup_load(mq, sq + 8*block, DK); ++ simdgroup_multiply_accumulate(mqk, mq, mk, mqk); ++ simdgroup_barrier(mem_flags::mem_threadgroup); ++ } ++ simdgroup_store(mqk, ss + 8*cc, SH, 0, false); ++ } ++ } else if (is_same::value) { + // we can read directly from global memory + device const k_t * pk = (device const k_t *) (k + ic*args.nb11); + threadgroup const q_t * pq = sq; +@@ -354,13 +417,20 @@ void kernel_flash_attn_ext_impl( + qk8x8_t mqk = make_filled_simdgroup_matrix((qk_t) 0.0f); + + for (short ii = 0; ii < DK16; ii += 4) { +- device const kd4x4_t * pk4x4 = (device const kd4x4_t *) (k + ((ic + 8*cc + ty)*args.nb11)); ++ const int logical = ic + 8*cc + ty; ++ const int physical = FC_flash_attn_ext_has_indices ? ++ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) : logical; ++ device const kd4x4_t * pk4x4 = (device const kd4x4_t *) (k + max(physical, 0)*args.nb11); + + if (DK16%4 == 0) { + // the head is evenly divisible by 4*16 = 64, so no need for bound checks + { + k4x4_t tmp; +- deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); ++ if (physical >= 0) { ++ deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); ++ } else { ++ tmp = k4x4_t(0); ++ } + sk4x4[4*ty + tx] = tmp; + } + +@@ -381,7 +451,11 @@ void kernel_flash_attn_ext_impl( + } else { + if (ii + tx < DK16) { + k4x4_t tmp; +- deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); ++ if (physical >= 0) { ++ deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); ++ } else { ++ tmp = k4x4_t(0); ++ } + sk4x4[4*ty + tx] = tmp; + } + +@@ -458,7 +532,30 @@ void kernel_flash_attn_ext_impl( + // O = O + (Q*K^T)*V + { + // we can read directly from global memory +- if (is_same::value) { ++ if (is_same::value && FC_flash_attn_ext_has_indices) { ++ const short col = tiisg%8; ++ const short row = tiisg/8; ++ for (short cc = 0; cc < C/8; ++cc) { ++ s8x8_t vs; ++ simdgroup_load(vs, ss + 8*cc, SH, 0, false); ++ for (short block = sgitg; block < DV/8; block += NSG) { ++ FOR_UNROLL (short part = 0; part < 2; ++part) { ++ const short r = row + 4*part; ++ const int physical = flash_attn_ext_indexed_physical(args, pidx, n_kv, ic + 8*cc + r); ++ sv[8*r + col] = physical < 0 ? v_t(0) : ++ ((device const v_t *) (v + physical*args.nb21))[8*block + col]; ++ } ++ simdgroup_barrier(mem_flags::mem_threadgroup); ++ v8x8_t mv; ++ o8x8_t lo; ++ simdgroup_load(mv, sv, 8); ++ simdgroup_load(lo, so + 8*block, PV); ++ simdgroup_multiply_accumulate(lo, vs, mv, lo); ++ simdgroup_store(lo, so + 8*block, PV); ++ simdgroup_barrier(mem_flags::mem_threadgroup); ++ } ++ } ++ } else if (is_same::value) { + static_assert(PV8 % NSG == 0, ""); + + constexpr short NO = PV8/NSG; +@@ -545,13 +642,20 @@ void kernel_flash_attn_ext_impl( + simdgroup_load(vs, ss + 8*cc, SH, 0, false); + + for (short ii = 4*sgitg; ii < DV16; ii += 4*NSG) { +- device const vd4x4_t * pv4x4 = (device const vd4x4_t *) (v + ((ic + 8*cc + ty)*args.nb21)); ++ const int logical = ic + 8*cc + ty; ++ const int physical = FC_flash_attn_ext_has_indices ? ++ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) : logical; ++ device const vd4x4_t * pv4x4 = (device const vd4x4_t *) (v + max(physical, 0)*args.nb21); + + if (DV16%4 == 0) { + // no need for bound checks + { + v4x4_t tmp; +- deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); ++ if (physical >= 0) { ++ deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); ++ } else { ++ tmp = v4x4_t(0); ++ } + sv4x4[4*ty + tx] = tmp; + } + +@@ -575,7 +679,11 @@ void kernel_flash_attn_ext_impl( + } else { + if (ii + tx < DV16) { + v4x4_t tmp; +- deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); ++ if (physical >= 0) { ++ deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); ++ } else { ++ tmp = v4x4_t(0); ++ } + sv4x4[4*ty + tx] = tmp; + } + +@@ -692,16 +800,22 @@ kernel void kernel_flash_attn_ext( + device const char * pad, + device const char * blk, + device char * dst, ++ device const char * indices, ++ device const char * lengths, + threadgroup half * shmem_f16 [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiisg[[thread_index_in_simdgroup]], + ushort sgitg[[simdgroup_index_in_threadgroup]]) { + #define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C +-#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg ++#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, indices, lengths, shmem_f16, tgpig, tiisg, sgitg + switch (FC_flash_attn_ext_nsg) { +- // note: disabled cases to reduce library load time +- //case 1: kernel_flash_attn_ext_impl(FWD_ARGS); break; +- //case 2: kernel_flash_attn_ext_impl(FWD_ARGS); break; ++ // Indexed gathers may need fewer simdgroups to fit their tile scratch. ++ case 1: ++ if (FC_flash_attn_ext_has_indices) { kernel_flash_attn_ext_impl(FWD_ARGS); } ++ break; ++ case 2: ++ if (FC_flash_attn_ext_has_indices) { kernel_flash_attn_ext_impl(FWD_ARGS); } ++ break; + case 4: kernel_flash_attn_ext_impl(FWD_ARGS); break; + case 8: kernel_flash_attn_ext_impl(FWD_ARGS); break; + } +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index 46270ba4b..4ef22227c 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -13,6 +13,7 @@ constant int32_t FC_flash_attn_ext_vec_ns20 [[function_constant(FC_FLASH_ATTN_EX + constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 22)]]; + constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; + constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; ++constant bool FC_flash_attn_ext_vec_has_indices [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; + template< + typename q4_t, // query types in shared memory + typename k4_t, // key types in shared memory +@@ -43,6 +44,7 @@ kernel void kernel_flash_attn_ext_vec( + device const char * pad, + device char * dst, + device const char * idx, ++ device const char * lengths, + threadgroup half * shmem_f16 [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiisg[[thread_index_in_simdgroup]], +@@ -160,7 +162,15 @@ kernel void kernel_flash_attn_ext_vec( + // sparse indices: the list of finite mask entries per query row + // the sparse path requires Q == 1 (enforced by the host) + device const int * pidx = nullptr; +- if (FC_flash_attn_ext_vec_has_sparse) { ++ int n_kv = args.ne11; ++ if (FC_flash_attn_ext_vec_has_indices) { ++ const int i1 = iq1%args.ne51; ++ const int i2 = iq2%args.ne52; ++ const int i3 = iq3%args.ne53; ++ pidx = (device const int *) (idx + i1*args.nb51 + i2*args.nb52 + i3*args.nb53); ++ const int count = *((device const int *) (lengths + i1*args.nb61 + i2*args.nb62 + i3*args.nb63)); ++ n_kv = clamp(count, 0, args.n_kv_indices); ++ } else if (FC_flash_attn_ext_vec_has_sparse) { + pidx = (device const int *) idx + + ((int64_t)(iq3%args.ne33)*args.ne32 + (iq2%args.ne32))*args.ne31*args.n_kv_max_padded + (iq1%args.ne31)*args.n_kv_max_padded; + } +@@ -181,7 +191,7 @@ kernel void kernel_flash_attn_ext_vec( + // each simdgroup handles blocks of Q rows and C columns + for (int ic0 = iwg*NSG + sgitg; ; ic0 += NWG*NSG) { + int ic = ic0*C; +- if (ic >= args.ne11) { ++ if (ic >= n_kv) { + break; + } + +@@ -227,7 +237,14 @@ kernel void kernel_flash_attn_ext_vec( + FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { + const short i = ii*NW + tiisg; + +- spidx[i] = pidx[ic + i]; ++ int physical = -1; ++ if (!FC_flash_attn_ext_vec_has_indices || ic + i < n_kv) { ++ physical = pidx[ic + i]; ++ } ++ if (FC_flash_attn_ext_vec_has_indices && (physical < 0 || physical >= args.n_kv_physical)) { ++ physical = -1; ++ } ++ spidx[i] = physical; + } + simdgroup_barrier(mem_flags::mem_threadgroup); + } +@@ -237,7 +254,7 @@ kernel void kernel_flash_attn_ext_vec( + FOR_UNROLL (short qq = 0; qq < Q; ++qq) { + const int i11 = spidx[tiisg]; + if ((iq1*Q + qq) < args.ne01 && i11 >= 0) { +- sm[qq*C + tiisg] = pm[qq][i11]; ++ sm[qq*C + tiisg] = pm[qq][FC_flash_attn_ext_vec_has_indices ? ic + tiisg : i11]; + } else { + sm[qq*C + tiisg] = -MAXHALF; + } +@@ -253,7 +270,9 @@ kernel void kernel_flash_attn_ext_vec( + } + } else { + FOR_UNROLL (short qq = 0; qq < Q; ++qq) { +- if ((iq1*Q + qq) >= args.ne01) { ++ if (FC_flash_attn_ext_vec_has_indices) { ++ sm[qq*C + tiisg] = (iq1*Q + qq) < args.ne01 && spidx[tiisg] >= 0 ? 0.0h : -MAXHALF; ++ } else if ((iq1*Q + qq) >= args.ne01) { + sm[qq*C + tiisg] = -MAXHALF; + } + } +diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp +index 17ceacc7a..a0f87bebe 100644 +--- a/ggml/src/ggml-opencl/ggml-opencl.cpp ++++ b/ggml/src/ggml-opencl/ggml-opencl.cpp +@@ -9402,6 +9402,9 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te + case GGML_OP_MEAN: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_FLASH_ATTN_EXT: { ++ if (op->src[5]) { ++ return false; ++ } + #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { + return true; +diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp +index 22b2f45e2..89d727ab3 100644 +--- a/ggml/src/ggml-openvino/ggml-openvino.cpp ++++ b/ggml/src/ggml-openvino/ggml-openvino.cpp +@@ -1761,6 +1761,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { + + static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(ggml_backend_dev_t dev, const ggml_tensor * op) { + GGML_ASSERT(dev->reg != nullptr); ++ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { ++ return {false, "request-indexed attention is not supported"}; ++ } + + ggml_backend_openvino_device_context * dev_ctx = (ggml_backend_openvino_device_context *) dev->context; + if (dev_ctx->ov_name != ggml_openvino_get_device_name()) { +diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp +index 6759af0ed..e0d4d3342 100644 +--- a/ggml/src/ggml-sycl/ggml-sycl.cpp ++++ b/ggml/src/ggml-sycl/ggml-sycl.cpp +@@ -7178,7 +7178,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons + case GGML_OP_SOLVE_TRI: + return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; + case GGML_OP_FLASH_ATTN_EXT: +- return ggml_sycl_flash_attn_ext_supported(device, op); ++ return !op->src[5] && ggml_sycl_flash_attn_ext_supported(device, op); + default: + return false; + } +diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +index 436bfe3bb..065a27b2a 100644 +--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp ++++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +@@ -15569,6 +15569,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm + } + case GGML_OP_FLASH_ATTN_EXT: + { ++ if (op->src[5]) { ++ return false; ++ } + bool coopmat2 = device->coopmat2; + uint32_t HSK = op->src[1]->ne[0]; + uint32_t HSV = op->src[2]->ne[0]; +diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp +index 15e6c784b..6400077b9 100644 +--- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp ++++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp +@@ -4580,7 +4580,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const + { + // conservative support checks for whether the more resource-intensive shader paths + // can be used, to avoid cases where flash_attn is assigned to the CPU later on +- supports_op = src0->type == GGML_TYPE_F32 && ++ supports_op = !op->src[5] && src0->type == GGML_TYPE_F32 && + (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || + src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && + (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || +diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c +index 01dc8d05c..d970209bf 100644 +--- a/ggml/src/ggml.c ++++ b/ggml/src/ggml.c +@@ -5516,20 +5516,40 @@ struct ggml_tensor * ggml_arange( + + // ggml_flash_attn_ext + +-struct ggml_tensor * ggml_flash_attn_ext( ++static struct ggml_tensor * ggml_flash_attn_ext_impl( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * mask, ++ struct ggml_tensor * indices, ++ struct ggml_tensor * lengths, + float scale, + float max_bias, + float logit_softcap) { + GGML_ASSERT(ggml_can_mul_mat(k, q)); + // TODO: check if vT can be multiplied by (k*qT) + +- GGML_ASSERT(q->ne[3] == k->ne[3]); +- GGML_ASSERT(q->ne[3] == v->ne[3]); ++ GGML_ASSERT((indices != NULL) == (lengths != NULL)); ++ GGML_ASSERT(q->ne[3] == k->ne[3] || (indices && k->ne[3] == 1)); ++ GGML_ASSERT(q->ne[3] == v->ne[3] || (indices && v->ne[3] == 1)); ++ ++ if (indices) { ++ GGML_ASSERT(indices->type == GGML_TYPE_I32 && lengths->type == GGML_TYPE_I32); ++ GGML_ASSERT(indices->ne[0] > 0 && lengths->ne[0] == 1); ++ GGML_ASSERT(k->ne[1] == v->ne[1]); ++ GGML_ASSERT(q->nb[0] == ggml_type_size(q->type)); ++ GGML_ASSERT(k->nb[0] == ggml_type_size(k->type)); ++ GGML_ASSERT(v->nb[0] == ggml_type_size(v->type)); ++ GGML_ASSERT(ggml_is_contiguous(indices) && ggml_is_contiguous(lengths)); ++ for (int d = 1; d < GGML_MAX_DIMS; ++d) { ++ GGML_ASSERT(indices->ne[d] > 0); ++ GGML_ASSERT(q->ne[d] % indices->ne[d] == 0); ++ GGML_ASSERT(lengths->ne[d] == indices->ne[d]); ++ } ++ GGML_ASSERT(mask == NULL || mask->ne[0] == indices->ne[0]); ++ GGML_ASSERT(mask == NULL || mask->ne[1] >= q->ne[1]); ++ } + + if (mask) { + GGML_ASSERT(mask->type == GGML_TYPE_F16); +@@ -5556,10 +5576,28 @@ struct ggml_tensor * ggml_flash_attn_ext( + result->src[1] = k; + result->src[2] = v; + result->src[3] = mask; ++ result->src[5] = indices; ++ result->src[6] = lengths; + + return result; + } + ++struct ggml_tensor * ggml_flash_attn_ext( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, struct ggml_tensor * k, struct ggml_tensor * v, ++ struct ggml_tensor * mask, float scale, float max_bias, float logit_softcap) { ++ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, NULL, NULL, scale, max_bias, logit_softcap); ++} ++ ++struct ggml_tensor * ggml_flash_attn_ext_indexed( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, struct ggml_tensor * k, struct ggml_tensor * v, ++ struct ggml_tensor * mask, struct ggml_tensor * indices, struct ggml_tensor * lengths, ++ float scale, float max_bias, float logit_softcap) { ++ GGML_ASSERT(indices && lengths); ++ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, indices, lengths, scale, max_bias, logit_softcap); ++} ++ + + void ggml_flash_attn_ext_set_prec( + struct ggml_tensor * a, +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index d55e38363..0e9996f97 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -19,10 +19,12 @@ set(LLAMA_CORE_SOURCES + llama-cparams.cpp + llama-grammar.cpp + llama-graph.cpp ++ llama-graph-kv-read.cpp + llama-hparams.cpp + llama-impl.cpp + llama-io.cpp + llama-kv-cache.cpp ++ llama-kv-read.cpp + llama-kv-cache-iswa.cpp + llama-kv-cache-dsa.cpp + llama-kv-cache-dsa-iswa.cpp +diff --git a/src/llama-graph-kv-read.cpp b/src/llama-graph-kv-read.cpp +new file mode 100644 +index 000000000..69788b4ec +--- /dev/null ++++ b/src/llama-graph-kv-read.cpp +@@ -0,0 +1,126 @@ ++#include "llama-graph.h" ++ ++#include "llama-cparams.h" ++#include "llama-kv-cache.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++ ++bool llm_graph_context::supports_indexed_attn(const ggml_tensor * node, ++ const ggml_tensor * storage) const { ++ while (storage->view_src) { ++ storage = storage->view_src; ++ } ++ if (storage->buffer) { ++ const auto type = ggml_backend_buffer_get_type(storage->buffer); ++ const auto device = ggml_backend_buft_get_device(type); ++ if (device) { ++ return ggml_backend_dev_supports_op(device, node); ++ } ++ // Generic CPU and mapped host buffers have no device owner. Resolve ++ // their capability through the scheduler's CPU backend, without ++ // admitting unsupported GPU-owned storage onto a CPU copy path. ++ if (!ggml_backend_buft_is_host(type) || !sched) { ++ return false; ++ } ++ for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { ++ const auto backend = ggml_backend_sched_get_backend(sched, i); ++ const auto backend_device = ggml_backend_get_device(backend); ++ if (backend_device && ggml_backend_dev_type(backend_device) == GGML_BACKEND_DEVICE_TYPE_CPU && ++ ggml_backend_supports_op(backend, node)) { ++ return true; ++ } ++ } ++ return false; ++ } ++ // Unallocated planning tensors have no buffer owner yet. Use the normal ++ // scheduler's preferred compute backend for the same capability query. ++ return sched && ggml_backend_sched_get_n_backends(sched) > 0 && ++ ggml_backend_supports_op(ggml_backend_sched_get_backend(sched, 0), node); ++} ++ ++static llama_kv_read_plan make_read_plan(const llm_graph_input_attn_kv & input, ++ const llama_ubatch & ubatch) { ++ const auto & params = input.cparams; ++ if (!params.flash_attn || !params.causal_attn || !params.kv_unified || params.training || ++ input.hparams.n_rel_attn_bkts != 0) { ++ return {}; ++ } ++ return input.mctx->get_read_plan(ubatch); ++} ++ ++void llm_graph_input_attn_kv::build_read_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { ++ read_plan = make_read_plan(*this, ubatch); ++ if (!read_plan) { ++ return; ++ } ++ self_read_indices = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, ++ read_plan.logical_extent, 1, 1, read_plan.request_count); ++ self_read_lengths = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, ++ 1, 1, 1, read_plan.request_count); ++ self_read_mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, ++ read_plan.logical_extent, read_plan.queries_per_request, 1, read_plan.request_count); ++ ggml_set_input(self_read_indices); ++ ggml_set_input(self_read_lengths); ++ ggml_set_input(self_read_mask); ++ ggml_set_name(self_read_indices, "attn_inp_read_indices"); ++ ggml_set_name(self_read_lengths, "attn_inp_read_lengths"); ++ ggml_set_name(self_read_mask, "attn_inp_read_mask"); ++} ++ ++bool llm_graph_input_attn_kv::can_reuse_read_inputs(const llama_ubatch & ubatch) { ++ auto next = make_read_plan(*this, ubatch); ++ if (static_cast(next) != static_cast(read_plan)) { ++ return false; ++ } ++ if (next.logical_extent != read_plan.logical_extent || ++ next.queries_per_request != read_plan.queries_per_request || ++ next.request_count != read_plan.request_count || ++ next.physical_extent != read_plan.physical_extent) { ++ return false; ++ } ++ read_plan = std::move(next); ++ return true; ++} ++ ++void llm_graph_input_attn_kv::set_read_inputs(const llama_ubatch & ubatch) { ++ if (!read_plan) { ++ return; ++ } ++ if (self_read_indices->buffer) { ++ ggml_backend_tensor_set(self_read_indices, read_plan.indices.data(), 0, ++ read_plan.indices.size() * sizeof(int32_t)); ++ } ++ if (self_read_lengths->buffer) { ++ ggml_backend_tensor_set(self_read_lengths, read_plan.lengths.data(), 0, ++ read_plan.lengths.size() * sizeof(int32_t)); ++ } ++ if (!self_read_mask->buffer) { ++ return; ++ } ++ ++ const uint32_t extent = read_plan.logical_extent; ++ const uint32_t queries = read_plan.queries_per_request; ++ std::vector mask(ggml_nelements(self_read_mask)); ++ const ggml_fp16_t drop = ggml_fp32_to_fp16(-INFINITY); ++ std::fill(mask.begin(), mask.end(), drop); ++ for (uint32_t request = 0; request < read_plan.request_count; ++request) { ++ for (uint32_t query = 0; query < queries; ++query) { ++ const llama_pos position = ubatch.pos[request * queries + query]; ++ auto * row = mask.data() + (static_cast(request) * queries + query) * extent; ++ for (int32_t slot = 0; slot < read_plan.lengths[request]; ++slot) { ++ const llama_pos key_position = read_plan.positions[request * extent + slot]; ++ if (key_position > position) { ++ break; ++ } ++ const float bias = hparams.f_max_alibi_bias > 0 ? ++ -static_cast(position - key_position) : 0.0f; ++ row[slot] = ggml_fp32_to_fp16(bias); ++ } ++ } ++ } ++ ggml_backend_tensor_set(self_read_mask, mask.data(), 0, mask.size() * sizeof(ggml_fp16_t)); ++} +diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp +index 569b27022..8e3dab5e9 100644 +--- a/src/llama-graph.cpp ++++ b/src/llama-graph.cpp +@@ -591,6 +591,8 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); + } + ++ set_read_inputs(*ubatch); ++ + if (self_k_rot && self_k_rot->buffer) { + mctx->set_input_k_rot(self_k_rot); + } +@@ -601,19 +603,23 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + } + + bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) { +- const auto * mctx = static_cast(params.mctx); ++ return can_reuse_attn(static_cast(params.mctx), ++ params.ubatch, params.cparams); ++} + +- this->mctx = mctx; ++bool llm_graph_input_attn_kv::can_reuse_attn(const llama_kv_cache_context * context, ++ const llama_ubatch & ubatch, const llama_cparams & params) { ++ mctx = context; + +- bool res = true; ++ bool res = can_reuse_read_inputs(ubatch); + + if (self_k_idxs && self_k_idxs->buffer) { +- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; ++ res &= self_k_idxs->ne[0] == ubatch.n_tokens; + } + //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there + + if (self_kq_mask && self_kq_mask->buffer) { +- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); ++ res &= can_reuse_kq_mask(self_kq_mask, mctx, ubatch, params); + } + + return res; +@@ -1263,23 +1269,8 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { + } + + void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { +- const auto * attn_ctx = mctx->get_attn(); +- +- // These tensors may not be allocated for staged slices that contain only +- // recurrent layers. +- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { +- attn_ctx->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); +- attn_ctx->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); +- attn_ctx->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); +- } +- +- if (inp_attn->self_k_rot) { +- attn_ctx->set_input_k_rot(inp_attn->self_k_rot); +- } +- +- if (inp_attn->self_v_rot) { +- attn_ctx->set_input_v_rot(inp_attn->self_v_rot); +- } ++ inp_attn->mctx = mctx->get_attn(); ++ inp_attn->set_input(ubatch); + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + +@@ -1299,16 +1290,7 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { + + this->mctx = mctx; + +- bool res = true; +- +- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { +- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; +- } +- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there +- +- if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { +- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); +- } ++ bool res = inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); + + if (inp_rs->s_copy && inp_rs->s_copy->buffer) { + res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); +@@ -1967,6 +1949,9 @@ void llm_graph_context::request_inputs(llm_graph_input_attn_kv * input) const { + request_input(input->self_k_idxs, "attention.key_indices"); + request_input(input->self_v_idxs, "attention.value_indices"); + request_input(input->self_kq_mask, "attention.mask"); ++ request_input(input->self_read_indices, "attention.read_indices"); ++ request_input(input->self_read_lengths, "attention.read_lengths"); ++ request_input(input->self_read_mask, "attention.read_mask"); + request_input(input->self_k_rot, "attention.key_rotation"); + request_input(input->self_v_rot, "attention.value_rotation"); + } +@@ -3384,11 +3369,17 @@ ggml_tensor * llm_graph_context::build_attn_mha( + ggml_tensor * v_mla, + int64_t n_kv_max, + float kq_scale, +- int il) const { ++ int il, ++ ggml_tensor * read_indices, ++ ggml_tensor * read_lengths, ++ ggml_tensor * dense_mask) const { ++ ggml_tensor * original_q = q; ++ ggml_tensor * original_k = k; ++ ggml_tensor * original_v = v; + const bool v_trans = v->nb[1] > v->nb[2]; + + // split the batch into streams if needed +- const auto n_stream = k->ne[3]; ++ const auto n_stream = read_indices ? read_indices->ne[3] : k->ne[3]; + + // the stream dim steps over one stream's worth of dim-2 (tokens): (ne[2]/n_stream) rows of stride nb[2]. + // q->nb[3]/n_stream only equals that for a contiguous q; nope-only MLA (glm5-next) passes a permuted +@@ -3427,16 +3418,26 @@ ggml_tensor * llm_graph_context::build_attn_mha( + } + + // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) +- if (k->type == GGML_TYPE_F32) { ++ if (!read_indices && k->type == GGML_TYPE_F32) { + k = ggml_cast(ctx0, k, GGML_TYPE_F16); + } + +- if (v->type == GGML_TYPE_F32) { ++ if (!read_indices && v->type == GGML_TYPE_F32) { + v = ggml_cast(ctx0, v, GGML_TYPE_F16); + } + +- cur = ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, kq_scale, hparams.f_max_alibi_bias, +- hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); ++ const float softcap = hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f; ++ cur = read_indices ? ggml_flash_attn_ext_indexed(ctx0, q, k, v, fa_mask, ++ read_indices, read_lengths, kq_scale, hparams.f_max_alibi_bias, softcap) : ++ ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, ++ kq_scale, hparams.f_max_alibi_bias, softcap); ++ if (read_indices && !supports_indexed_attn(cur, original_k)) { ++ // Keep unsupported devices and K/V types on their existing native ++ // attention path, rather than copying the shared pool to the CPU. ++ GGML_ASSERT(dense_mask); ++ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, ++ sinks, v_mla, n_kv_max, kq_scale, il); ++ } + res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); + + ggml_flash_attn_ext_add_sinks(cur, sinks); +@@ -3643,6 +3644,8 @@ static std::unique_ptr build_attn_inp_kv_impl( + inp->self_kq_mask_cnv = inp->self_kq_mask; + } + ++ inp->build_read_inputs(ctx0, ubatch); ++ + inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); + inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); + +@@ -3724,7 +3727,11 @@ ggml_tensor * llm_graph_context::build_attn( + + ggml_tensor * kq_mask = inp->get_kq_mask(); + +- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); ++ // Bias-producing builders retain their existing dense mask and semantics. ++ const bool indexed = inp->self_read_indices != nullptr && kq_b == nullptr && v_mla == nullptr; ++ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, ++ indexed ? inp->self_read_mask : kq_mask, sinks, v_mla, 0, kq_scale, il, ++ indexed ? inp->self_read_indices : nullptr, indexed ? inp->self_read_lengths : nullptr, kq_mask); + cb(cur, "kqv_out", il); + + if (inp->self_v_rot) { +diff --git a/src/llama-graph.h b/src/llama-graph.h +index a4ffee4e5..f32b6ef58 100644 +--- a/src/llama-graph.h ++++ b/src/llama-graph.h +@@ -4,6 +4,7 @@ + #include "llama-batch.h" + #include "llama-hparams.h" + #include "llama-adapter.h" ++#include "llama-kv-read.h" + + #include "skippy/block_boundaries.h" + #include "skippy/graph_identity.h" +@@ -430,6 +431,12 @@ public: + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params & params) override; ++ bool can_reuse_attn(const llama_kv_cache_context * context, const llama_ubatch & ubatch, ++ const llama_cparams & params); ++ ++ void build_read_inputs(ggml_context * ctx, const llama_ubatch & ubatch); ++ void set_read_inputs(const llama_ubatch & ubatch); ++ bool can_reuse_read_inputs(const llama_ubatch & ubatch); + + ggml_tensor * get_k_idxs() const { return self_k_idxs; } + ggml_tensor * get_v_idxs() const { return self_v_idxs; } +@@ -442,6 +449,13 @@ public: + ggml_tensor * self_kq_mask = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream] + ggml_tensor * self_kq_mask_cnv = nullptr; // [n_kv, n_batch/n_stream, 1, n_stream] + ++ // Optional logical reads into the existing physical K/V storage. The dense ++ // mask remains available for attention nodes with additional bias semantics. ++ ggml_tensor * self_read_indices = nullptr; ++ ggml_tensor * self_read_lengths = nullptr; ++ ggml_tensor * self_read_mask = nullptr; ++ llama_kv_read_plan read_plan; ++ + // note: assumes v_rot^2 == I + ggml_tensor * self_k_rot = nullptr; + ggml_tensor * self_v_rot = nullptr; +@@ -1433,7 +1447,12 @@ struct llm_graph_context { + ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] + int64_t n_kv_max, + float kq_scale, +- int il) const; ++ int il, ++ ggml_tensor * read_indices = nullptr, ++ ggml_tensor * read_lengths = nullptr, ++ ggml_tensor * dense_mask = nullptr) const; ++ ++ bool supports_indexed_attn(const ggml_tensor * node, const ggml_tensor * storage) const; + + llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; + +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index 021fdfe2e..df68f3c0d 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -15,6 +15,7 @@ struct llama_model; + struct llama_context; + struct skippy_kv_page_desc; + struct skippy_cachegen_record_v1; ++struct llama_kv_read_plan; + + // + // llama_kv_cache +@@ -470,6 +471,7 @@ public: + + uint32_t get_n_kv() const; + uint32_t get_n_kv_pos_contiguous() const; ++ llama_kv_read_plan get_read_plan(const llama_ubatch & ubatch) const; + + ggml_type type_k() const; + ggml_type type_v() const; +diff --git a/src/llama-kv-read.cpp b/src/llama-kv-read.cpp +new file mode 100644 +index 000000000..934d3b733 +--- /dev/null ++++ b/src/llama-kv-read.cpp +@@ -0,0 +1,148 @@ ++#include "llama-kv-read.h" ++ ++#include "llama-kv-cache.h" ++ ++#include ++#include ++#include ++ ++namespace { ++ ++struct request_queries { ++ llama_seq_id sequence; ++ uint32_t count = 0; ++ llama_pos max_position = -1; ++}; ++ ++bool scalar_text_positions(const llama_ubatch & ubatch) { ++ if (ubatch.n_pos == 0) { ++ return false; ++ } ++ // Ordinary text can carry multiple rotary-position planes. The batch ++ // allocator expands these to [p, p, p, 0, ...]; spatial inputs retain ++ // independent coordinates and need the existing spatial mask instead. ++ for (uint32_t axis = 1; axis < ubatch.n_pos; ++axis) { ++ for (uint32_t token = 0; token < ubatch.n_tokens; ++token) { ++ const llama_pos expected = axis < 3 ? ubatch.pos[token] : 0; ++ if (ubatch.pos[axis * ubatch.n_tokens + token] != expected) { ++ return false; ++ } ++ } ++ } ++ return true; ++} ++ ++bool query_runs(const llama_ubatch & ubatch, std::vector & requests) { ++ std::set sequences; ++ std::set positions; ++ for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { ++ if (ubatch.n_seq_id[i] != 1 || !ubatch.seq_id[i] || ubatch.pos[i] < 0) { ++ return false; ++ } ++ const llama_seq_id sequence = ubatch.seq_id[i][0]; ++ if (sequence < 0 || sequence >= LLAMA_MAX_SEQ) { ++ return false; ++ } ++ if (requests.empty() || requests.back().sequence != sequence) { ++ // A request must own one contiguous query run, including decode ++ // split_simple batches whose b_equal_seqs flag is false. ++ if (!sequences.insert(sequence).second) { ++ return false; ++ } ++ requests.push_back({sequence}); ++ positions.clear(); ++ } ++ if (!positions.insert(ubatch.pos[i]).second) { ++ return false; ++ } ++ auto & request = requests.back(); ++ ++request.count; ++ request.max_position = std::max(request.max_position, ubatch.pos[i]); ++ } ++ const uint32_t count = requests.front().count; ++ return std::all_of(requests.begin(), requests.end(), [count](const request_queries & request) { ++ return request.count == count; ++ }); ++} ++ ++bool visible_count(const llama_kv_cache & cache, const request_queries & request, ++ uint32_t physical_extent, bool spatial_positions, int32_t & count) { ++ const auto & cells = cache.get_cells(request.sequence); ++ llama_pos previous = -1; ++ count = 0; ++ for (const auto & entry : cells.seq_pos_get(request.sequence)) { ++ if (entry.first > request.max_position) { ++ break; ++ } ++ if (entry.first < 0 || entry.first == previous || entry.second >= physical_extent || ++ count == std::numeric_limits::max()) { ++ return false; ++ } ++ if (spatial_positions) { ++ const auto & spatial = cells.ext_get(entry.second); ++ if (spatial.x != entry.first || spatial.y != entry.first) { ++ return false; ++ } ++ } ++ previous = entry.first; ++ ++count; ++ } ++ return true; ++} ++ ++} // namespace ++ ++llama_kv_read_plan llama_kv_cache_context::get_read_plan(const llama_ubatch & ubatch) const { ++ if (!kv || kv->get_n_stream() != 1 || kv->get_n_swa() != 0 || ++ ubatch.n_tokens == 0 || ubatch.decision_order || ++ !ubatch.pos || !ubatch.n_seq_id || !ubatch.seq_id) { ++ return {}; ++ } ++ if (!scalar_text_positions(ubatch)) { ++ return {}; ++ } ++ const uint32_t physical_extent = get_n_kv(); ++ if (physical_extent == 0 || physical_extent > static_cast(std::numeric_limits::max())) { ++ return {}; ++ } ++ ++ std::vector requests; ++ if (!query_runs(ubatch, requests)) { ++ return {}; ++ } ++ llama_kv_read_plan plan; ++ plan.physical_extent = physical_extent; ++ plan.lengths.resize(requests.size()); ++ uint32_t max_length = 0; ++ for (size_t i = 0; i < requests.size(); ++i) { ++ if (!visible_count(*kv, requests[i], physical_extent, ubatch.n_pos >= 3, plan.lengths[i])) { ++ return {}; ++ } ++ max_length = std::max(max_length, static_cast(plan.lengths[i])); ++ } ++ constexpr uint32_t alignment = 256; ++ if (max_length > static_cast(std::numeric_limits::max()) - (alignment - 1)) { ++ return {}; ++ } ++ plan.logical_extent = std::max(alignment, ((max_length + alignment - 1) / alignment) * alignment); ++ if (requests.size() > std::numeric_limits::max() / plan.logical_extent) { ++ return {}; ++ } ++ const size_t elements = requests.size() * plan.logical_extent; ++ plan.indices.assign(elements, -1); ++ plan.positions.assign(elements, -1); ++ for (size_t i = 0; i < requests.size(); ++i) { ++ size_t destination = i * plan.logical_extent; ++ for (const auto & entry : kv->get_cells(requests[i].sequence).seq_pos_get(requests[i].sequence)) { ++ if (entry.first > requests[i].max_position) { ++ break; ++ } ++ plan.indices[destination] = static_cast(entry.second); ++ plan.positions[destination] = entry.first; ++ ++destination; ++ } ++ } ++ plan.queries_per_request = requests.front().count; ++ plan.request_count = static_cast(requests.size()); ++ return plan; ++} +diff --git a/src/llama-kv-read.h b/src/llama-kv-read.h +new file mode 100644 +index 000000000..ca21eae3a +--- /dev/null ++++ b/src/llama-kv-read.h +@@ -0,0 +1,20 @@ ++#pragma once ++ ++#include "llama.h" ++ ++#include ++#include ++ ++// Request-major logical token positions and their shared physical attention ++// cells. Padding is -1; lengths, not physical pool occupancy, bound each read. ++struct llama_kv_read_plan { ++ uint32_t queries_per_request = 0; ++ uint32_t request_count = 0; ++ uint32_t physical_extent = 0; ++ uint32_t logical_extent = 0; ++ std::vector indices; ++ std::vector positions; ++ std::vector lengths; ++ ++ explicit operator bool() const { return request_count != 0; } ++}; +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index def0ea7a6..0e279f1bc 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -345,6 +345,8 @@ endif() + + llama_build(test-backend-ops.cpp LINK ggml) + ++llama_build_and_test(test-flash-attn-indexed.cpp LINK ggml ARGS --backend CPU) ++ + llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) + llama_build_and_test(test-model-load-cancel.cpp LABEL "model") + llama_build_and_test(test-autorelease.cpp LABEL "model") +diff --git a/tests/test-flash-attn-indexed.cpp b/tests/test-flash-attn-indexed.cpp +new file mode 100644 +index 000000000..813953ac1 +--- /dev/null ++++ b/tests/test-flash-attn-indexed.cpp +@@ -0,0 +1,378 @@ ++#include "ggml.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++constexpr int64_t kv_heads = 2; ++constexpr int64_t requests = 4; ++// Match test_flash_attn_ext::max_nmse_err in test-backend-ops.cpp. ++constexpr double max_nmse = 5e-4; ++ ++struct attention_case { ++ int64_t queries; ++ int64_t logical_rows; ++ bool mask; ++ bool sinks; ++ bool query_local = false; ++ bool strided_query = false; ++ ggml_type type_k = GGML_TYPE_F16; ++ ggml_type type_v = GGML_TYPE_F16; ++ int64_t dk = 256; ++ int64_t dv = 256; ++ float max_bias = 1.5f; ++ int64_t heads = 8; ++}; ++ ++void require(bool condition, const char * message) { ++ if (!condition) { ++ throw std::runtime_error(message); ++ } ++} ++ ++struct inputs { ++ const attention_case spec; ++ const int64_t physical_rows; ++ const int64_t mask_queries; ++ const int64_t index_queries; ++ std::vector q; ++ const size_t row_k; ++ const size_t row_v; ++ std::vector k, v, logical_k, logical_v; ++ std::vector mask; ++ std::vector indices, lengths; ++ std::vector sinks; ++ ++ explicit inputs(attention_case value) : spec(value), physical_rows(2*value.logical_rows + 257), ++ mask_queries((value.queries + 63)/64*64), index_queries(value.query_local ? value.queries : 1), ++ q(value.dk*value.queries*value.heads*requests), ++ row_k(ggml_row_size(value.type_k, value.dk)), row_v(ggml_row_size(value.type_v, value.dv)), ++ k(row_k*physical_rows*kv_heads), v(row_v*physical_rows*kv_heads), ++ logical_k(row_k*value.logical_rows*kv_heads*requests), ++ logical_v(row_v*value.logical_rows*kv_heads*requests), ++ mask(value.logical_rows*mask_queries*requests), ++ indices(value.logical_rows*index_queries*requests), lengths(index_queries*requests), sinks(value.heads) { ++ std::mt19937 random(34791); ++ std::uniform_real_distribution sample(-0.75f, 0.75f); ++ for (float & item : q) { ++ item = sample(random); ++ } ++ std::vector values(std::max(value.dk, value.dv)*physical_rows*kv_heads); ++ for (float & item : values) { ++ item = sample(random); ++ } ++ ggml_quantize_chunk(value.type_k, values.data(), k.data(), 0, physical_rows*kv_heads, value.dk, nullptr); ++ for (float & item : values) { ++ item = sample(random); ++ } ++ ggml_quantize_chunk(value.type_v, values.data(), v.data(), 0, physical_rows*kv_heads, value.dv, nullptr); ++ for (float & item : sinks) { ++ item = sample(random); ++ } ++ } ++ ++ void refresh(int phase) { ++ const int64_t width = spec.logical_rows; ++ std::fill(indices.begin(), indices.end(), -1); ++ std::fill(logical_k.begin(), logical_k.end(), 0); ++ std::fill(logical_v.begin(), logical_v.end(), 0); ++ const std::array counts = phase == 0 ? ++ std::array{0, 31, 65, int32_t(width - 7)} : ++ std::array{65, int32_t(width - 9), 0, 31}; ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t query = 0; query < index_queries; ++query) { ++ const int32_t count = std::max(0, counts[request] - int32_t(query % 3)); ++ lengths[request*index_queries + query] = count; ++ for (int32_t slot = 0; slot < count; ++slot) { ++ // Shared first rows plus interleaved, nonmonotonic physical rows. ++ const int32_t physical = int32_t((slot*37 + (slot < 5 ? 0 : request*53) + phase*101) % physical_rows); ++ indices[(request*index_queries + query)*width + slot] = physical; ++ } ++ } ++ for (int64_t slot = 0; slot < width; ++slot) { ++ const int32_t physical = indices[request*index_queries*width + slot]; ++ if (physical < 0) { ++ continue; ++ } ++ for (int64_t head = 0; head < kv_heads; ++head) { ++ const size_t src = head*physical_rows + physical; ++ const size_t dst = (request*kv_heads + head)*width + slot; ++ // Preserve the exact encoded block bytes, not re-quantized floats. ++ std::copy_n(k.data() + src*row_k, row_k, logical_k.data() + dst*row_k); ++ std::copy_n(v.data() + src*row_v, row_v, logical_v.data() + dst*row_v); ++ } ++ } ++ for (int64_t query = 0; query < mask_queries; ++query) { ++ const int64_t iq = spec.query_local ? std::min(query, spec.queries - 1) : 0; ++ const int32_t count = lengths[request*index_queries + iq]; ++ for (int64_t slot = 0; slot < width; ++slot) { ++ float bias = -std::numeric_limits::infinity(); ++ if (query < spec.queries && slot < count) { ++ bias = spec.mask ? -0.025f*float(slot % 7) : 0.0f; ++ if (spec.mask && slot % 11 == 3) { ++ bias = -std::numeric_limits::infinity(); ++ } ++ } ++ mask[(request*mask_queries + query)*width + slot] = ggml_fp32_to_fp16(bias); ++ } ++ } ++ } ++ } ++}; ++ ++struct graph_fixture { ++ ggml_context * ctx = nullptr; ++ ggml_backend_buffer_t buffer = nullptr; ++ ggml_tensor * q = nullptr; ++ ggml_tensor * k = nullptr; ++ ggml_tensor * v = nullptr; ++ ggml_tensor * mask = nullptr; ++ ggml_tensor * indices = nullptr; ++ ggml_tensor * lengths = nullptr; ++ ggml_tensor * sinks = nullptr; ++ ggml_tensor * output = nullptr; ++ ggml_cgraph * graph = nullptr; ++ const bool indexed; ++ ++ graph_fixture(ggml_backend_t backend, const inputs & data, bool use_indices) : indexed(use_indices) { ++ ggml_init_params params{32*ggml_tensor_overhead() + ggml_graph_overhead_custom(32, false), nullptr, true}; ++ ctx = ggml_init(params); ++ require(ctx != nullptr, "allocate graph context"); ++ if (data.spec.strided_query) { ++ auto storage = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, 2*data.spec.queries, data.spec.heads, requests); ++ q = ggml_view_4d(ctx, storage, data.spec.dk, data.spec.queries, data.spec.heads, requests, ++ 2*storage->nb[1], storage->nb[2], storage->nb[3], 0); ++ } else { ++ q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, data.spec.queries, data.spec.heads, requests); ++ } ++ const int64_t rows = indexed ? data.physical_rows : data.spec.logical_rows; ++ const int64_t streams = indexed ? 1 : requests; ++ k = ggml_new_tensor_4d(ctx, data.spec.type_k, data.spec.dk, rows, kv_heads, streams); ++ v = ggml_new_tensor_4d(ctx, data.spec.type_v, data.spec.dv, rows, kv_heads, streams); ++ // Dense reference always masks the padding excluded by indexed lengths. ++ if (!indexed || data.spec.mask) { ++ mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, data.spec.logical_rows, data.mask_queries, 1, requests); ++ } ++ if (indexed) { ++ indices = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, data.spec.logical_rows, data.index_queries, 1, requests); ++ lengths = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, 1, data.index_queries, 1, requests); ++ output = ggml_flash_attn_ext_indexed(ctx, q, k, v, mask, indices, lengths, ++ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, 0.0f); ++ } else { ++ output = ggml_flash_attn_ext(ctx, q, k, v, mask, ++ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, 0.0f); ++ } ++ if (data.spec.sinks) { ++ sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, data.spec.heads); ++ ggml_flash_attn_ext_add_sinks(output, sinks); ++ } ++ ggml_prec_set_acc(output, GGML_PREC_F32); ++ require(ggml_backend_supports_op(backend, output), "selected backend does not support indexed test shape"); ++ graph = ggml_new_graph_custom(ctx, 32, false); ++ ggml_build_forward_expand(graph, output); ++ buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); ++ require(buffer != nullptr, "allocate backend graph tensors"); ++ } ++ ++ ~graph_fixture() { ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++ } ++ graph_fixture(const graph_fixture &) = delete; ++ graph_fixture & operator=(const graph_fixture &) = delete; ++ ++ std::vector run(ggml_backend_t backend, const inputs & data) { ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t head = 0; head < data.spec.heads; ++head) { ++ for (int64_t query = 0; query < data.spec.queries; ++query) { ++ const size_t offset = request*q->nb[3] + head*q->nb[2] + query*q->nb[1]; ++ const size_t source = ((request*data.spec.heads + head)*data.spec.queries + query)*data.spec.dk; ++ ggml_backend_tensor_set(q, data.q.data() + source, offset, data.spec.dk*sizeof(float)); ++ } ++ } ++ } ++ ggml_backend_tensor_set(k, indexed ? data.k.data() : data.logical_k.data(), 0, ggml_nbytes(k)); ++ ggml_backend_tensor_set(v, indexed ? data.v.data() : data.logical_v.data(), 0, ggml_nbytes(v)); ++ if (mask) { ++ ggml_backend_tensor_set(mask, data.mask.data(), 0, ggml_nbytes(mask)); ++ } ++ if (indices) { ++ ggml_backend_tensor_set(indices, data.indices.data(), 0, ggml_nbytes(indices)); ++ ggml_backend_tensor_set(lengths, data.lengths.data(), 0, ggml_nbytes(lengths)); ++ } ++ if (sinks) { ++ ggml_backend_tensor_set(sinks, data.sinks.data(), 0, ggml_nbytes(sinks)); ++ } ++ require(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS, "compute attention graph"); ++ std::vector result(ggml_nelements(output)); ++ ggml_backend_tensor_get(output, result.data(), 0, ggml_nbytes(output)); ++ return result; ++ } ++}; ++ ++void compare(const std::vector & expected, const std::vector & actual, ++ const inputs & data, const char * backend, int phase) { ++ double maximum_nmse = 0.0; ++ float max_absolute = 0.0f; ++ const size_t request_elements = data.spec.dv*data.spec.heads*data.spec.queries; ++ for (int64_t request = 0; request < requests; ++request) { ++ double error = 0.0, energy = 0.0; ++ for (size_t i = request*request_elements; i < (request + 1)*request_elements; ++i) { ++ require(std::isfinite(expected[i]) && std::isfinite(actual[i]), "non-finite attention output"); ++ const double delta = double(expected[i]) - actual[i]; ++ error += delta*delta; ++ energy += double(expected[i])*expected[i]; ++ max_absolute = std::max(max_absolute, float(std::abs(delta))); ++ } ++ if (energy == 0.0) { ++ require(error == 0.0, "empty request must produce exact zero output"); ++ } else { ++ maximum_nmse = std::max(maximum_nmse, error/energy); ++ require(error/energy <= max_nmse, "indexed attention exceeds existing FA NMSE tolerance"); ++ } ++ } ++ std::printf("PASS backend=%s K=%s V=%s dk=%lld dv=%lld heads=%lld bias=%.2f q=%lld logical=%lld mask=%d sinks=%d query_local=%d strided_q=%d phase=%d max_request_nmse=%.9g max_abs=%.9g\n", ++ backend, ggml_type_name(data.spec.type_k), ggml_type_name(data.spec.type_v), ++ (long long) data.spec.dk, (long long) data.spec.dv, (long long) data.spec.heads, ++ data.spec.mask ? data.spec.max_bias : 0.0f, (long long) data.spec.queries, (long long) data.spec.logical_rows, ++ data.spec.mask, data.spec.sinks, data.spec.query_local, data.spec.strided_query, phase, maximum_nmse, max_absolute); ++} ++ ++void set_threads(ggml_backend_t backend) { ++ const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)); ++ const auto setter = reinterpret_cast( ++ ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads")); ++ if (setter) { ++ setter(backend, 4); ++ } ++} ++ ++// Accept an exact device (e.g. MTL0/CUDA0) or its registry (Metal/CUDA). ++ggml_backend_t open_backend(const char * name) { ++ if (auto exact = ggml_backend_init_by_name(name, nullptr)) { ++ return exact; ++ } ++ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { ++ auto device = ggml_backend_dev_get(i); ++ const auto registry = ggml_backend_dev_backend_reg(device); ++ if (std::strcmp(ggml_backend_reg_name(registry), name) == 0) { ++ return ggml_backend_dev_init(device, nullptr); ++ } ++ } ++ return nullptr; ++} ++ ++void run_case(ggml_backend_t cpu, ggml_backend_t target, attention_case spec) { ++ inputs data(spec); ++ graph_fixture reference(cpu, data, false); ++ graph_fixture indexed(cpu, data, true); ++ std::unique_ptr device; ++ if (target != cpu) { ++ if (ggml_backend_supports_op(target, indexed.output)) { ++ device = std::make_unique(target, data, true); ++ } else { ++ const bool dense_supported = ggml_backend_supports_op(target, reference.output); ++ require(!spec.mask || spec.query_local || !dense_supported, ++ "selected backend must support the canonical masked request-local shape"); ++ std::printf("SKIP optional backend=%s K=%s V=%s q=%lld mask=%d query_local=%d dense_admission=%d: indexed shape explicitly unsupported; CPU verification remains required\n", ++ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), ++ (long long) spec.queries, spec.mask, spec.query_local, dense_supported); ++ } ++ } ++ for (int phase = 0; phase < 2; ++phase) { ++ data.refresh(phase); ++ const auto expected = reference.run(cpu, data); ++ compare(expected, indexed.run(cpu, data), data, ggml_backend_name(cpu), phase); ++ if (device) { ++ compare(expected, device->run(target, data), data, ggml_backend_name(target), phase); ++ } ++ } ++} ++} // namespace ++ ++int main(int argc, char ** argv) { ++ try { ++ require(argc == 1 || (argc == 3 && std::strcmp(argv[1], "--backend") == 0), ++ "usage: test-flash-attn-indexed [--backend DEVICE_NAME]"); ++ ggml_backend_load_all(); ++ using backend_ptr = std::unique_ptr; ++ backend_ptr cpu(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr), ggml_backend_free); ++ require(cpu != nullptr, "CPU reference backend unavailable"); ++ set_threads(cpu.get()); ++ backend_ptr selected(nullptr, ggml_backend_free); ++ if (argc == 3) { ++ selected.reset(open_backend(argv[2])); ++ require(selected != nullptr, "requested backend unavailable"); ++ } else { ++ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)); ++ if (!selected) { ++ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr)); ++ } ++ } ++ const bool selected_cpu = selected && ++ ggml_backend_dev_type(ggml_backend_get_device(selected.get())) == GGML_BACKEND_DEVICE_TYPE_CPU; ++ auto target = selected && !selected_cpu ? selected.get() : cpu.get(); ++ std::printf("indexed FA: CPU reference and target=%s; per-request NMSE limit=%.9g\n", ggml_backend_name(target), max_nmse); ++ for (int64_t queries : {1, 4, 31, 32, 64}) { ++ run_case(cpu.get(), target, {queries, 256, true, true}); ++ } ++ run_case(cpu.get(), target, {1, 4352, true, true}); ++ run_case(cpu.get(), target, {4, 256, false, false}); ++ run_case(cpu.get(), target, {31, 256, true, false, true}); ++ run_case(cpu.get(), target, {32, 256, true, true, false, true}); ++ const std::array types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, ++ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}; ++ for (auto type_k : types) { ++ for (auto type_v : types) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, type_k, type_v}); ++ } ++ } ++ } ++ const std::array, 13> head_shapes = {{{32, 32}, {64, 64}, {96, 96}, ++ {96, 64}, {128, 128}, {128, 96}, {192, 192}, {192, 128}, {256, 256}, ++ {320, 256}, {512, 512}, {576, 512}, {128, 64}}}; ++ for (const auto & dimensions : head_shapes) { ++ for (auto type : types) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimensions[0], dimensions[1]}); ++ } ++ } ++ } ++ // CUDA's larger-head kernels require zero ALiBi and admitted GQA tile ratios. ++ const std::array, 5> wide_shapes = {{{192, 128, 16}, ++ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; ++ for (const auto & dimensions : wide_shapes) { ++ for (auto type : types) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimensions[0], dimensions[1], 0.0f, dimensions[2]}); ++ } ++ } ++ } ++ for (int64_t dimension : {40, 48, 72, 80, 112}) { ++ for (auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimension, dimension}); ++ } ++ } ++ } ++ return 0; ++ } catch (const std::exception & error) { ++ std::fprintf(stderr, "indexed FA test failed: %s\n", error.what()); ++ return 1; ++ } ++} +-- +2.56.0 + diff --git a/todo.md b/todo.md index 3e0d9c8bd1..99071e57fc 100644 --- a/todo.md +++ b/todo.md @@ -39,6 +39,16 @@ Small generated native fixtures supplement this matrix; they do not replace it. - [ ] Measure identical cold work after retaining additional prefixes. Compare attention kernel time, matrix multiplication, transfers, and mask/input work against standard vanilla to catch costs that grow with idle physical KV cells. +- [ ] Exercise every KV format supported by the CUDA and Metal attention paths, + including supported mixed K/V types, in prefill and decode. Verify indexed GPU + execution, unequal lengths, recycled physical rows, and graph reuse; CPU or + dense-path fallback must not count as quantized indexed-attention coverage. +- [ ] Run real-model prefill and generated-token tests across all four models on + **CUDA, Metal, and CPU**, with flash attention and unified KV explicitly + enabled. Cover F16 and every KV format and mixed K/V combination supported by + each backend; include cold execution, retained-prefix pressure, warm reuse, + and checkpoint restoration. Keep the operator matrix as a separate gate; + generated fixtures and kernel tests do not replace these runs. - [ ] Test cache-off controls and c1 generated-content parity. Output-token counts and their hashes alone are not generated-token correctness evidence. - [ ] Test the default 1 GiB checkpoint budget and an explicit larger budget, @@ -66,6 +76,18 @@ Small generated native fixtures supplement this matrix; they do not replace it. - [ ] Verify source, model, binary, test binary, runtime leaf, ABI, patch digest, image, client, and corpus identities before measuring. Reject stale or nested runtime bundles and require proof of real GPU execution. +- [ ] Verify the effective native graph after execution: flash-attention nodes + must consume the request indices and lengths and execute on the requested + `MTL0`, `CUDA0`, or CPU backend, with the expected K/V types. Weight placement + or requested flags alone do not prove this. Missing backend support, disabled + FA, dense fallback, or execution on the wrong backend must fail the required + gate rather than silently pass or skip it. CPU execution is required for CPU + jobs and is a failure for required Metal/CUDA jobs. +- [ ] Provide test entrypoints that can set FA, unified KV, and K/V types + explicitly even when an ordinary CLI omits those options. Keep default CPU + reference tests separate from explicit required CPU/Metal/CUDA model runs. + Record real generated output and preserve failed numerical comparisons without + loosening their gates. - [ ] Schedule independent jobs across equivalent available Sparks without stacking measurements on one GPU. Current excluded nodes are `spark-000280` (`spark-db08`) and `spark-000499` (`spark-9f06`); enforce exclusions through the @@ -75,4 +97,4 @@ Small generated native fixtures supplement this matrix; they do not replace it. classify unsupported or missing required evidence explicitly. - [ ] Report correctness separately from performance regressions. Document the commands and run the reusable suite across all four models on the allowed - machines, with CUDA and Metal coverage recorded separately. + machines, with CUDA, Metal, and CPU coverage recorded separately. From 493892c56d352a16e9a3f565c6c01e6513fc7252 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 16:52:59 +1100 Subject: [PATCH 07/81] docs(skippy): distinguish attention layout rounding from indexing --- .../docs/design/INDEXED_ATTENTION_STATUS.md | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md index 6620aeb185..2166c0cd3c 100644 --- a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -1,8 +1,9 @@ # Indexed KV attention: review candidate -Status on 2026-10-31: implementation available for review; actual-model CUDA -numerical parity fails. This candidate is not qualified for deployment or -throughput comparisons. +Status on 2026-10-31: implementation available for review. The first real-model +attention layer matches existing dense CUDA attention exactly with the same +logical layout. Comparison against the old physical layout still fails. Full +model and cache validation remains in progress; no new throughput is qualified. ## Change @@ -47,7 +48,42 @@ indexed/indexed repeats each have zero logit delta and zero greedy differences. Dense/indexed comparisons fail the unchanged `1e-6` full-vocabulary gate: maximum logit delta `0.284694672`, with one greedy difference. Divergence is already present at the first decode step; this is not only accumulated drift. -Performance runs and other-model fanout remain blocked pending diagnosis. +That failed comparison remains recorded and has not been relabeled as a pass. + +## Controlled attention replay + +Jobs `job_fp9kyakwncmatr5` and `job_nxze85xz8tsvhd5` isolate the first actual +attention layer using the saved canonical state, without another prefill. +Queries, complete physical K/V payloads, selected rows, and selected masks are +byte-identical across the two model executions. The newly written token is +present in each request's 23,498 visible rows. Capturing the layer does not +change either execution's final logits. + +Replaying the captured inputs produces these results: + +- Original physical dense replay reproduces the captured dense output exactly. +- Indexed replay reproduces the captured indexed output exactly. +- Existing dense CUDA attention with compact request-local K/V produces + **bit-identical output to indexed attention**, across all 16,384 output values. + Both select the same MMA specialization, launch geometry, and logical extent. +- Changing only the existing dense operation's query layout changes its output + by up to `0.00948334`. Compacting its physical extent then changes its output + by up to `0.00588727`. Neither comparison uses the indexed reader. + +The existing CUDA kernel accumulates probability-times-value products in half +precision. Layout and span change its partitioning and rounding history. An +independent FP64 calculation on the worst differing head finds errors in both +layouts; the compact/indexed result is not uniformly more accurate than the old +physical result. The ordinary CPU FA implementation also uses half accumulation +for this F16-V shape, so it is not an independent FP32 oracle here. + +The next gates retain the existing numerical limits: indexed versus existing +dense attention at the **same logical geometry** (`1e-6`), independent FP64 +attention references using the existing operator per-request NMSE limit +(`5e-4`), and unchanged full-model checkpoint/cache assertions. These controls +are being extended across all attention layers. The old physical-layout +full-model comparison remains a separate failed diagnostic; its tolerance is +not being raised to qualify the candidate. The reusable four-model CUDA/Metal/CPU validation work is tracked in [todo.md](../../../todo.md). From 52ee08743a4858c36962b6c05598c2017c88b952 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 17:33:44 +1100 Subject: [PATCH 08/81] perf(ggml): bound indexed attention tuning and mask construction --- .../docs/design/INDEXED_ATTENTION_STATUS.md | 75 ++++++++++++++----- ...equest-local-KV-indices-in-flash-att.patch | 58 +++++++++++--- 2 files changed, 102 insertions(+), 31 deletions(-) diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md index 2166c0cd3c..b833ac9147 100644 --- a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -1,9 +1,10 @@ # Indexed KV attention: review candidate -Status on 2026-10-31: implementation available for review. The first real-model -attention layer matches existing dense CUDA attention exactly with the same -logical layout. Comparison against the old physical layout still fails. Full -model and cache validation remains in progress; no new throughput is qualified. +Status on 2026-10-31: implementation available for review. All eight real-model +attention layers match existing dense CUDA attention exactly at the same logical +layout. Strict cache tests pass on CUDA and Metal. Comparison against the old +physical layout still fails; that diagnostic is retained below. Final performance +qualification and four-model CUDA coverage are in progress. ## Change @@ -22,20 +23,25 @@ reviewers can inspect it independently. ## Validation - Clean replay from native upstream `620d2225cc436ab0b001e3200e590e3b286ef9ab` - produces native HEAD `3e756354af978f8a3432a22df7e1465363538ee8`, tree - `d9963c3bedb9f1d6658821784a897c149ad1bccf`, queue digest - `194c5d51170a0e9a47dbe8268f1a2422323e8088fb0cd68aa20ad52f9dd94c88`. + produces native HEAD `1b3f2e6fc36d020260b61c672e168da51d8310a7`, tree + `bdb3081b92c7af8261500aec37af89046104201c`, queue digest + `4035b2c99d9ddc9c9597f363210e7734a884b84f5f3b0b9b18e1730d51710740`. - Operator comparisons pass: 910 CPU, 654 Metal, and 608 CUDA. CUDA graphs are enabled. The existing per-request NMSE limit remains `5e-4`. Cases already unsupported by a backend's dense operator remain explicitly unsupported. -- Real Qwen3.5-4B smoke tests pass on CPU and Metal for all eight supported - same-type KV formats. Graph checks require indices, lengths, the requested - KV type, and the selected backend throughout prefill and decode. These are - execution smoke checks, not cross-path numerical parity evidence. +- Real Qwen3.5-4B smoke tests pass for all eight supported same-type Metal KV + formats and all 64 CPU mixed K/V pairs. Graph checks require indices, lengths, + the requested KV type, and the selected backend throughout prefill and decode. + These are execution smoke checks, not cross-path numerical parity evidence. +- Final CUDA proof job `job_x7fs8vb280zjz00`, run `run_nd0p378y1k069ct`, passes + all eight real-model attention-layer replays, resident ownership checks, and + the unchanged Qwen3.5-4B chat-parity and growing-checkpoint tests. The final + local Metal runtime passes those same two cache regressions and exact-leaf + runtime discovery. - The prior local native suite completed with 285 executed tests passing and one explicitly skipped long GPU test. -## Blocking CUDA result +## Retained physical-layout CUDA diagnostic JY job `job_yg6c28ny2f5k9hn`, run `run_wkzw1rnq1ccps94`, on Spark 000137 built and packaged this candidate and passed operator and small resident tests. @@ -77,13 +83,44 @@ layouts; the compact/indexed result is not uniformly more accurate than the old physical result. The ordinary CPU FA implementation also uses half accumulation for this F16-V shape, so it is not an independent FP32 oracle here. -The next gates retain the existing numerical limits: indexed versus existing -dense attention at the **same logical geometry** (`1e-6`), independent FP64 -attention references using the existing operator per-request NMSE limit -(`5e-4`), and unchanged full-model checkpoint/cache assertions. These controls -are being extended across all attention layers. The old physical-layout -full-model comparison remains a separate failed diagnostic; its tolerance is -not being raised to qualify the candidate. +The completed controls retain the existing numerical limits: indexed versus +existing dense attention at the **same logical geometry** (`1e-6`), independent +FP64 attention references using the existing operator per-request NMSE limit +(`5e-4`), and unchanged full-model checkpoint/cache assertions. All eight actual +attention layers match compact dense bit for bit. Across every query head and +layer, CUDA's worst per-request NMSE is `3.321e-6` against true F32 queries or +`3.324e-6` against rounded F16 queries; the new CPU indexed reader's worst values +are `1.356e-7` and `8.187e-10`, respectively. The old physical-layout full-model +comparison remains a separate failed diagnostic; its tolerance was not raised. + +## Measured cost and final host change + +The v3 pressure run (`job_01ge0nmkfdfp0xg`) completed all 25 requests. Keeping +additional idle prefixes no longer increases attention work: three equal cold +waves took `28.69 / 28.59 / 28.42 s`, versus `33.15 / 53.81 / 74.22 s` before +indexed reads. CUDA attention time stayed `4.26 / 4.28 / 4.26 s`, versus +`10.11 / 29.92 / 49.57 s` before. Standard vanilla's waves took +`24.36 / 24.74 / 25.12 s`, so removing that scaling cost alone did not establish +parity. Warm repeats retained real prefix hits. These are profiled pressure +diagnostics, not full AgentX throughput scores. + +The final host change fills zero-bias causal masks in contiguous spans instead +of calling the F32-to-F16 conversion helper once per visible key. Positive ALiBi +keeps its existing calculation. A bounded CPU microbenchmark verifies identical +mask bytes, including gaps, empty rows, padded rows and positive ALiBi. For four +requests with 23,552 padded keys, measured construction falls from `14.54` to +`0.53 ms` at 64 queries and from `29.14` to `1.16 ms` at 128 queries. Actual +captured CUDA inputs, attention outputs and step-zero logits remain byte-identical +to v3; no GPU kernel changed in this last step. The final pressure run +(`job_7ap9pd6carpy2b2`) passed: equal cold waves took +`27.19 / 26.96 / 27.34 s`, while attention remained `4.24 / 4.24 / 4.31 s`. +The unchanged GPU cost and lower total time agree with a host-side improvement. +The time without GPU activity falls to `1.63 / 1.36 / 1.43 s`, from +`3.09 / 2.97 / 2.87 s` in v3; standard vanilla measures +`0.73 / 1.06 / 1.39 s`. Most of the remaining pressure gap is GPU-active work, +including indexed attention's roughly `4.24 s` versus vanilla's `2.88 s`. +This still trails the saved standard-vanilla pressure control. Full fixed-cohort +job `job_agr2k8yy2ry29qe` is the separate performance qualification. The reusable four-model CUDA/Metal/CPU validation work is tracked in [todo.md](../../../todo.md). diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch index 0e9a27c3a3..d8da32bd6a 100644 --- a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch +++ b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch @@ -1,6 +1,6 @@ -From f644ed55e3ed368fc752f8aa7b37a8829a94a7ce Mon Sep 17 00:00:00 2001 +From 49e7635856484a30c1e98fc5755e50c933d26306 Mon Sep 17 00:00:00 2001 From: Mesh-LLM CI -Date: Sat, 31 Oct 2026 16:18:58 +1100 +Date: Sat, 31 Oct 2026 17:14:46 +1100 Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention --- @@ -18,7 +18,7 @@ Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention ggml/src/ggml-cuda/fattn-mma-f16.cuh | 208 ++++++---- ggml/src/ggml-cuda/fattn-tile.cuh | 95 ++++- ggml/src/ggml-cuda/fattn-vec.cuh | 53 ++- - ggml/src/ggml-cuda/fattn.cu | 63 ++- + ggml/src/ggml-cuda/fattn.cu | 68 +++- ggml/src/ggml-cuda/ggml-cuda.cu | 1 + ggml/src/ggml-et/ggml-et.cpp | 3 + ggml/src/ggml-hexagon/ggml-hexagon.cpp | 2 +- @@ -36,7 +36,7 @@ Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention ggml/src/ggml-webgpu/ggml-webgpu.cpp | 2 +- ggml/src/ggml.c | 44 +- src/CMakeLists.txt | 2 + - src/llama-graph-kv-read.cpp | 126 ++++++ + src/llama-graph-kv-read.cpp | 134 +++++++ src/llama-graph.cpp | 85 ++-- src/llama-graph.h | 21 +- src/llama-kv-cache.h | 2 + @@ -44,7 +44,7 @@ Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention src/llama-kv-read.h | 20 + tests/CMakeLists.txt | 2 + tests/test-flash-attn-indexed.cpp | 378 ++++++++++++++++++ - 40 files changed, 1687 insertions(+), 207 deletions(-) + 40 files changed, 1698 insertions(+), 209 deletions(-) create mode 100644 ggml/src/ggml-cpu/attention-indexed.cpp create mode 100644 ggml/src/ggml-cpu/attention-indexed.h create mode 100644 ggml/src/ggml-cuda/fattn-indexed.cuh @@ -1356,7 +1356,7 @@ index 57a285565..596165504 100644 #endif // FLASH_ATTN_AVAILABLE } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu -index 5fa3e5308..3825a51f1 100644 +index 5fa3e5308..b74322b6f 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -130,6 +130,9 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ @@ -1378,7 +1378,33 @@ index 5fa3e5308..3825a51f1 100644 for (const ggml_tensor * t : {Q, K, V, mask}) { if (t == nullptr || ggml_is_quantized(t->type)) { continue; -@@ -537,6 +540,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { +@@ -357,6 +360,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg + case 576: { + // For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels. + GGML_ASSERT(V->ne[0] == 512); ++ const int64_t kv_span = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; + float max_bias = 0.0f; + memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); + +@@ -375,7 +379,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg + break; + } + if (cc >= GGML_CUDA_CC_BLACKWELL) { +- if (Q->ne[1] <= 4 && K->ne[1] >= 65536) { ++ if (Q->ne[1] <= 4 && kv_span >= 65536) { + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + break; + } +@@ -392,7 +396,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg + } + if (cc >= GGML_CUDA_CC_TURING) { + if (Q->ne[1] <= 4) { +- if (K->ne[1] <= 16384) { ++ if (kv_span <= 16384) { + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + break; + } +@@ -537,6 +541,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { } } @@ -1406,7 +1432,7 @@ index 5fa3e5308..3825a51f1 100644 static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { #ifndef FLASH_ATTN_AVAILABLE GGML_UNUSED(device); GGML_UNUSED(dst); -@@ -557,7 +581,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const +@@ -557,7 +582,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const // The effective batch size for the kernel can be increased by gqa_ratio. // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded, @@ -1415,7 +1441,7 @@ index 5fa3e5308..3825a51f1 100644 for (const ggml_tensor * t : {Q, K, V, mask}) { if (t == nullptr || ggml_is_quantized(t->type)) { continue; -@@ -629,9 +653,40 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const +@@ -629,9 +654,40 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; } @@ -1457,7 +1483,7 @@ index 5fa3e5308..3825a51f1 100644 // If Turing tensor cores are available, use them: if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { -@@ -749,7 +804,7 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d +@@ -749,7 +805,7 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d } const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra = @@ -2446,10 +2472,10 @@ index d55e38363..0e9996f97 100644 llama-kv-cache-dsa-iswa.cpp diff --git a/src/llama-graph-kv-read.cpp b/src/llama-graph-kv-read.cpp new file mode 100644 -index 000000000..69788b4ec +index 000000000..379c7f458 --- /dev/null +++ b/src/llama-graph-kv-read.cpp -@@ -0,0 +1,126 @@ +@@ -0,0 +1,134 @@ +#include "llama-graph.h" + +#include "llama-cparams.h" @@ -2558,11 +2584,19 @@ index 000000000..69788b4ec + const uint32_t queries = read_plan.queries_per_request; + std::vector mask(ggml_nelements(self_read_mask)); + const ggml_fp16_t drop = ggml_fp32_to_fp16(-INFINITY); ++ const ggml_fp16_t keep = ggml_fp32_to_fp16(0.0f); + std::fill(mask.begin(), mask.end(), drop); + for (uint32_t request = 0; request < read_plan.request_count; ++request) { ++ const auto * begin = read_plan.positions.data() + static_cast(request) * extent; ++ const auto * end = begin + read_plan.lengths[request]; + for (uint32_t query = 0; query < queries; ++query) { + const llama_pos position = ubatch.pos[request * queries + query]; + auto * row = mask.data() + (static_cast(request) * queries + query) * extent; ++ if (hparams.f_max_alibi_bias <= 0) { ++ const auto * visible = std::upper_bound(begin, end, position); ++ std::fill(row, row + (visible - begin), keep); ++ continue; ++ } + for (int32_t slot = 0; slot < read_plan.lengths[request]; ++slot) { + const llama_pos key_position = read_plan.positions[request * extent + slot]; + if (key_position > position) { From 88c0e4af4180dca2ad128629228bae2e136256a0 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 17:48:25 +1100 Subject: [PATCH 09/81] test(skippy): add reusable four-model KV validation commands --- just/skippy.just | 10 + skippy/crates/skippy-correctness/README.md | 7 + .../src/openai_cache_reuse.rs | 38 +- .../src/openai_cache_reuse/tests.rs | 51 ++- skippy/evals/kv-validation/README.md | 106 +++++ skippy/evals/kv-validation/cell.example.json | 8 + skippy/evals/kv-validation/fleet.example.json | 10 + skippy/evals/kv-validation/models.json | 58 +++ .../evals/kv-validation/native/CMakeLists.txt | 16 + .../native/indexed-real-kv-matrix.cpp | 195 +++++++++ .../evals/kv-validation/producer.example.json | 14 + todo.md | 44 +- tools/xtask/src/automation/kv_validation.rs | 83 ++++ .../src/automation/kv_validation/contract.rs | 199 +++++++++ .../src/automation/kv_validation/evidence.rs | 159 ++++++++ .../src/automation/kv_validation/execution.rs | 308 ++++++++++++++ .../src/automation/kv_validation/jy_plan.rs | 136 +++++++ .../automation/kv_validation/preparation.rs | 133 +++++++ .../src/automation/kv_validation/server.rs | 239 +++++++++++ .../src/automation/kv_validation/tests.rs | 376 ++++++++++++++++++ tools/xtask/src/automation/mod.rs | 1 + .../automation/native_artifact_identity.rs | 2 +- tools/xtask/src/cli.rs | 5 + tools/xtask/src/main.rs | 1 + 24 files changed, 2189 insertions(+), 10 deletions(-) create mode 100644 skippy/evals/kv-validation/README.md create mode 100644 skippy/evals/kv-validation/cell.example.json create mode 100644 skippy/evals/kv-validation/fleet.example.json create mode 100644 skippy/evals/kv-validation/models.json create mode 100644 skippy/evals/kv-validation/native/CMakeLists.txt create mode 100644 skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp create mode 100644 skippy/evals/kv-validation/producer.example.json create mode 100644 tools/xtask/src/automation/kv_validation.rs create mode 100644 tools/xtask/src/automation/kv_validation/contract.rs create mode 100644 tools/xtask/src/automation/kv_validation/evidence.rs create mode 100644 tools/xtask/src/automation/kv_validation/execution.rs create mode 100644 tools/xtask/src/automation/kv_validation/jy_plan.rs create mode 100644 tools/xtask/src/automation/kv_validation/preparation.rs create mode 100644 tools/xtask/src/automation/kv_validation/server.rs create mode 100644 tools/xtask/src/automation/kv_validation/tests.rs diff --git a/just/skippy.just b/just/skippy.just index b3e2c9ec8c..075d327839 100644 --- a/just/skippy.just +++ b/just/skippy.just @@ -1,3 +1,13 @@ +# Prepare the pinned evaluator once, then run or plan explicit model cells. +skippy-kv-prepare input output: + @just automation-run automation kv-validation prepare --input "{{ input }}" --output "{{ output }}" + +skippy-kv-validate input output: + @just automation-run automation kv-validation run --input "{{ input }}" --output "{{ output }}" + +skippy-kv-jy-plan input output: + @just automation-run automation kv-validation jy-plan --input "{{ input }}" --output "{{ output }}" + # Build the complete standalone Skippy product for local iteration. [unix] skippy backend="" cuda_arch="" rocm_arch="": diff --git a/skippy/crates/skippy-correctness/README.md b/skippy/crates/skippy-correctness/README.md index a6326e2970..9af034162c 100644 --- a/skippy/crates/skippy-correctness/README.md +++ b/skippy/crates/skippy-correctness/README.md @@ -30,6 +30,13 @@ against recompute. ## Commands +`open-ai-cache-reuse` targets a fresh endpoint and verifies deterministic cold, +repeat and growing-chat reuse. It requires an uncached nonempty seed, actual +cache hits and byte-identical generated content on both repeats, using +temperature 0 and seed 42. Its JSON retains generated content separately from +the cache-token accounting. The manual four-model owner is documented in +[KV validation](../../evals/kv-validation/README.md). + ```bash skippy-correctness single-step \ --model model.gguf \ diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs index 05e0d31f51..c7d652ad21 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs @@ -24,31 +24,47 @@ pub fn run(args: OpenAiCacheReuseArgs) -> Result<()> { let url = format!("{}/chat/completions", args.base_url.trim_end_matches('/')); let first_turn = vec![json!({"role": "user", "content": prompt})]; let seed = complete(&client, &url, &args.model, &first_turn, args.max_tokens)?; + ensure!( + seed.cached_tokens == 0, + "cold seed unexpectedly reused a prompt prefix" + ); + ensure!(!seed.content.is_empty(), "cold seed returned empty content"); let repeat = complete(&client, &url, &args.model, &first_turn, args.max_tokens)?; require_hit("repeat", &repeat)?; + require_content("repeat", &seed, &repeat)?; let mut growing_turn = first_turn; - growing_turn.push(json!({"role": "assistant", "content": seed.content})); + growing_turn.push(json!({"role": "assistant", "content": seed.content.clone()})); growing_turn.push(json!({"role": "user", "content": "Summarize your answer in one word."})); let grown_seed = complete(&client, &url, &args.model, &growing_turn, args.max_tokens)?; require_hit("growing chat", &grown_seed)?; + ensure!( + !grown_seed.content.is_empty(), + "growing chat returned empty content" + ); let grown_repeat = complete(&client, &url, &args.model, &growing_turn, args.max_tokens)?; require_hit("growing chat repeat", &grown_repeat)?; + require_content("growing chat repeat", &grown_seed, &grown_repeat)?; println!( "{}", - serde_json::to_string_pretty(&json!({ + serde_json::to_string(&json!({ "status": "pass", + "content_parity": "exact", + "cold_content": seed.content, "repeat": { "cached_tokens": repeat.cached_tokens, - "prompt_tokens": repeat.prompt_tokens + "prompt_tokens": repeat.prompt_tokens, + "content": repeat.content }, "growing_chat_repeat": { "cached_tokens": grown_repeat.cached_tokens, - "prompt_tokens": grown_repeat.prompt_tokens + "prompt_tokens": grown_repeat.prompt_tokens, + "content": grown_repeat.content }, "growing_chat": { "cached_tokens": grown_seed.cached_tokens, - "prompt_tokens": grown_seed.prompt_tokens + "prompt_tokens": grown_seed.prompt_tokens, + "content": grown_seed.content } }))? ); @@ -68,6 +84,8 @@ fn complete( "model": model, "messages": messages, "max_tokens": max_tokens, + "temperature": 0, + "seed": 42, "reasoning_effort": "none" })) .send() @@ -95,6 +113,16 @@ fn complete( }) } +fn require_content(label: &str, expected: &Completion, actual: &Completion) -> Result<()> { + ensure!( + actual.content == expected.content, + "{label} generated-content mismatch: expected={:?} actual={:?}", + expected.content, + actual.content + ); + Ok(()) +} + fn require_hit(label: &str, completion: &Completion) -> Result<()> { ensure!( completion.cached_tokens > 0 && completion.cached_tokens <= completion.prompt_tokens, diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs index 493c9da15a..72c5cd6368 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs @@ -44,6 +44,11 @@ struct Peer { impl Peer { fn new(cached: [u64; 4]) -> Self { + Self::with_content(cached, ["answer-0", "answer-0", "answer-2", "answer-2"]) + } + + fn with_content(cached: [u64; 4], content: [&str; 4]) -> Self { + let content = content.map(str::to_owned); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); let base_url = format!("http://{}/v1", listener.local_addr().unwrap()); @@ -67,7 +72,7 @@ impl Peer { let index = requests.len(); requests.push(request); let response = json!({ - "choices": [{"message": {"content": format!("answer-{index}")}}], + "choices": [{"message": {"content": content.get(index).cloned().unwrap_or_default()}}], "usage": {"prompt_tokens": 100, "prompt_tokens_details": {"cached_tokens": cached.get(index).copied().unwrap_or(0)}} }).to_string(); @@ -152,11 +157,13 @@ fn assert_sequence(requests: &[Value]) { assert_eq!(request["model"], "fixture-model"); assert_eq!(request["max_tokens"], 8); assert_eq!(request["reasoning_effort"], "none"); + assert_eq!(request["temperature"], 0); + assert_eq!(request["seed"], 42); assert_eq!( request["messages"][0], json!({"role": "user", "content": "A finite cache prefix.\n"}) ); - assert_eq!(request.as_object().unwrap().len(), 4); + assert_eq!(request.as_object().unwrap().len(), 6); } if requests.len() > 1 { assert_eq!( @@ -243,3 +250,43 @@ fn actual_cache_api_rejects_zero_tokens_and_empty_prompt_before_http() { ); assert!(peer.finish().is_empty()); } + +#[test] +fn generated_content_mismatch_fails_before_any_later_request() { + let prompt = Prompt::new(); + for (contents, requests_expected) in [ + (["seed", "changed", "grown", "grown"], 2), + (["seed", "seed", "grown", "changed"], 4), + ] { + let peer = Peer::with_content([0, 50, 50, 50], contents); + let error = run(args(&peer, &prompt)).unwrap_err().to_string(); + assert!(error.contains("generated-content mismatch"), "{error}"); + assert_eq!(peer.finish().len(), requests_expected); + } +} + +#[test] +fn cold_seed_must_be_uncached_and_nonempty() { + let prompt = Prompt::new(); + for (cached, contents, expected) in [ + ( + [1, 50, 50, 50], + ["seed", "seed", "grown", "grown"], + "cold seed unexpectedly", + ), + ( + [0, 50, 50, 50], + ["", "", "grown", "grown"], + "cold seed returned empty", + ), + ] { + let peer = Peer::with_content(cached, contents); + assert!( + run(args(&peer, &prompt)) + .unwrap_err() + .to_string() + .contains(expected) + ); + assert_eq!(peer.finish().len(), 1); + } +} diff --git a/skippy/evals/kv-validation/README.md b/skippy/evals/kv-validation/README.md new file mode 100644 index 0000000000..e5d7866c79 --- /dev/null +++ b/skippy/evals/kv-validation/README.md @@ -0,0 +1,106 @@ +# Four-model KV validation foundation + +Explicit manual validation for the four AgentX **Q4_K_M** models in +[models.json](models.json). The catalog is byte-for-byte the manifest from +`6c0464e5531a9ff8ceb89c068ad94cd53c71e334:skippy/evals/agentx/models.json`, SHA-256 +`6a2b724cf32208186d80ac614e21a168bfc08ca72e55afdabc3dc39b338c9206`. +It pins repositories, GGUF hashes, model revisions and tokenizer revisions. +Workers never download or substitute another model. + +This foundation runs: + +* Real-model FA/unified-KV prefill (20–64 tokens) and 16 greedy decode steps. + CUDA and CPU require all 64 pairs of F32/F16/BF16/Q4_0/Q4_1/Q5_0/Q5_1/Q8_0; + Metal requires its eight supported same-type pairs and explicitly reports its + 56 preexisting unsupported mixed pairs. Each model loads **once** for this + matrix, with a fresh context per pair. Every executed attention graph must + consume indices and lengths, retain requested K/V types, and execute on the + selected CUDA0, MTL0 or CPU backend. No GPU-to-CPU or dense fallback qualifies. +* One fresh Skippy product server at c1/F16, followed by deterministic + cold/repeat/growing/repeat HTTP requests. It requires cache hits and exact + generated-content parity, not just matching output counts. +* The unchanged strict chat-parity and growing-checkpoint Rust regressions for + the catalog's two recurrent/hybrid workloads. These fixtures retain their + recurrent message-boundary assertions; dense rows use the generic HTTP gate. + +Long c4 state comparisons, L3 restart, pressure, default-budget qualification and +standard-vanilla performance comparisons remain separate work in +[todo.md](../../../todo.md). A green foundation is not throughput parity or full +KV certification. There is no automatic GPU CI trigger or new serving option. + +## Prepare once, run many + +Build the matching product/runtime and the dynamic serving test binary through +the existing Just/native workflow. Build `skippy-correctness` with the dynamic +runtime dependency feature. The producer image must contain those exact tools, +the prepared native source, the workspace and this automation executable. +Prepare once **inside that immutable image**, preserving paths across workers. +No worker rebuilds native code, Rust or the model matrix executable. + +Copy [producer.example.json](producer.example.json), replace its absolute paths +and source commit, and observe byte pins. Empty SHA fields are allowed only as +inputs to the explicit `pin` operation; `prepare` and `run` refuse missing pins. + +```sh +just automation-run automation kv-validation pin \ + --input /absolute/producer.paths.json --output /absolute/producer.pinned.json +just skippy-kv-prepare /absolute/producer.pinned.json /absolute/kv-prepared +``` + +`prepare` verifies the exact runtime leaf/backend/tree hash and tool bytes, +checks the clean native source HEAD before and after compiling the external +test harness, and emits `/absolute/kv-prepared/prepared.json`. It uses shared +libraries and matching private graph headers, without modifying the native +patch queue. Source declarations are provenance; artifact hashes and the trusted +producer image bind the executable bytes actually consumed. + +Copy [cell.example.json](cell.example.json), supply the prepared receipt SHA +(`shasum -a 256 /absolute/kv-prepared/prepared.json`) and the actual model path. +All artifact paths must be absolute and outputs fresh. + +```sh +just skippy-kv-validate /absolute/cell.json /absolute/new-evidence +``` + +Choose `cpu`, `metal` or `cuda` in the producer; run a separate prepared producer +for each backend. `run` validates the exact model SHA and GGUF dimensions, checks +the exact runtime leaf with the product doctor, supervises all children with +deadlines/cancellation, and preserves failed evidence. The fixture adapter's +runtime-parent directory contains only the doctor-verified leaf. Disk is off, +checkpoint RAM is explicitly 8 GiB, and server settings/arguments are retained. + +Output includes `result.json`, sanitized child logs, settings/identities, typed +cache content/counter evidence in `cache-evidence.json`, and a sibling +`new-evidence.tar.gz` and its `new-evidence.archive.json` hash. Runtime symlinks +are excluded from the archive; their identity remains in JSON. Required child +failure, numerical/content mismatch, missing evidence, deadline or cancellation +fails the command. Preserve both the failed receipt and evidence archive. +The cache receipt is a closed typed projection observed before log sanitization; +it preserves only the declared content, counters and status, never arbitrary +child payloads, protocol headers or environment data. + +## Explicit JY jobs + +Copy [fleet.example.json](fleet.example.json), bind the **prepared image's +immutable SHA**, automation path and prepared-receipt path/SHA, then select +eligible Sparks. The planner rejects both excluded node IDs (`spark-000280`, +`spark-000499`) and hostnames (`spark-db08`, `spark-9f06`). Each worker also checks +its actual hostname. Jobs are independent per model and reuse the prepared +image; JY's node lease queues jobs rather than stacking GPU measurements. + +```sh +just skippy-kv-jy-plan /absolute/fleet.json /absolute/new-jobs +jy submit /absolute/new-jobs/qwen3-4b-q4-k-m.json +jy submit /absolute/new-jobs/qwen3.5-4b-q4-k-m.json +jy submit /absolute/new-jobs/qwen3-coder-30b-a3b-q4-k-m.json +jy submit /absolute/new-jobs/qwen3.5-35b-a3b-q4-k-m.json +``` + +These specs use the accepted lab/custom JY schema: pinned `model_package`, +stream-delivered `AGENTX_MODEL_PATH`, immutable workspace revision, JY-owned +artifact/result paths and a thin Docker adapter invoking the typed worker. +No patches, credentials or arbitrary policy scripts are embedded. Flat result +and compressed evidence files survive JY's flat-file artifact transport. +The current JY adapter supports Linux CPU/CUDA only. Run Metal natively with the +same `prepare`/`run` commands; a native macOS JY executor requires a separately +verified executor contract and is not silently emulated in Docker. diff --git a/skippy/evals/kv-validation/cell.example.json b/skippy/evals/kv-validation/cell.example.json new file mode 100644 index 0000000000..1b39f38526 --- /dev/null +++ b/skippy/evals/kv-validation/cell.example.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "prepared": {"path": "/opt/kv-prepared/prepared.json", "sha256": "0000000000000000000000000000000000000000000000000000000000000000"}, + "model_key": "qwen3.5-4b-q4-k-m", + "model": "/models/Qwen3.5-4B-Q4_K_M.gguf", + "port": 19337, + "execution_seconds": 1800 +} diff --git a/skippy/evals/kv-validation/fleet.example.json b/skippy/evals/kv-validation/fleet.example.json new file mode 100644 index 0000000000..e9a59f3e95 --- /dev/null +++ b/skippy/evals/kv-validation/fleet.example.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "backend": "cuda", + "source_commit": "0000000000000000000000000000000000000000", + "prepared_image": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "automation": "/opt/mesh-llm/target/release/xtask", + "prepared": {"path": "/opt/kv-prepared/prepared.json", "sha256": "0000000000000000000000000000000000000000000000000000000000000000"}, + "nodes": [{"id": "spark-000137", "hostname": "spark-james"}], + "execution_seconds": 1800 +} diff --git a/skippy/evals/kv-validation/models.json b/skippy/evals/kv-validation/models.json new file mode 100644 index 0000000000..9122975b33 --- /dev/null +++ b/skippy/evals/kv-validation/models.json @@ -0,0 +1,58 @@ +[ + { + "key": "qwen3-4b-q4-k-m", + "family": "dense", + "repo": "unsloth/Qwen3-4B-Instruct-2507-GGUF", + "revision": "a06e946bb6b655725eafa393f4a9745d460374c9", + "tokenizer": "Qwen/Qwen3-4B-Instruct-2507", + "files": [ + { + "name": "Qwen3-4B-Instruct-2507-Q4_K_M.gguf", + "sha256": "3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597" + } + ], + "tokenizer_revision": "cdbee75f17c01a7cc42f958dc650907174af0554" + }, + { + "key": "qwen3.5-4b-q4-k-m", + "family": "hybrid-dense", + "repo": "unsloth/Qwen3.5-4B-GGUF", + "revision": "e87f176479d0855a907a41277aca2f8ee7a09523", + "tokenizer": "Qwen/Qwen3.5-4B", + "files": [ + { + "name": "Qwen3.5-4B-Q4_K_M.gguf", + "sha256": "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4" + } + ], + "tokenizer_revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a" + }, + { + "key": "qwen3-coder-30b-a3b-q4-k-m", + "family": "attention-moe", + "repo": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", + "revision": "b17cb02dd882d5b6ab62fc777ad2995f19668350", + "tokenizer": "Qwen/Qwen3-Coder-30B-A3B-Instruct", + "files": [ + { + "name": "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf", + "sha256": "fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad" + } + ], + "tokenizer_revision": "b2cff646eb4bb1d68355c01b18ae02e7cf42d120" + }, + { + "key": "qwen3.5-35b-a3b-q4-k-m", + "family": "hybrid-moe", + "repo": "unsloth/Qwen3.5-35B-A3B-GGUF", + "revision": "bc014a17be43adabd7066b7a86075ff935c6a4e2", + "tokenizer": "Qwen/Qwen3.5-35B-A3B", + "files": [ + { + "name": "Qwen3.5-35B-A3B-Q4_K_M.gguf", + "sha256": "3b46d1066bc91cc2d613e3bc22ce691dd77e6f0d33c9060690d24ce6de494375" + } + ], + "tokenizer_revision": "59d61f3ce65a6d9863b86d2e96597125219dc754" + } +] diff --git a/skippy/evals/kv-validation/native/CMakeLists.txt b/skippy/evals/kv-validation/native/CMakeLists.txt new file mode 100644 index 0000000000..d31901236d --- /dev/null +++ b/skippy/evals/kv-validation/native/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.20) +project(indexed_real_kv_matrix LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(NATIVE_SOURCE "" CACHE PATH "Matching prepared native source checkout") +set(NATIVE_LIB_DIR "" CACHE PATH "Exact final runtime library directory") +if(NOT EXISTS "${NATIVE_SOURCE}/src/llama-context.h") + message(FATAL_ERROR "NATIVE_SOURCE must name the matching prepared source") +endif() +foreach(component llama ggml ggml-base) + find_library(NATIVE_${component} NAMES ${component} PATHS "${NATIVE_LIB_DIR}" NO_DEFAULT_PATH REQUIRED) +endforeach() +add_executable(indexed-real-kv-matrix indexed-real-kv-matrix.cpp) +target_include_directories(indexed-real-kv-matrix PRIVATE "${NATIVE_SOURCE}/include" + "${NATIVE_SOURCE}/src" "${NATIVE_SOURCE}/ggml/include" "${NATIVE_SOURCE}/ggml/src") +target_link_libraries(indexed-real-kv-matrix PRIVATE ${NATIVE_llama} ${NATIVE_ggml} ${NATIVE_ggml-base}) +set_target_properties(indexed-real-kv-matrix PROPERTIES BUILD_RPATH "${NATIVE_LIB_DIR}") diff --git a/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp new file mode 100644 index 0000000000..9df6e1b243 --- /dev/null +++ b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp @@ -0,0 +1,195 @@ +#include "llama.h" +#include "llama-context.h" +#include "llama-graph.h" +#include "llama-model.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using clock_type = std::chrono::steady_clock; +const std::array kv_types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, + GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}; + +void require(bool value, const std::string & message) { + if (!value) throw std::runtime_error(message); +} + +ggml_type parse_type(const char * name) { + for (auto type : kv_types) { + if (std::strcmp(ggml_type_name(type), name) == 0) return type; + } + throw std::runtime_error(std::string("unsupported matrix KV type: ") + name); +} + +int inspect(llama_context * ctx, ggml_type type_k, ggml_type type_v, + const char * expected_backend, int step) { + const auto result = ctx->get_gf_res_prev_active(); + require(result != nullptr, "no active real model graph"); + const auto graph = result->get_gf(); + int attention = 0; + for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { + const auto node = ggml_graph_node(graph, i); + if (node->op != GGML_OP_FLASH_ATTN_EXT) continue; + const auto backend = ggml_backend_sched_get_tensor_backend(ctx->get_sched(), node); + require(backend && std::strcmp(ggml_backend_name(backend), expected_backend) == 0, + "real attention executed on the wrong backend"); + require(node->src[5] && node->src[6], "real flash attention missing request indices/lengths"); + require(node->src[1]->type == type_k && node->src[2]->type == type_v, "actual K/V dtype changed"); + ++attention; + if (step == 0 && attention == 1) { + std::printf("REAL_FA backend=%s K=%s V=%s q=%lld physical=%lld logical=%lld requests=%lld\n", + ggml_backend_name(backend), ggml_type_name(type_k), ggml_type_name(type_v), + (long long) node->src[0]->ne[1], (long long) node->src[1]->ne[1], + (long long) node->src[5]->ne[0], (long long) node->src[5]->ne[3]); + } + } + require(attention > 0, "no real flash attention operations"); + return attention; +} + +std::vector tokenize(const llama_vocab * vocab) { + const std::string prompt = + "Once upon a time, a small bear found a red ball. " + "The bear carried the ball home and showed it to a friend. " + "Together they made up a game and played happily in the garden."; + std::vector tokens(prompt.size() + 16); + const auto count = llama_tokenize(vocab, prompt.c_str(), (int) prompt.size(), + tokens.data(), (int) tokens.size(), true, true); + require(count >= 20 && count <= 64, "prompt must fit one wide-prefill microbatch (20..64 tokens)"); + tokens.resize(count); + return tokens; +} + +const float * finite_logits(llama_context * ctx, int n_vocab) { + const float * logits = llama_get_logits_ith(ctx, -1); + require(logits != nullptr, "missing logits"); + require(std::all_of(logits, logits + n_vocab, + [](float value) { return std::isfinite(value); }), "nonfinite output logits"); + return logits; +} + +void run_pair(llama_model * model, const std::vector & prompt, + const char * backend, ggml_type type_k, ggml_type type_v) { + const auto start = clock_type::now(); + auto params = llama_context_default_params(); + params.n_ctx = 512; + params.n_batch = 128; + params.n_ubatch = 64; + params.n_seq_max = 1; + params.kv_unified = true; + params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; + params.type_k = type_k; + params.type_v = type_v; + using context_ptr = std::unique_ptr; + context_ptr ctx(llama_init_from_model(model, params), llama_free); + require(ctx != nullptr, "context open failed (model/KV semantics or backend admission)"); + // The public batch borrows its token array; decoding does not mutate it. + auto tokens = prompt; + require(llama_decode(ctx.get(), llama_batch_get_one(tokens.data(), (int32_t) tokens.size())) == 0, + "prompt decode failed"); + int expected_attention = 0; + for (uint32_t layer = 0; layer < model->hparams.n_layer(); ++layer) { + expected_attention += !model->hparams.is_recr(layer); + } + const int attention = inspect(ctx.get(), type_k, type_v, backend, 0); + require(attention == expected_attention, + "not every attention layer used the required indexed backend"); + const auto vocab = llama_model_get_vocab(model); + const auto n_vocab = llama_vocab_n_tokens(vocab); + const float * logits = finite_logits(ctx.get(), n_vocab); + std::string completion; + for (int step = 0; step < 16; ++step) { + auto token = (llama_token) (std::max_element(logits, logits + n_vocab) - logits); + char piece[256]; + const int bytes = llama_token_to_piece(vocab, token, piece, sizeof(piece), 0, true); + require(bytes >= 0, "token piece buffer too small"); + completion.append(piece, bytes); + require(llama_decode(ctx.get(), llama_batch_get_one(&token, 1)) == 0, "greedy decode failed"); + require(inspect(ctx.get(), type_k, type_v, backend, step + 1) == attention, + "attention layer count changed during decode"); + logits = finite_logits(ctx.get(), n_vocab); + } + require(!completion.empty(), "empty completion"); + const auto elapsed = std::chrono::duration(clock_type::now() - start).count(); + std::printf("PASS backend=%s K=%s V=%s prefill=%zu decoded=16 attention_layers=%d seconds=%.6f completion_hex=", + backend, ggml_type_name(type_k), ggml_type_name(type_v), tokens.size(), attention, elapsed); + for (unsigned char value : completion) std::printf("%02x", value); + std::printf("\n"); + std::fflush(stdout); +} +} // namespace + +int main(int argc, char ** argv) { + llama_model * model = nullptr; + try { + require(argc == 3 || argc == 4 || argc == 5, + "usage: indexed-real-kv-matrix MODEL CUDA0|MTL0|CPU [K_TYPE [V_TYPE]]"); + const char * backend = argv[2]; + const bool cpu = std::strcmp(backend, "CPU") == 0; + const bool metal = std::strcmp(backend, "MTL0") == 0; + require(cpu || metal || std::strcmp(backend, "CUDA0") == 0, "select CPU, MTL0 or CUDA0 explicitly"); + ggml_backend_load_all(); + const auto device = ggml_backend_dev_by_name(backend); + require(device != nullptr, "selected backend unavailable"); + ggml_backend_dev_t devices[] = {device, nullptr}; + auto params = llama_model_default_params(); + params.devices = cpu ? nullptr : devices; + params.n_gpu_layers = cpu ? 0 : 99; + const auto load_start = clock_type::now(); + model = llama_model_load_from_file(argv[1], params); + require(model != nullptr, "model open failed"); + const auto tokens = tokenize(llama_model_get_vocab(model)); + std::printf("MODEL backend=%s path=%s loads=1 seconds=%.6f prefill=%zu ctx=512 batch=128 ubatch=64 output=16\n", + backend, argv[1], std::chrono::duration(clock_type::now() - load_start).count(), tokens.size()); + std::vector> pairs; + int skipped = 0; + if (argc >= 4) { + const auto k = parse_type(argv[3]); + pairs.push_back({k, argc == 5 ? parse_type(argv[4]) : k}); + } else { + for (auto k : kv_types) { + for (auto v : kv_types) { + if (metal && k != v) { + std::printf("SKIP backend=MTL0 K=%s V=%s reason=preexisting_Metal_requires_matching_KV_types\n", + ggml_type_name(k), ggml_type_name(v)); + ++skipped; + } else { + pairs.push_back({k, v}); + } + } + } + } + int passed = 0; + int failed = 0; + for (const auto & pair : pairs) { + try { + run_pair(model, tokens, backend, pair[0], pair[1]); + ++passed; + } catch (const std::exception & error) { + std::printf("FAIL backend=%s K=%s V=%s reason=%s\n", backend, + ggml_type_name(pair[0]), ggml_type_name(pair[1]), error.what()); + std::fflush(stdout); + ++failed; + } + } + std::printf("SUMMARY backend=%s model_loads=1 passed=%d failed=%d skipped=%d\n", backend, passed, failed, skipped); + llama_model_free(model); + llama_backend_free(); + return failed == 0 ? 0 : 1; + } catch (const std::exception & error) { + std::fprintf(stderr, "matrix setup failed: %s\n", error.what()); + if (model) llama_model_free(model); + llama_backend_free(); + return 2; + } +} diff --git a/skippy/evals/kv-validation/producer.example.json b/skippy/evals/kv-validation/producer.example.json new file mode 100644 index 0000000000..7692f50531 --- /dev/null +++ b/skippy/evals/kv-validation/producer.example.json @@ -0,0 +1,14 @@ +{ + "schema_version": 1, + "backend": "cuda", + "workspace": "/opt/mesh-llm", + "native_source": "/opt/mesh-llm/.deps/llama.cpp", + "native_source_commit": "0000000000000000000000000000000000000000", + "runtime_bundle": "/opt/mesh-llm/dist/native-runtimes/meshllm-native-runtime-linux-aarch64-cuda13", + "runtime_sha256": "", + "cli": {"path": "/opt/mesh-llm/target/release/skippy", "sha256": ""}, + "correctness": {"path": "/opt/mesh-llm/target/release/skippy-correctness", "sha256": ""}, + "serving_tests": {"path": "/opt/kv-tools/skippy-serving-tests", "sha256": ""}, + "just": "/usr/local/bin/just", + "cmake": "/usr/bin/cmake" +} diff --git a/todo.md b/todo.md index 99071e57fc..c95e81c677 100644 --- a/todo.md +++ b/todo.md @@ -1,7 +1,47 @@ # Reusable KV validation on JY -Implement this **after the current cache and performance work**. Turn the -experiments into repeatable JY jobs that we can run whenever KV behavior changes. +The bounded [validation foundation](skippy/evals/kv-validation/README.md) now +provides explicit reusable commands. Complete the remaining cases below after +the current cache and performance work. + +## Completed foundation + +- [x] Own the exact four-model manifest and reject model/hash substitutions. +- [x] Prepare a matching-header, pinned-runtime real-model evaluator once and + reuse one model load across the supported K/V type pairs. +- [x] Provide typed Rust pin/prepare/run/JY-plan commands and thin Just recipes, + with bounded child supervision, cancellation and failed evidence retention. +- [x] Run a fresh c1 cold/repeat/growing/repeat generated-content check, plus the + unchanged strict recurrent chat/growing tests for the declared hybrid rows. +- [x] Emit four independent Linux CPU/CUDA JY specs with excluded-host guards, + immutable image/model/tool identities and no worker rebuilds. Local Metal + uses the same native prepare/run commands; native macOS JY admission remains + separate work. + +The new command passed end to end locally on the pinned Qwen3.5-4B model with +all eight Metal formats. This does not mark the full four-model/backend suite, +long-prefix ownership, L3 restart or throughput comparisons complete. + +## Retain PR #2657's correctness requirements + +Cache-owned immutable checkpoints replace the old execution-lane pinning and +leased-pointer recorder. Before closing +[PR #2657](https://github.com/Mesh-LLM/mesh-llm/pull/2657) as fully superseded: + +- [ ] Port native hybrid cancellation/consumer-error, recorder saturation and + unload/L3-restart integration assertions to cache-owned checkpoints. Keep + exact consumed-token boundaries, immutable KV/recurrent state and transactional + restore checks; token-count hashes cannot replace them. +- [ ] Exercise the new spill reservation under byte-budget refusal, queue-full, + disconnect, export failure and blocked/failed writes. Reserve both attention + and recurrent bytes before export; retain accounting through write completion + and prove all failure paths release it without wedging request admission. +- [ ] Document and expose the current best-effort cold-eviction policy: a refused + or failed L3 offload can release the final cached native owner. This loses reuse + and causes later prefill; it does not make every retained prefix durable. + Existing blob-L1 refusal tests do not cover native-owner eviction. Preserve + explicit refusal/eviction outcomes rather than restoring the old lane-pinning + timeout or forced direct-decode routing. ## Four-model AgentX matrix diff --git a/tools/xtask/src/automation/kv_validation.rs b/tools/xtask/src/automation/kv_validation.rs new file mode 100644 index 0000000000..56a6192afe --- /dev/null +++ b/tools/xtask/src/automation/kv_validation.rs @@ -0,0 +1,83 @@ +//! Explicit, pinned four-model KV validation; never an automatic CI hardware gate. +mod contract; +mod evidence; +mod execution; +mod jy_plan; +mod preparation; +#[cfg(test)] +mod tests; +use crate::command::DynResult; +use std::path::{Path, PathBuf}; + +pub(crate) fn run(args: &[String]) -> DynResult<()> { + if args == ["--help"] { + println!( + "cargo xtool automation kv-validation {{pin|prepare|run|jy-plan}} --input ABS_JSON --output ABS_FRESH_PATH" + ); + return Ok(()); + } + let [verb, input_flag, input, output_flag, output] = args else { + return Err("KV validation requires verb --input ABS_JSON --output ABS_FRESH_PATH".into()); + }; + if input_flag != "--input" || output_flag != "--output" { + return Err("invalid KV validation arguments".into()); + } + let output = PathBuf::from(output); + contract::absolute(&output)?; + if verb == "run-env" { + if input != "KV_VALIDATION_REQUEST_JSON" { + return Err("KV worker requires its dedicated request environment".into()); + } + let bytes = std::env::var(input)?; + if bytes.len() > 1024 * 1024 { + return Err("KV worker request exceeds1MiB".into()); + } + return execution::run(serde_json::from_str(&bytes)?, &output); + } + let input = PathBuf::from(input); + contract::absolute(&input)?; + let bytes = super::receipt_files::bounded(&input, 1024 * 1024)?; + match verb.as_str() { + "pin" => preparation::pin(serde_json::from_slice(&bytes)?, &output), + "prepare" => preparation::run(serde_json::from_slice(&bytes)?, &output), + "run" => execution::run(serde_json::from_slice(&bytes)?, &output), + "jy-plan" => jy_plan::run(serde_json::from_slice(&bytes)?, &output), + _ => Err("unknown KV validation verb".into()), + } +} +fn hash(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(bytes)) +} +fn publish(path: &Path, value: &impl serde::Serialize) -> DynResult<()> { + super::receipt_files::fresh(path, &serde_json::to_vec_pretty(value)?) +} +fn verify_bundle( + path: &Path, + expected: &str, + backend: contract::Backend, + native_source_commit: &str, +) -> DynResult<()> { + super::native_artifact_identity::verify(path, expected)?; + let manifest: serde_json::Value = serde_json::from_slice(&super::receipt_files::bounded( + &path.join("manifest.json"), + 1024 * 1024, + )?)?; + verify_manifest(&manifest, backend, native_source_commit) +} +fn verify_manifest( + manifest: &serde_json::Value, + backend: contract::Backend, + native_source_commit: &str, +) -> DynResult<()> { + if manifest["runtime"]["backend"]["kind"] != backend.kind() + || manifest["build"]["backend"] != backend.kind() + || manifest["build"]["llama_patched_sha"] != native_source_commit + || manifest["runtime"]["libraries"] + .as_array() + .is_none_or(Vec::is_empty) + { + return Err("KV runtime requires matching source and exact backend leaf manifest".into()); + } + Ok(()) +} diff --git a/tools/xtask/src/automation/kv_validation/contract.rs b/tools/xtask/src/automation/kv_validation/contract.rs new file mode 100644 index 0000000000..da6e1c5f77 --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/contract.rs @@ -0,0 +1,199 @@ +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +pub(super) const CATALOG: &[u8] = + include_bytes!("../../../../../skippy/evals/kv-validation/models.json"); +pub(super) const CATALOG_SHA: &str = + "6a2b724cf32208186d80ac614e21a168bfc08ca72e55afdabc3dc39b338c9206"; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub(super) enum Backend { + Cpu, + Metal, + Cuda, +} +impl Backend { + pub(super) fn device(self) -> &'static str { + match self { + Self::Cpu => "CPU", + Self::Metal => "MTL0", + Self::Cuda => "CUDA0", + } + } + pub(super) fn kind(self) -> &'static str { + match self { + Self::Cpu => "cpu", + Self::Metal => "metal", + Self::Cuda => "cuda", + } + } + pub(super) fn pairs(self) -> usize { + if self == Self::Metal { 8 } else { 64 } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Tool { + pub path: PathBuf, + pub sha256: String, +} +impl Tool { + pub(super) fn verify(&self) -> DynResult<()> { + absolute(&self.path)?; + let actual = crate::product::digest::file_sha256(&self.path).map_err(|e| e.error)?; + if actual != self.sha256 { + return Err("KV validation file SHA-256 mismatch".into()); + } + Ok(()) + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Producer { + pub schema_version: u32, + pub backend: Backend, + pub workspace: PathBuf, + pub native_source: PathBuf, + pub native_source_commit: String, + pub runtime_bundle: PathBuf, + pub runtime_sha256: String, + pub cli: Tool, + pub correctness: Tool, + pub serving_tests: Tool, + pub just: PathBuf, + pub cmake: PathBuf, +} +impl Producer { + pub(super) fn verify(&self) -> DynResult<()> { + if self.schema_version != 1 || !sha(&self.native_source_commit, 40) { + return Err("invalid KV producer schema/source".into()); + } + for path in [ + &self.workspace, + &self.native_source, + &self.runtime_bundle, + &self.just, + &self.cmake, + ] { + absolute(path)?; + } + if !self.workspace.join("Justfile").is_file() + || !self.native_source.join("src/llama-context.h").is_file() + { + return Err("KV producer requires owning workspace and prepared native source".into()); + } + for tool in [&self.cli, &self.correctness, &self.serving_tests] { + tool.verify()?; + } + super::verify_bundle( + &self.runtime_bundle, + &self.runtime_sha256, + self.backend, + &self.native_source_commit, + )?; + Ok(()) + } +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Prepared { + pub schema_version: u32, + pub catalog_sha256: String, + pub producer: Producer, + pub matrix: Tool, +} +impl Prepared { + pub(super) fn verify(&self) -> DynResult<()> { + if self.schema_version != 1 || self.catalog_sha256 != CATALOG_SHA { + return Err("KV prepared receipt catalog/schema mismatch".into()); + } + self.producer.verify()?; + self.matrix.verify() + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Cell { + pub schema_version: u32, + pub prepared: Tool, + pub model_key: String, + pub model: PathBuf, + pub port: u16, + pub execution_seconds: u64, +} +impl Cell { + pub(super) fn validate(&self) -> DynResult { + if self.schema_version != 1 + || self.port < 1024 + || !(30..=14400).contains(&self.execution_seconds) + { + return Err("invalid bounded KV cell".into()); + } + absolute(&self.model)?; + models()? + .into_iter() + .find(|m| m.key == self.model_key) + .ok_or_else(|| "KV cell requires one exact declared AgentX model".into()) + } +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Model { + pub key: String, + pub family: String, + pub repo: String, + pub revision: String, + pub tokenizer: String, + pub tokenizer_revision: String, + pub files: Vec, +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ModelFile { + pub name: String, + pub sha256: String, +} +impl Model { + pub(super) fn reference(&self) -> String { + format!("hf:{}@{}#{}", self.repo, self.revision, self.files[0].name) + } + pub(super) fn recurrent_case(&self) -> bool { + self.family.starts_with("hybrid-") + } +} +pub(super) fn models() -> DynResult> { + if super::hash(CATALOG) != CATALOG_SHA { + return Err("declared AgentX catalog bytes changed".into()); + } + let models: Vec = serde_json::from_slice(CATALOG)?; + if models.len() != 4 + || models.iter().any(|m| { + m.files.len() != 1 + || !sha(&m.revision, 40) + || !sha(&m.tokenizer_revision, 40) + || !sha(&m.files[0].sha256, 64) + }) + { + return Err("invalid four-model pinned catalog".into()); + } + Ok(models) +} +pub(super) fn sha(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +pub(super) fn absolute(path: &Path) -> DynResult<()> { + if !path.is_absolute() { + return Err("KV validation paths must be absolute".into()); + } + Ok(()) +} diff --git a/tools/xtask/src/automation/kv_validation/evidence.rs b/tools/xtask/src/automation/kv_validation/evidence.rs new file mode 100644 index 0000000000..03185d1fca --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/evidence.rs @@ -0,0 +1,159 @@ +use super::contract::Backend; +use crate::command::DynResult; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct CacheEvidence { + status: String, + content_parity: String, + cold_content: String, + repeat: CacheResponse, + growing_chat: CacheResponse, + growing_chat_repeat: CacheResponse, +} +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +struct CacheResponse { + cached_tokens: u64, + prompt_tokens: u64, + content: String, +} +impl CacheEvidence { + pub(super) fn verify(&self) -> DynResult<()> { + if self.status != "pass" + || self.content_parity != "exact" + || self.cold_content.is_empty() + || self.repeat.content != self.cold_content + || self.growing_chat.content.is_empty() + || self.growing_chat_repeat.content != self.growing_chat.content + || [&self.repeat, &self.growing_chat, &self.growing_chat_repeat] + .into_iter() + .any(|r| r.cached_tokens == 0 || r.cached_tokens > r.prompt_tokens) + { + return Err("generic cache evidence lacks exact content parity and valid reuse".into()); + } + Ok(()) + } +} + +pub(super) fn doctor(value: &serde_json::Value, runtime: &std::path::Path) -> DynResult<()> { + if value["native_runtime"]["path"].as_str() != runtime.to_str() + || value + .get("runtime_issue") + .is_none_or(|issue| !issue.is_null()) + { + return Err( + "doctor requires exact runtime leaf and an explicitly clean runtime issue".into(), + ); + } + Ok(()) +} + +const TYPES: [&str; 8] = ["f32", "f16", "bf16", "q4_0", "q4_1", "q5_0", "q5_1", "q8_0"]; +fn fields(line: &str) -> BTreeMap<&str, &str> { + line.split_ascii_whitespace() + .filter_map(|word| word.split_once('=')) + .collect() +} +pub(super) fn matrix(text: &str, backend: Backend) -> DynResult<()> { + let mut pairs = BTreeSet::new(); + let mut models = 0; + let mut summaries = 0; + let mut observed = BTreeSet::new(); + let mut skips = BTreeSet::new(); + for line in text.lines() { + let f = fields(line); + if line.starts_with("MODEL ") { + models += 1; + if f.get("backend") != Some(&backend.device()) || f.get("loads") != Some(&"1") { + return Err("KV matrix model load/backend evidence mismatch".into()); + } + } else if line.starts_with("REAL_FA ") + || line.starts_with("PASS ") + || line.starts_with("SKIP ") + { + let k = *f.get("K").ok_or("matrix missing K")?; + let v = *f.get("V").ok_or("matrix missing V")?; + if !TYPES.contains(&k) + || !TYPES.contains(&v) + || f.get("backend") != Some(&backend.device()) + { + return Err("KV matrix unexpected dtype/backend".into()); + } + if line.starts_with("SKIP ") { + if backend != Backend::Metal + || k == v + || f.get("reason") != Some(&"preexisting_Metal_requires_matching_KV_types") + || !skips.insert((k, v)) + { + return Err("KV matrix cannot skip required pair".into()); + } + } else if line.starts_with("REAL_FA ") { + if !observed.insert((k, v)) + || f.get("q") + .and_then(|s| s.parse::().ok()) + .is_none_or(|q| !(20..=64).contains(&q)) + { + return Err("KV matrix missing wide-prefill graph evidence".into()); + } + } else { + let completion = f.get("completion_hex").ok_or("matrix completion missing")?; + let seconds = f + .get("seconds") + .ok_or("matrix timing missing")? + .parse::()?; + if !seconds.is_finite() + || seconds < 0.0 + || f.get("decoded") != Some(&"16") + || f.get("attention_layers") + .and_then(|v| v.parse::().ok()) + .is_none_or(|n| n == 0) + || completion.is_empty() + || completion.len() % 2 != 0 + || !completion.bytes().all(|b| b.is_ascii_hexdigit()) + || !pairs.insert((k, v)) + { + return Err("invalid KV matrix completion/graph evidence".into()); + } + } + } else if line.starts_with("SUMMARY ") { + summaries += 1; + if f.get("backend") != Some(&backend.device()) + || f.get("model_loads") != Some(&"1") + || f.get("failed") != Some(&"0") + || f.get("passed").and_then(|v| v.parse::().ok()) != Some(backend.pairs()) + { + return Err("KV matrix summary failed".into()); + } + } else if line.starts_with("FAIL ") { + return Err("KV matrix reported failure".into()); + } + } + let expected: BTreeSet<_> = TYPES + .into_iter() + .flat_map(|k| { + TYPES + .into_iter() + .filter_map(move |v| (backend != Backend::Metal || k == v).then_some((k, v))) + }) + .collect(); + if models != 1 + || summaries != 1 + || pairs != expected + || observed != expected + || skips.len() != if backend == Backend::Metal { 56 } else { 0 } + { + return Err("KV matrix incomplete/duplicate roster".into()); + } + Ok(()) +} + +pub(super) fn rust_test(text: &str, test: &str) -> DynResult<()> { + if !text.contains(&format!("test {test} ...")) + || !text.contains("test result: ok. 1 passed; 0 failed; 0 ignored;") + { + return Err("required actual-model Rust cache test did not execute".into()); + } + Ok(()) +} diff --git a/tools/xtask/src/automation/kv_validation/execution.rs b/tools/xtask/src/automation/kv_validation/execution.rs new file mode 100644 index 0000000000..e2c001246e --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/execution.rs @@ -0,0 +1,308 @@ +use super::{ + contract::{Backend, Cell, Prepared}, + evidence, publish, +}; +use crate::{ + command::DynResult, + process::{ + self, Cancellation, Completion, Limits, OutputFiles, ProcessSpec, Readiness, Value as Arg, + }, +}; +use serde_json::json; +use std::{ + collections::BTreeMap, + ffi::OsString, + path::Path, + time::{Duration, Instant}, +}; +#[path = "server.rs"] +mod server; + +pub(super) fn environment(extra: &[(&str, OsString)]) -> BTreeMap { + let mut env: BTreeMap<_, _> = [ + "PATH", + "HOME", + "SYSTEMROOT", + "WINDIR", + "CUDA_VISIBLE_DEVICES", + ] + .into_iter() + .filter_map(|key| std::env::var_os(key).map(|v| (key.into(), Arg::Public(v)))) + .collect(); + env.insert("HF_HUB_OFFLINE".into(), Arg::Public("1".into())); + env.extend( + extra + .iter() + .map(|(k, v)| ((*k).into(), Arg::Public(v.clone()))), + ); + env +} +pub(super) fn limits(execution: Duration) -> Limits { + Limits { + execution, + graceful_shutdown: Duration::from_secs(10), + forced_shutdown: Duration::from_secs(2), + retained_bytes_per_stream: 16 * 1024 * 1024, + readiness: Readiness::None, + completion: Completion::Exit, + } +} +pub(super) fn child( + binary: &Path, + args: Vec, + paths: (&Path, &Path), + label: &str, + duration: Duration, + cancel: &Cancellation, + extra: &[(&str, OsString)], +) -> DynResult { + let (cwd, output) = paths; + let stdout = output.join(format!("{label}.stdout.log")); + let stderr = output.join(format!("{label}.stderr.log")); + let result = process::supervise( + &ProcessSpec { + executable: binary.into(), + arguments: args.into_iter().map(Arg::Public).collect(), + cwd: cwd.into(), + environment: environment(extra), + }, + &limits(duration), + cancel, + OutputFiles { + stdout: Some(stdout.clone()), + stderr: Some(stderr), + }, + ); + let result = match result { + Ok(result) => result, + Err(error) => { + publish( + &output.join(format!("{label}.process.json")), + &json!({"success":false,"supervision_failure":error.to_string()}), + )?; + return Err(error.into()); + } + }; + publish( + &output.join(format!("{label}.process.json")), + &json!({"success":result.success(),"outcome":format!("{:?}",result.outcome),"cleanup_complete":result.cleanup.complete,"forced":result.cleanup.forced,"exit_code":result.status.and_then(|s|s.code())}), + )?; + if !result.success() + || !result.cleanup.complete + || result.cleanup.forced + || result.cleanup.failure.is_some() + || result.cleanup.graceful_signal_failed + { + return Err(format!("KV child {label} failed; raw output retained").into()); + } + Ok(String::from_utf8( + crate::automation::receipt_files::bounded(&stdout, 16 * 1024 * 1024)?, + )?) +} +pub(super) fn run(input: Cell, output: &Path) -> DynResult<()> { + input.validate()?; + std::fs::create_dir(output)?; + let interrupt = crate::automation::command_interrupt::Interrupt::install()?; + let deadline = Instant::now() + Duration::from_secs(input.execution_seconds); + let result = execute(&input, output, deadline, &interrupt.cancellation()); + let finish = interrupt.finish(); + let passed = result.is_ok() && finish.is_ok() && Instant::now() < deadline; + publish( + &output.join("result.json"), + &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"scope":"KVdtype_dispatch_generic_c1_cache_plus_declared_recurrent_regressions_not_long_c4_L3_or_performance"}), + )?; + archive(output)?; + finish?; + result?; + if !passed { + return Err("KV validation deadline exceeded".into()); + } + Ok(()) +} +pub(super) fn archive(output: &Path) -> DynResult<()> { + let path = output.with_extension("tar.gz"); + let archive_name = path + .file_name() + .and_then(|name| name.to_str()) + .ok_or("KV archive filename must be Unicode")?; + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + let gzip = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + let mut tar = tar::Builder::new(gzip); + let mut pending = vec![output.to_path_buf()]; + while let Some(directory) = pending.pop() { + for entry in std::fs::read_dir(directory)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push(entry.path()); + } else if kind.is_file() { + tar.append_path_with_name( + entry.path(), + Path::new("evidence").join(entry.path().strip_prefix(output)?), + )?; + } else if !kind.is_symlink() { + return Err("KV evidence contains a special file".into()); + } + } + } + tar.into_inner()?.finish()?; + let sha256 = crate::product::digest::file_sha256(&path).map_err(|e| e.error)?; + publish( + &output.with_extension("archive.json"), + &json!({"archive":archive_name,"sha256":sha256,"symlinks":"excluded; selected runtime identity retained in JSON"}), + ) +} +fn remaining(deadline: Instant) -> DynResult { + deadline + .saturating_duration_since(Instant::now()) + .checked_sub(Duration::from_secs(12)) + .filter(|d| !d.is_zero()) + .ok_or_else(|| "KV validation cleanup reserve exhausted".into()) +} +fn execute(input: &Cell, output: &Path, deadline: Instant, cancel: &Cancellation) -> DynResult<()> { + let model = input.validate()?; + input.prepared.verify()?; + let prepared: Prepared = serde_json::from_slice(&crate::automation::receipt_files::bounded( + &input.prepared.path, + 1024 * 1024, + )?)?; + prepared.verify()?; + crate::automation::replay_matrix::model_preflight::verify( + &input.model, + &model.files[0].sha256, + 2048, + )?; + let dimensions = + crate::automation::replay_matrix::model_preflight::dimensions::inspect(&input.model)? + .ok_or("model dimensions missing")?; + publish( + &output.join("identities.json"), + &json!({"prepared":prepared,"model":model,"model_layers":dimensions.block_count}), + )?; + let producer = &prepared.producer; + let doctor = child( + &producer.cli.path, + vec![ + "--output".into(), + "json".into(), + "--runtime-bundle".into(), + producer.runtime_bundle.clone().into_os_string(), + "--runtime-selection".into(), + producer.backend.kind().into(), + "doctor".into(), + ], + (output, output), + "doctor", + remaining(deadline)?, + cancel, + &[], + )?; + let doctor: serde_json::Value = serde_json::from_str(&doctor)?; + evidence::doctor(&doctor, &producer.runtime_bundle)?; + let text = child( + &prepared.matrix.path, + vec![ + input.model.clone().into_os_string(), + producer.backend.device().into(), + ], + (output, output), + "matrix", + remaining(deadline)?, + cancel, + &[], + )?; + evidence::matrix(&text, producer.backend)?; + server::run( + input, + &prepared, + &model, + output, + remaining(deadline)?, + cancel, + )?; + if model.recurrent_case() { + recurrent( + input, + &prepared, + dimensions.block_count, + output, + deadline, + cancel, + )?; + } + prepared.verify()?; + Ok(()) +} +fn recurrent( + input: &Cell, + prepared: &Prepared, + layers: u64, + output: &Path, + deadline: Instant, + cancel: &Cancellation, +) -> DynResult<()> { + // Test discovery's documented parent layout contains exactly this verified leaf. + let parent = output.join("test-runtime"); + std::fs::create_dir(&parent)?; + #[cfg(unix)] + std::os::unix::fs::symlink( + &prepared.producer.runtime_bundle, + parent.join("selected-runtime"), + )?; + #[cfg(windows)] + std::os::windows::fs::symlink_dir( + &prepared.producer.runtime_bundle, + parent.join("selected-runtime"), + )?; + let model_id = format!("{}:Q4_K_M", input.validate()?.repo); + let env = [ + ( + "MESH_LLM_NATIVE_RUNTIME_BUNDLE_DIR", + parent.into_os_string(), + ), + ( + "SKIPPY_RECURRENT_CACHE_TEST_MODEL", + input.model.clone().into_os_string(), + ), + ( + "SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS", + layers.to_string().into(), + ), + ("SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID", model_id.into()), + ( + "SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS", + if prepared.producer.backend == Backend::Cpu { + "0" + } else { + "99" + } + .into(), + ), + ]; + for suffix in [ + "recurrent_chat_checkpoint_preserves_cached_output_parity", + "recurrent_post_decode_checkpoint_reuses_a_growing_prompt", + ] { + let test = format!("frontend::local_generation::tests::{suffix}"); + let text = child( + &prepared.producer.serving_tests.path, + vec![ + "--exact".into(), + test.clone().into(), + "--ignored".into(), + "--nocapture".into(), + "--test-threads=1".into(), + ], + (output, output), + suffix, + remaining(deadline)?, + cancel, + &env, + )?; + evidence::rust_test(&text, &test)?; + } + Ok(()) +} diff --git a/tools/xtask/src/automation/kv_validation/jy_plan.rs b/tools/xtask/src/automation/kv_validation/jy_plan.rs new file mode 100644 index 0000000000..95d2ea170d --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/jy_plan.rs @@ -0,0 +1,136 @@ +//! Manual JY specs using the observed lab/custom schema, not a new CI provider. +use super::{ + contract::{self, Backend, Cell, Tool}, + publish, +}; +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Node { + pub id: String, + pub hostname: String, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Fleet { + pub schema_version: u32, + pub backend: Backend, + pub source_commit: String, + pub prepared_image: String, + pub automation: PathBuf, + pub prepared: Tool, + pub nodes: Vec, + pub execution_seconds: u64, +} +impl Fleet { + fn validate(&self) -> DynResult<()> { + if self.schema_version != 1 + || !contract::sha(&self.source_commit, 40) + || self.backend == Backend::Metal + || self + .prepared_image + .strip_prefix("sha256:") + .is_none_or(|s| !contract::sha(s, 64)) + || self.nodes.is_empty() + || self.nodes.len() > 16 + || !(30..=14400).contains(&self.execution_seconds) + { + return Err( + "JY foundation requires pinned Linux CPU/CUDA image, source and bounded nodes/time" + .into(), + ); + } + contract::absolute(&self.automation)?; + contract::absolute(&self.prepared.path)?; + if !contract::sha(&self.prepared.sha256, 64) { + return Err("JY prepared receipt SHA required".into()); + } + let mut ids = BTreeSet::new(); + let mut hosts = BTreeSet::new(); + for node in &self.nodes { + if !node.id.starts_with("spark-") + || !safe_name(&node.id) + || !safe_name(&node.hostname) + || excluded(&node.id, &node.hostname) + || !ids.insert(&node.id) + || !hosts.insert(&node.hostname) + { + return Err("duplicate, excluded or malformed JY node".into()); + } + } + Ok(()) + } +} +fn safe_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 64 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') +} +pub(super) fn excluded(id: &str, hostname: &str) -> bool { + ["spark-000280", "spark-000499"].contains(&id) + || ["spark-db08", "spark-9f06"].contains(&hostname) +} +fn quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +pub(super) fn run(input: Fleet, output: &Path) -> DynResult<()> { + input.validate()?; + std::fs::create_dir(output)?; + for (index, model) in contract::models()?.iter().enumerate() { + let node = &input.nodes[index % input.nodes.len()]; + let request = Cell { + schema_version: 1, + prepared: input.prepared.clone(), + model_key: model.key.clone(), + model: "/model.gguf".into(), + port: 19337, + execution_seconds: input.execution_seconds, + }; + let gpu = if input.backend == Backend::Cuda { + " --gpus all" + } else { + "" + }; + // This is only a platform adapter. Selection, identity, supervision and + // pass/fail policy live in the typed run owner inside the immutable image. + let command = format!( + "set -eu\ncase \"$(hostname -s)\" in {}) ;; *) exit 90;; esac\nset +e\ndocker run --rm --init{gpu} --user \"$(id -u):$(id -g)\" --mount \"type=bind,src=$AGENTX_MODEL_PATH,dst=/model.gguf,readonly\" --mount \"type=bind,src=$JIANYANG_ARTIFACT_DIR,dst=/artifacts\" --env KV_VALIDATION_REQUEST_JSON {} {} automation kv-validation run-env --input KV_VALIDATION_REQUEST_JSON --output /artifacts/evidence\nworker_status=$?\nset -e\nif [ -f \"$JIANYANG_ARTIFACT_DIR/evidence/result.json\" ]; then cp \"$JIANYANG_ARTIFACT_DIR/evidence/result.json\" \"$JIANYANG_RESULT_PATH\"; fi\nexit \"$worker_status\"\n", + node.hostname, + quote(&input.prepared_image), + quote( + input + .automation + .to_str() + .ok_or("automation path Unicode required")? + ) + ); + let spec = json!({"spec":{ + "budget":{"max_duration_s":input.execution_seconds+120,"grace_s":90,"max_usd":0}, + "description":"Explicit four-model KV foundation: dtype dispatch, deterministic c1 reuse, declared recurrent regressions; excludes long-c4/L3/performance.", + "harness":{"args":{},"concurrency":[1],"name":"custom","percentiles":[50,90,95,99],"request_count":1,"seed":0,"trace":{"kind":"synthetic","ref":"none"},"version":"kv-validation-foundation-v1","warmup_requests":0}, + "labels":{"campaign":"kv-validation","model":model.key,"node":node.id}, + "name":format!("kv-validation-{}-{}",input.backend.kind(),model.key),"priority":20,"retries":0, + "runtime":{"command":command,"env":{"HF_HUB_OFFLINE":"1","JIANYANG_COMMIT":input.source_commit,"JIANYANG_REPO_DIR":"mesh-llm","KV_VALIDATION_REQUEST_JSON":serde_json::to_string(&request)?}, + "flags":{"backend":input.backend.kind(),"model":model.reference(),"ref":format!("commit:{}",input.source_commit),"repo":"mesh-llm","validation":"kv-foundation","node":node.id}, + "model_package":{"egress":"lab_only","ref":model.reference(),"sha256":model.files[0].sha256}, + "models":[{"delivery":"stream","env":"AGENTX_MODEL_PATH","pin":false,"ref":model.reference()}],"volumes":[], + "workspace":{"repos":[{"rev":input.source_commit,"submodules":false,"url":"https://github.com/Mesh-LLM/mesh-llm.git"}],"retain":"always"}}, + "target":{"executor":"lab","num_nodes":1,"os":"linux","spot":false,"nodes":[node.id]} + }}); + publish(&output.join(format!("{}.json", model.key)), &spec)?; + } + publish( + &output.join("plan.json"), + &json!({"schema_version":1,"jobs":4,"catalog_sha256":contract::CATALOG_SHA,"backend":input.backend,"source_commit":input.source_commit,"prepared_image":input.prepared_image,"execution":"submit each model JSON with jy submit; no automatic dispatch"}), + ) +} diff --git a/tools/xtask/src/automation/kv_validation/preparation.rs b/tools/xtask/src/automation/kv_validation/preparation.rs new file mode 100644 index 0000000000..3fda669636 --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/preparation.rs @@ -0,0 +1,133 @@ +use super::{ + contract::{CATALOG_SHA, Prepared, Producer, Tool}, + execution::child, + publish, +}; +use crate::{command::DynResult, process::Cancellation}; +use std::{ffi::OsString, path::Path, time::Duration}; + +pub(super) fn pin(mut input: Producer, output: &Path) -> DynResult<()> { + for tool in [ + &mut input.cli, + &mut input.correctness, + &mut input.serving_tests, + ] { + tool.sha256 = crate::product::digest::file_sha256(&tool.path).map_err(|e| e.error)?; + } + input.runtime_sha256 = + crate::automation::native_artifact_identity::observe(&input.runtime_bundle)?; + input.verify()?; + publish(output, &input) +} + +pub(super) fn run(input: Producer, output: &Path) -> DynResult<()> { + input.verify()?; + std::fs::create_dir(output)?; + let interrupt = crate::automation::command_interrupt::Interrupt::install()?; + let result = prepare(&input, output, &interrupt.cancellation()); + let finished = interrupt.finish(); + finished?; + result +} +fn prepare(input: &Producer, output: &Path, cancel: &Cancellation) -> DynResult<()> { + source(input, output, cancel, "source-before")?; + let native = input.workspace.join("skippy/evals/kv-validation/native"); + let build = output.join("build"); + let args: Vec = vec![ + "with-lld".into(), + input.cmake.clone().into_os_string(), + "-S".into(), + native.into_os_string(), + "-B".into(), + build.clone().into_os_string(), + "-DCMAKE_BUILD_TYPE=Release".into(), + format!("-DNATIVE_SOURCE={}", input.native_source.display()).into(), + format!( + "-DNATIVE_LIB_DIR={}", + input.runtime_bundle.join("lib").display() + ) + .into(), + ]; + child( + &input.just, + args, + (&input.workspace, output), + "configure", + Duration::from_secs(120), + cancel, + &[], + )?; + child( + &input.just, + vec![ + "with-lld".into(), + input.cmake.clone().into_os_string(), + "--build".into(), + build.clone().into_os_string(), + "--target".into(), + "indexed-real-kv-matrix".into(), + "-j".into(), + "2".into(), + ], + (&input.workspace, output), + "build", + Duration::from_secs(180), + cancel, + &[], + )?; + let path = build.join("indexed-real-kv-matrix"); + let sha256 = crate::product::digest::file_sha256(&path).map_err(|e| e.error)?; + input.verify()?; + source(input, output, cancel, "source-after")?; + publish( + &output.join("prepared.json"), + &Prepared { + schema_version: 1, + catalog_sha256: CATALOG_SHA.into(), + producer: input.clone(), + matrix: Tool { path, sha256 }, + }, + ) +} + +fn source(input: &Producer, output: &Path, cancel: &Cancellation, label: &str) -> DynResult<()> { + let args = vec![ + "with-lld".into(), + "git".into(), + "-C".into(), + input.native_source.clone().into_os_string(), + "rev-parse".into(), + "HEAD".into(), + ]; + let observed = child( + &input.just, + args, + (&input.workspace, output), + label, + Duration::from_secs(30), + cancel, + &[], + )?; + if observed.trim() != input.native_source_commit { + return Err("prepared native source HEAD differs from declared identity".into()); + } + child( + &input.just, + vec![ + "with-lld".into(), + "git".into(), + "-C".into(), + input.native_source.clone().into_os_string(), + "diff".into(), + "--quiet".into(), + "HEAD".into(), + "--".into(), + ], + (&input.workspace, output), + &format!("{label}-clean"), + Duration::from_secs(30), + cancel, + &[], + )?; + Ok(()) +} diff --git a/tools/xtask/src/automation/kv_validation/server.rs b/tools/xtask/src/automation/kv_validation/server.rs new file mode 100644 index 0000000000..602d90b3fb --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/server.rs @@ -0,0 +1,239 @@ +//! One fresh product host with one deterministic cache client; both trees owned. +use super::super::{ + contract::{Backend, Cell, Model, Prepared}, + evidence::CacheEvidence, + publish, +}; +use super::{environment, limits}; +use crate::{ + command::DynResult, + process::{ + self, ObservedLine, OutputFiles, ProbeDecision, ProcessSpec, Stream, Value as Arg, + retained::{ + self, Action, Context, Coordinator, ExpectedExit, Launch, MemberId, MemberState, + }, + }, +}; +use serde_json::json; +use std::{ffi::OsString, path::Path, time::Duration}; + +struct Owner { + server: Option, + client: Option, + ready: bool, + stopping: bool, + port: u16, + cache_evidence: Option, + duplicate_evidence: bool, +} +impl Coordinator for Owner { + type Rejection = String; + fn captured_line(&mut self, member: MemberId, line: ObservedLine<'_>) { + if line.bytes.len() > 16384 { + return; + } + if member == MemberId::WorkerOne && line.stream == Stream::Stdout { + // Only this declared cache receipt is retained before log sanitization. + // Arbitrary stdout, environment and protocol headers are never copied. + if let Ok(evidence) = serde_json::from_slice::(line.bytes) { + self.duplicate_evidence |= self.cache_evidence.is_some(); + self.cache_evidence = Some(evidence); + } + return; + } + if member != MemberId::Seed { + return; + } + if let Ok(event) = serde_json::from_slice::(line.bytes) { + self.ready |= event["schema_version"] == 1 + && event["type"] == "status" + && event["data"]["message"] + == format!("skippy-serving listening: openai=127.0.0.1:{}", self.port); + } + } + fn line(&mut self, _: MemberId, _: ObservedLine<'_>) -> ProbeDecision { + ProbeDecision::Pending + } + fn tick(&mut self, context: Context<'_>) -> Action { + if self.stopping { + return Action::Complete; + } + if let Some(server) = self.server.take() { + return Action::Start(server); + } + if self.ready + && context + .members + .iter() + .any(|m| m.member == MemberId::Seed && m.state == MemberState::Starting) + { + return Action::Admit(MemberId::Seed); + } + if context + .members + .iter() + .any(|m| m.member == MemberId::Seed && matches!(m.state, MemberState::Ready { .. })) + && let Some(client) = self.client.take() + { + return match ExpectedExit::new(&[0], context.remaining) { + Ok(policy) => Action::StartExpected { + launch: client, + policy, + }, + Err(e) => Action::Reject(e.to_string()), + }; + } + if context.members.iter().any(|m| { + m.member == MemberId::WorkerOne + && matches!(m.state, MemberState::ExpectedExit { status: 0, .. }) + }) { + self.stopping = true; + return Action::Stop(MemberId::Seed); + } + Action::Pending + } +} +fn launch( + binary: &Path, + args: Vec, + output: &Path, + label: &str, + member: MemberId, + duration: Duration, +) -> Launch { + Launch { + member, + spec: ProcessSpec { + executable: binary.into(), + arguments: args.into_iter().map(Arg::Public).collect(), + cwd: output.into(), + environment: environment(&[]), + }, + files: OutputFiles { + stdout: Some(output.join(format!("{label}.stdout.log"))), + stderr: Some(output.join(format!("{label}.stderr.log"))), + }, + readiness_deadline: duration, + } +} +pub(super) fn run( + input: &Cell, + prepared: &Prepared, + model: &Model, + output: &Path, + duration: Duration, + cancel: &process::Cancellation, +) -> DynResult<()> { + let producer = &prepared.producer; + let prompt = output.join("cache-prompt.txt"); + std::fs::write( + &prompt, + "Describe the red ball and its shape in a short answer.\n".repeat(16), + )?; + let args = vec![ + "--output".into(), + "jsonl".into(), + "--runtime-bundle".into(), + producer.runtime_bundle.clone().into_os_string(), + "--runtime-selection".into(), + producer.backend.kind().into(), + "serve".into(), + "--model-path".into(), + input.model.clone().into_os_string(), + "--model-id".into(), + model.key.clone().into(), + "--bind-addr".into(), + format!("127.0.0.1:{}", input.port).into(), + "--ctx-size".into(), + "2048".into(), + "--generation-concurrency".into(), + "1".into(), + "--n-gpu-layers".into(), + if producer.backend == Backend::Cpu { + "0" + } else { + "99" + } + .into(), + "--batch-size".into(), + "128".into(), + "--microbatch-size".into(), + "64".into(), + "--threads".into(), + "4".into(), + "--threads-batch".into(), + "4".into(), + "--flash-attention".into(), + "enabled".into(), + "--kv-cache-type-k".into(), + "f16".into(), + "--kv-cache-type-v".into(), + "f16".into(), + "--prefix-cache".into(), + "on".into(), + "--prefix-cache-ram".into(), + "8GiB".into(), + "--prefix-cache-min-tokens".into(), + "1".into(), + "--kv-cache-disk".into(), + "off".into(), + "--temperature".into(), + "0".into(), + ]; + publish( + &output.join("cache-server-settings.json"), + &json!({"arguments":args,"runtime_bundle":producer.runtime_bundle,"c1_only":true,"long_pressure_L3":false}), + )?; + let client_args = vec![ + "open-ai-cache-reuse".into(), + "--base-url".into(), + format!("http://127.0.0.1:{}/v1", input.port).into(), + "--model".into(), + model.key.clone().into(), + "--prompt-file".into(), + prompt.into_os_string(), + "--max-tokens".into(), + "8".into(), + "--request-timeout-secs".into(), + "120".into(), + ]; + let mut owner = Owner { + server: Some(launch( + &producer.cli.path, + args, + output, + "cache-server", + MemberId::Seed, + duration, + )), + client: Some(launch( + &producer.correctness.path, + client_args, + output, + "cache-client", + MemberId::WorkerOne, + duration, + )), + ready: false, + stopping: false, + port: input.port, + cache_evidence: None, + duplicate_evidence: false, + }; + let report = retained::run(&mut owner, &limits(duration), cancel)?; + publish( + &output.join("cache-process.json"), + &json!({"success":report.success(),"outcome":format!("{:?}",report.outcome),"rejection":report.rejection,"failure":report.failure.as_ref().map(ToString::to_string)}), + )?; + if !report.success() { + return Err("fresh product cache correctness did not finish cleanly".into()); + } + if owner.duplicate_evidence { + return Err("generic cache client emitted duplicate evidence".into()); + } + let evidence = owner + .cache_evidence + .ok_or("generic cache client evidence missing")?; + evidence.verify()?; + publish(&output.join("cache-evidence.json"), &evidence) +} diff --git a/tools/xtask/src/automation/kv_validation/tests.rs b/tools/xtask/src/automation/kv_validation/tests.rs new file mode 100644 index 0000000000..69458b06d9 --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/tests.rs @@ -0,0 +1,376 @@ +use super::{ + contract::{self, Backend, Cell, Tool}, + evidence, execution, jy_plan, +}; +use std::path::PathBuf; + +#[cfg(unix)] +#[test] +fn evidence_archive_receipt_binds_contents_and_excludes_runtime_symlinks() { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("evidence"); + std::fs::create_dir_all(output.join("nested")).unwrap(); + std::fs::write(output.join("result.json"), br#"{"status":"passed"}"#).unwrap(); + std::fs::write( + output.join("nested/response.txt"), + b"exact generated content", + ) + .unwrap(); + let outside = dir.path().join("external-runtime"); + std::fs::create_dir(&outside).unwrap(); + std::fs::write( + outside.join("library"), + b"must not enter evidence transport", + ) + .unwrap(); + std::os::unix::fs::symlink(&outside, output.join("selected-runtime")).unwrap(); + execution::archive(&output).unwrap(); + + let receipt: serde_json::Value = + serde_json::from_slice(&std::fs::read(output.with_extension("archive.json")).unwrap()) + .unwrap(); + assert_eq!(receipt["archive"], "evidence.tar.gz"); + let bytes = std::fs::read(output.with_extension("tar.gz")).unwrap(); + assert_eq!(receipt["sha256"], super::hash(&bytes)); + let gzip = flate2::read::GzDecoder::new(bytes.as_slice()); + let mut tar = tar::Archive::new(gzip); + let mut restored = std::collections::BTreeMap::new(); + for entry in tar.entries().unwrap() { + let mut entry = entry.unwrap(); + assert!(entry.header().entry_type().is_file()); + let path = entry.path().unwrap().to_path_buf(); + let mut contents = Vec::new(); + std::io::Read::read_to_end(&mut entry, &mut contents).unwrap(); + assert!(restored.insert(path, contents).is_none()); + } + assert_eq!( + restored, + std::collections::BTreeMap::from([ + ( + PathBuf::from("evidence/result.json"), + br#"{"status":"passed"}"#.to_vec() + ), + ( + PathBuf::from("evidence/nested/response.txt"), + b"exact generated content".to_vec() + ), + ]) + ); + assert!( + execution::archive(&output).is_err(), + "never overwrite existing evidence" + ); +} + +#[cfg(unix)] +#[test] +fn archive_refuses_non_unicode_filename_before_creating_transport() { + use std::os::unix::ffi::OsStringExt; + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join(std::ffi::OsString::from_vec(vec![0xff])); + let error = execution::archive(&output).unwrap_err(); + assert!(error.to_string().contains("filename must be Unicode")); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); +} + +#[test] +fn cache_projection_rejects_content_mismatch_invalid_reuse_and_extra_payload() { + let valid = serde_json::json!({ + "status":"pass", "content_parity":"exact", "cold_content":"round", + "repeat":{"cached_tokens":20,"prompt_tokens":22,"content":"round"}, + "growing_chat":{"cached_tokens":20,"prompt_tokens":28,"content":"sphere"}, + "growing_chat_repeat":{"cached_tokens":26,"prompt_tokens":28,"content":"sphere"} + }); + let parse = |value: serde_json::Value| -> crate::command::DynResult<()> { + serde_json::from_value::(value)?.verify() + }; + parse(valid.clone()).unwrap(); + for (pointer, value) in [ + ("/repeat/content", serde_json::json!("different")), + ( + "/growing_chat_repeat/content", + serde_json::json!("different"), + ), + ("/repeat/cached_tokens", serde_json::json!(0)), + ("/repeat/cached_tokens", serde_json::json!(23)), + ("/status", serde_json::json!("failed")), + ] { + let mut changed = valid.clone(); + *changed.pointer_mut(pointer).unwrap() = value; + assert!(parse(changed).is_err()); + } + let mut extra = valid; + extra["arbitrary_protocol_headers"] = serde_json::json!({"header":"not retained"}); + assert!(parse(extra).is_err()); +} + +#[test] +fn doctor_requires_explicit_clean_issue_and_exact_selected_leaf() { + let path = PathBuf::from("/runtime/exact-leaf"); + let clean = serde_json::json!({"native_runtime":{"path":path},"runtime_issue":null}); + evidence::doctor(&clean, &path).unwrap(); + for invalid in [ + serde_json::json!({"native_runtime":{"path":path}}), + serde_json::json!({"native_runtime":{"path":path},"runtime_issue":"ABI mismatch"}), + serde_json::json!({"native_runtime":{"path":"/runtime"},"runtime_issue":null}), + serde_json::json!({"runtime_issue":null}), + ] { + assert!(evidence::doctor(&invalid, &path).is_err()); + } +} + +#[test] +fn separately_pinned_headers_cannot_mismatch_the_runtime_build() { + let source = "1".repeat(40); + let manifest = serde_json::json!({ + "build":{"backend":"metal","llama_patched_sha":source}, + "runtime":{"backend":{"kind":"metal"},"libraries":["lib/libllama.dylib"]} + }); + super::verify_manifest(&manifest, Backend::Metal, &source).unwrap(); + assert!(super::verify_manifest(&manifest, Backend::Metal, &"2".repeat(40)).is_err()); + assert!(super::verify_manifest(&manifest, Backend::Cuda, &source).is_err()); + let mut missing = manifest; + missing["build"] + .as_object_mut() + .unwrap() + .remove("llama_patched_sha"); + assert!(super::verify_manifest(&missing, Backend::Metal, &source).is_err()); +} + +#[test] +fn exact_four_agentx_model_bytes_and_pins_are_retained() { + let models = contract::models().unwrap(); + assert_eq!(super::hash(contract::CATALOG), contract::CATALOG_SHA); + assert_eq!( + models.iter().map(|m| m.key.as_str()).collect::>(), + [ + "qwen3-4b-q4-k-m", + "qwen3.5-4b-q4-k-m", + "qwen3-coder-30b-a3b-q4-k-m", + "qwen3.5-35b-a3b-q4-k-m" + ] + ); + assert_eq!(models.iter().filter(|m| m.recurrent_case()).count(), 2); + assert!( + models + .iter() + .all(|m| m.reference().contains("@") && m.reference().ends_with("Q4_K_M.gguf")) + ); +} + +fn matrix(backend: Backend) -> String { + let mut text = format!("MODEL backend={} loads=1\n", backend.device()); + for k in ["f32", "f16", "bf16", "q4_0", "q4_1", "q5_0", "q5_1", "q8_0"] { + for v in ["f32", "f16", "bf16", "q4_0", "q4_1", "q5_0", "q5_1", "q8_0"] { + if backend == Backend::Metal && k != v { + text += &format!( + "SKIP backend=MTL0 K={k} V={v} reason=preexisting_Metal_requires_matching_KV_types\n" + ); + } else { + text += &format!( + "REAL_FA backend={} K={k} V={v} q=39 physical=256 logical=256 requests=1\nPASS backend={} K={k} V={v} prefill=39 decoded=16 attention_layers=8 seconds=0.5 completion_hex=6869\n", + backend.device(), + backend.device() + ); + } + } + } + text + &format!( + "SUMMARY backend={} model_loads=1 passed={} failed=0 skipped={}\n", + backend.device(), + backend.pairs(), + if backend == Backend::Metal { 56 } else { 0 } + ) +} + +#[test] +fn gpu_evidence_requires_every_pair_actual_graph_and_finite_results() { + for backend in [Backend::Cpu, Backend::Metal, Backend::Cuda] { + let text = matrix(backend); + evidence::matrix(&text, backend).unwrap(); + for broken in [ + text.replacen("q=39", "q=1", 1), + text.replacen("seconds=0.5", "seconds=NaN", 1), + text.replacen("decoded=16", "decoded=0", 1), + text.replacen("completion_hex=6869", "completion_hex=", 1), + text.replacen("failed=0", "failed=1", 1), + text.replacen("REAL_FA ", "MISSING_FA ", 1), + ] { + assert!(evidence::matrix(&broken, backend).is_err()); + } + assert!( + evidence::matrix(&(text.clone() + "PASS backend=CPU K=f16 V=f16\n"), backend).is_err() + ); + } + assert!( + evidence::matrix(&matrix(Backend::Cpu), Backend::Cuda).is_err(), + "CPU cannot qualify requested CUDA" + ); +} + +#[test] +fn rust_success_marker_cannot_hide_an_ignored_or_missing_test() { + let name = "fixture::required_cache_test"; + evidence::rust_test( + &format!("test {name} ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored;"), + name, + ) + .unwrap(); + for text in [ + "test result: ok. 0 passed; 0 failed; 1 ignored;", + "test result: ok. 1 passed; 0 failed; 0 ignored;", + ] { + assert!(evidence::rust_test(text, name).is_err()); + } +} + +#[test] +fn changed_artifact_bytes_fail_identity_before_execution() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("tool"); + std::fs::write(&path, b"first").unwrap(); + let tool = Tool { + path: path.clone(), + sha256: super::hash(b"first"), + }; + tool.verify().unwrap(); + std::fs::write(path, b"other").unwrap(); + assert!(tool.verify().is_err()); +} + +#[test] +fn unknown_model_and_unbounded_cell_are_rejected() { + let mut cell = Cell { + schema_version: 1, + prepared: Tool { + path: "/prepared.json".into(), + sha256: "0".repeat(64), + }, + model_key: "qwen3.5-4b-q4-k-m".into(), + model: "/model.gguf".into(), + port: 19337, + execution_seconds: 120, + }; + cell.validate().unwrap(); + cell.model_key = "substituted-model".into(); + assert!(cell.validate().is_err()); + cell.model_key = "qwen3.5-4b-q4-k-m".into(); + cell.execution_seconds = u64::MAX; + assert!(cell.validate().is_err()); +} + +#[test] +fn excluded_sparks_are_refused_by_id_and_real_hostname() { + for (id, host) in [ + ("spark-000280", "different"), + ("spark-000499", "different"), + ("spark-000137", "spark-db08"), + ("spark-000137", "spark-9f06"), + ] { + assert!(jy_plan::excluded(id, host)); + } + assert!(!jy_plan::excluded("spark-000137", "spark-james")); +} + +#[test] +fn accepted_jy_envelope_keeps_all_four_pins_and_never_submits() { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("jobs"); + let input = jy_plan::Fleet { + schema_version: 1, + backend: Backend::Cuda, + source_commit: "1".repeat(40), + prepared_image: format!("sha256:{}", "2".repeat(64)), + automation: "/opt/xtask".into(), + prepared: Tool { + path: "/opt/prepared.json".into(), + sha256: "3".repeat(64), + }, + nodes: vec![jy_plan::Node { + id: "spark-000137".into(), + hostname: "spark-james".into(), + }], + execution_seconds: 1800, + }; + jy_plan::run(input, &output).unwrap(); + for model in contract::models().unwrap() { + let value: serde_json::Value = serde_json::from_slice( + &std::fs::read(output.join(format!("{}.json", model.key))).unwrap(), + ) + .unwrap(); + let runtime = &value["spec"]["runtime"]; + assert_eq!(runtime["model_package"]["ref"], model.reference()); + assert_eq!(runtime["model_package"]["sha256"], model.files[0].sha256); + assert_eq!(runtime["models"][0]["env"], "AGENTX_MODEL_PATH"); + assert_eq!(runtime["workspace"]["repos"][0]["rev"], "1".repeat(40)); + let command = runtime["command"].as_str().unwrap(); + assert!(command.contains("run-env")); + assert!( + !command.contains("cargo ") + && !command.contains("base64") + && !command.contains("jy submit") + ); + assert!(command.contains("exit \"$worker_status\"")); + assert_eq!( + value["spec"]["target"]["nodes"], + serde_json::json!(["spark-000137"]) + ); + } + assert_eq!(std::fs::read_dir(output).unwrap().count(), 5); +} + +#[cfg(unix)] +#[test] +fn supervised_child_captures_success_and_refuses_failed_exit() { + let dir = tempfile::tempdir().unwrap(); + let cancel = crate::process::Cancellation::default(); + let invoke = |label: &str, command: &str| { + execution::child( + &PathBuf::from("/bin/sh"), + vec!["-c".into(), command.into()], + (dir.path(), dir.path()), + label, + std::time::Duration::from_secs(2), + &cancel, + &[], + ) + }; + assert_eq!(invoke("success", "printf observed").unwrap(), "observed"); + assert!(invoke("failed", "printf rejected; exit 7").is_err()); + let receipt: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path().join("failed.process.json")).unwrap()) + .unwrap(); + assert_eq!(receipt["success"], false); + assert_eq!(receipt["exit_code"], 7); + assert_eq!(receipt["cleanup_complete"], true); +} + +#[cfg(unix)] +#[test] +fn cancellation_refuses_child_and_preserves_failed_process_receipt() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("must-not-start"); + let cancel = crate::process::Cancellation::default(); + cancel.cancel(); + let result = execution::child( + &PathBuf::from("/bin/sh"), + vec![ + "-c".into(), + "printf started > \"$1\"".into(), + "fixture".into(), + marker.clone().into_os_string(), + ], + (dir.path(), dir.path()), + "cancelled", + std::time::Duration::from_secs(2), + &cancel, + &[], + ); + assert!(result.is_err()); + assert!(!marker.exists()); + let receipt: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path().join("cancelled.process.json")).unwrap()) + .unwrap(); + assert_eq!(receipt["success"], false); + assert!(receipt["supervision_failure"].as_str().is_some()); +} diff --git a/tools/xtask/src/automation/mod.rs b/tools/xtask/src/automation/mod.rs index 4dfb185b43..37b883b9e0 100644 --- a/tools/xtask/src/automation/mod.rs +++ b/tools/xtask/src/automation/mod.rs @@ -38,6 +38,7 @@ pub(crate) mod event_benchmark_runner; pub(crate) mod family_battery_policy; pub(crate) mod family_model_identity; pub(crate) mod guardrail_corpus; +pub(crate) mod kv_validation; pub(crate) mod laya; pub(crate) mod local_ports; pub(crate) mod logging_console; diff --git a/tools/xtask/src/automation/native_artifact_identity.rs b/tools/xtask/src/automation/native_artifact_identity.rs index 295638cfb8..2f89d2abbf 100644 --- a/tools/xtask/src/automation/native_artifact_identity.rs +++ b/tools/xtask/src/automation/native_artifact_identity.rs @@ -42,7 +42,7 @@ fn complete_tree(root: &Path) -> DynResult<()> { Ok(()) } -fn observe(root: &Path) -> DynResult { +pub(in crate::automation) fn observe(root: &Path) -> DynResult { if !root.is_absolute() || !root.is_dir() { return Err("native artifact observation requires an absolute directory".into()); } diff --git a/tools/xtask/src/cli.rs b/tools/xtask/src/cli.rs index 8ceb383912..00047cf5f9 100644 --- a/tools/xtask/src/cli.rs +++ b/tools/xtask/src/cli.rs @@ -7,6 +7,7 @@ const HF_CONVERTED_ARTIFACT_USAGE: &str = pub(crate) fn print_usage() { println!(" cargo xtool ci-ops pr-authority-audit --help"); println!(" cargo xtool automation mtp-scheduler --help"); + println!(" cargo xtool automation kv-validation --help"); println!( " cargo xtool automation agent-recording-proxy UPSTREAM_API_BASE CAPTURE_JSONL READY_FILE LIFETIME_SECONDS" ); @@ -107,6 +108,7 @@ pub(crate) struct Cli<'a> { } pub(crate) enum CliCommand<'a> { + KvValidation(&'a [String]), MtpScheduler(&'a [String]), MtpSchedulerWorker(&'a [String]), SuffixProposer(&'a [String]), @@ -304,6 +306,9 @@ impl<'a> Cli<'a> { [domain, scope, rest @ ..] if domain == "automation" && scope == "cache-family-moe" => { CliCommand::CacheFamilyMoe(rest) } + [domain, scope, rest @ ..] if domain == "automation" && scope == "kv-validation" => { + CliCommand::KvValidation(rest) + } [domain, scope, rest @ ..] if domain == "automation" && scope == "cache-family-run" => { CliCommand::CacheFamilyRun(rest) } diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs index bc721fbd2f..ebf1ca3a56 100644 --- a/tools/xtask/src/main.rs +++ b/tools/xtask/src/main.rs @@ -52,6 +52,7 @@ fn run() -> DynResult<()> { .map(|path| repository::RepositoryRoot::resolve(Some(path))) .transpose()?; match parsed.command { + cli::CliCommand::KvValidation(rest) => automation::kv_validation::run(rest), cli::CliCommand::EndpointModelDiscovery(rest) => { automation::endpoint_model_discovery::run(rest) } From 5e45c6a49af3fd81a8f5ce3ab0ef25e735c9fb96 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 18:00:52 +1100 Subject: [PATCH 10/81] test(skippy): drain snapshot fixture output while children run --- .../tests/snapshot_promotion_cli.rs | 22 +-- .../snapshot_promotion_cli/child_capture.rs | 131 ++++++++++++++++++ .../snapshot_promotion_cli/generic_jobs.rs | 18 +-- .../tests/snapshot_promotion_cli/layer_job.rs | 16 +-- 4 files changed, 143 insertions(+), 44 deletions(-) create mode 100644 skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs diff --git a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli.rs b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli.rs index 197592fae0..bf45c34dad 100644 --- a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli.rs +++ b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli.rs @@ -7,8 +7,7 @@ use hub_fixture::Server; use std::{ fs, process::{Command, Output, Stdio}, - thread, - time::{Duration, Instant}, + time::Duration, }; fn cli(endpoint: &str, args: &[&str]) -> Output { @@ -28,22 +27,13 @@ fn cli(endpoint: &str, args: &[&str]) -> Output { finish_fixture_child(child) } -fn finish_fixture_child(mut child: std::process::Child) -> Output { - let deadline = Instant::now() + Duration::from_secs(30); - while child.try_wait().unwrap().is_none() { - if Instant::now() >= deadline { - child.kill().unwrap(); - let output = child.wait_with_output().unwrap(); - panic!( - "snapshot CLI timed out: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - thread::sleep(Duration::from_millis(10)); - } - child.wait_with_output().unwrap() +fn finish_fixture_child(child: std::process::Child) -> Output { + child_capture::finish(child, Duration::from_secs(30), "snapshot CLI") } +#[path = "snapshot_promotion_cli/child_capture.rs"] +mod child_capture; + fn info() -> Vec { serde_json::to_vec(&serde_json::json!({"id":"fixture/model","sha":"a".repeat(40)})).unwrap() } diff --git a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs new file mode 100644 index 0000000000..1659ebb274 --- /dev/null +++ b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs @@ -0,0 +1,131 @@ +//! Drain fixture output while the owned child runs, keeping its existing deadline. + +use std::{ + io::{Read, Write}, + process::{Child, Command, Output, Stdio}, + thread, + time::{Duration, Instant}, +}; + +const STREAM_LIMIT: usize = 2 * 1024 * 1024; +const FIXTURE_MODE: &str = "SKIPPY_SNAPSHOT_CAPTURE_FIXTURE"; + +struct CapturedChild { + output: Output, + timed_out: bool, + output_exceeded: bool, +} + +pub(super) fn finish(child: Child, timeout: Duration, label: &str) -> Output { + let captured = capture(child, timeout); + assert!( + !captured.timed_out, + "{label} timed out: {}", + captured.output.status + ); + assert!( + !captured.output_exceeded, + "{label} exceeded fixture output limit" + ); + captured.output +} + +fn drain(mut stream: impl Read) -> (Vec, bool) { + let mut bytes = Vec::new(); + stream + .by_ref() + .take((STREAM_LIMIT + 1) as u64) + .read_to_end(&mut bytes) + .expect("read fixture output"); + let exceeded = bytes.len() > STREAM_LIMIT; + bytes.truncate(STREAM_LIMIT); + // Continue draining excessive output rather than blocking the child after + // filling the bounded retained buffer. The caller still rejects overflow. + std::io::copy(&mut stream, &mut std::io::sink()).expect("drain fixture output"); + (bytes, exceeded) +} + +fn capture(mut child: Child, timeout: Duration) -> CapturedChild { + let stdout = child.stdout.take().expect("fixture stdout is piped"); + let stderr = child.stderr.take().expect("fixture stderr is piped"); + thread::scope(|scope| { + let stdout = scope.spawn(|| drain(stdout)); + let stderr = scope.spawn(|| drain(stderr)); + let deadline = Instant::now() + timeout; + let (status, timed_out) = loop { + if let Some(status) = child.try_wait().expect("poll fixture child") { + break (status, false); + } + if Instant::now() >= deadline { + let _ = child.kill(); + break (child.wait().expect("reap timed-out fixture child"), true); + } + thread::sleep(Duration::from_millis(5)); + }; + let (stdout, stdout_exceeded) = stdout.join().expect("stdout reader panicked"); + let (stderr, stderr_exceeded) = stderr.join().expect("stderr reader panicked"); + CapturedChild { + output: Output { + status, + stdout, + stderr, + }, + timed_out, + output_exceeded: stdout_exceeded || stderr_exceeded, + } + }) +} + +fn fixture(mode: &str) -> Child { + Command::new(std::env::current_exe().unwrap()) + .env_clear() + .env(FIXTURE_MODE, mode) + .args([ + "--exact", + "child_capture::fixture_child", + "--nocapture", + "--test-threads=1", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() +} + +#[test] +fn fixture_child() { + match std::env::var(FIXTURE_MODE).as_deref() { + Ok("large") => { + std::io::stdout() + .write_all(&vec![b'o'; 1024 * 1024]) + .unwrap(); + std::io::stderr() + .write_all(&vec![b'e'; 1024 * 1024]) + .unwrap(); + } + Ok("wait") => thread::sleep(Duration::from_secs(60)), + _ => {} + } +} + +#[test] +fn drains_both_streams_before_waiting_for_exit() { + let output = finish(fixture("large"), Duration::from_secs(10), "large fixture"); + assert!(output.status.success()); + assert!( + output + .stdout + .windows(1024 * 1024) + .any(|bytes| bytes.iter().all(|byte| *byte == b'o')) + ); + assert_eq!(output.stderr, vec![b'e'; 1024 * 1024]); +} + +#[test] +fn deadline_still_kills_and_reaps_the_owned_child() { + let started = Instant::now(); + let captured = capture(fixture("wait"), Duration::from_millis(100)); + assert!(captured.timed_out); + assert!(!captured.output.status.success()); + assert!(started.elapsed() < Duration::from_secs(5)); +} diff --git a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/generic_jobs.rs b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/generic_jobs.rs index c4b01ff54f..8b615f410c 100644 --- a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/generic_jobs.rs +++ b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/generic_jobs.rs @@ -5,7 +5,7 @@ use skippy_model_package::jobs::{HardwareFlavor, plan_cpu_job_from_hardware}; use std::{ path::Path, process::{Command, Stdio}, - time::{Duration, Instant}, + time::Duration, }; fn fixture() -> Value { let plan = plan_cpu_job_from_hardware( @@ -38,7 +38,7 @@ fn hex_digest(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } fn invoke(root: &Path, args: &[&str]) -> std::process::Output { - let mut child = Command::new(env!("CARGO_BIN_EXE_model-package-generic-jobs")) + let child = Command::new(env!("CARGO_BIN_EXE_model-package-generic-jobs")) .args(args) .current_dir(root) .env_clear() @@ -46,19 +46,7 @@ fn invoke(root: &Path, args: &[&str]) -> std::process::Output { .stderr(Stdio::piped()) .spawn() .unwrap(); - let until = Instant::now() + Duration::from_secs(10); - while child.try_wait().unwrap().is_none() { - if Instant::now() >= until { - child.kill().unwrap(); - let output = child.wait_with_output().unwrap(); - panic!( - "finite facade timed out: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - std::thread::sleep(Duration::from_millis(5)); - } - child.wait_with_output().unwrap() + super::child_capture::finish(child, Duration::from_secs(10), "finite facade") } #[test] fn actual_generic_jobs_facade_prepares_original_72h_without_network_or_token() { diff --git a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/layer_job.rs b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/layer_job.rs index 1de8031ac8..ca7ff017d7 100644 --- a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/layer_job.rs +++ b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/layer_job.rs @@ -4,20 +4,10 @@ use std::{ fs, path::Path, process::{Command, Output, Stdio}, - thread, - time::{Duration, Instant}, + time::Duration, }; -fn finish(mut child: std::process::Child) -> Output { - let until = Instant::now() + Duration::from_secs(10); - while child.try_wait().unwrap().is_none() { - if Instant::now() >= until { - child.kill().unwrap(); - let result = child.wait_with_output().unwrap(); - panic!("owned layer CLI deadline: {}", result.status); - } - thread::sleep(Duration::from_millis(5)); - } - child.wait_with_output().unwrap() +fn finish(child: std::process::Child) -> Output { + super::child_capture::finish(child, Duration::from_secs(10), "owned layer CLI") } fn inputs(root: &Path) -> (std::path::PathBuf, std::path::PathBuf) { let manifest = root.join("model-package.json"); From 0f741cd9381ed00738c3c7f247a670311fc89756 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 18:04:21 +1100 Subject: [PATCH 11/81] docs(skippy): record throughput parity and four-model CUDA validation --- .../docs/design/INDEXED_ATTENTION_STATUS.md | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md index b833ac9147..2bbe8b5299 100644 --- a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -3,8 +3,9 @@ Status on 2026-10-31: implementation available for review. All eight real-model attention layers match existing dense CUDA attention exactly at the same logical layout. Strict cache tests pass on CUDA and Metal. Comparison against the old -physical layout still fails; that diagnostic is retained below. Final performance -qualification and four-model CUDA coverage are in progress. +physical layout still fails; that diagnostic is retained below. The final CUDA +AgentX arm completes at 26.91 output tokens/s versus a fresh same-host standard +vanilla arm at 26.34. All four selected models pass their CUDA KV-format matrix. ## Change @@ -33,6 +34,15 @@ reviewers can inspect it independently. formats and all 64 CPU mixed K/V pairs. Graph checks require indices, lengths, the requested KV type, and the selected backend throughout prefill and decode. These are execution smoke checks, not cross-path numerical parity evidence. +- The four selected Q4_K_M models each pass all 64 CUDA mixed K/V pairs: dense + Qwen3-4B (36 attention layers), hybrid Qwen3.5-4B (8), Qwen3-Coder-30B (48), + and hybrid MoE Qwen3.5-35B (10). Source-identical Spark 000907 runs cover the + middle two; the final performance runtime on Spark 000137 covers the other + two. Each matrix loads its model once and checks every executed attention + graph's indices, lengths, K/V types and GPU backend. The final checked-in + driver additionally requires the exact expected attention-layer count and + all-vocabulary finite logits; earlier frozen smoke drivers check NaN-free + logits and a finite greedy-selected logit. Their proof scopes remain distinct. - Final CUDA proof job `job_x7fs8vb280zjz00`, run `run_nd0p378y1k069ct`, passes all eight real-model attention-layer replays, resident ownership checks, and the unchanged Qwen3.5-4B chat-parity and growing-checkpoint tests. The final @@ -122,5 +132,28 @@ including indexed attention's roughly `4.24 s` versus vanilla's `2.88 s`. This still trails the saved standard-vanilla pressure control. Full fixed-cohort job `job_agr2k8yy2ry29qe` is the separate performance qualification. +## Full fixed-work replay + +The final candidate job `job_agr2k8yy2ry29qe`, run `run_spranb971p0czpp`, +completed successfully on Spark 000137: **26.9097 output tokens/s**, all 69 +requests and 18,713 output tokens, zero errors. It read 3,562,313 cached prompt +tokens out of 3,940,542 presented tokens, the same cache work as the preceding +admission-fixed baseline. Peak sampled process RSS was 10.38 GiB. + +The fresh same-host standard vanilla confirmation (`job_jhe5qzycenack95`, run +`run_ghdjyknby3jdsmd`) also succeeds: **26.3370 output tokens/s**, 69 requests, +18,713 outputs and zero errors. It reads 3,566,742 cached prompt tokens and +peaks at 13.92 GiB sampled process RSS. Standard uses four separate KV slots; +Skippy retains unified KV. Both resolve 20 generation and 20 batch threads, +batch 2,048, microbatch 512 and F16 KV. Standard's thread settings resolve from +defaults and are verified in its log; Skippy passes them explicitly. + +This sequential single pair puts Skippy 2.17% ahead and supports throughput +parity on this workload, not a universal speedup claim. The previous standard +control was 26.8779, which illustrates run variation. This is not a six-arm +ABBAAB campaign or qualification of every model/concurrency. Source, runtime, +model, fixed-work, raw artifacts and GPU clock/temperature evidence are retained +in the independent comparison receipts. + The reusable four-model CUDA/Metal/CPU validation work is tracked in [todo.md](../../../todo.md). From d871b37f314f7f8a907c67fc641641380d032c20 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 18:38:17 +1100 Subject: [PATCH 12/81] test(skippy): verify native checkpoint cold offload and restart --- .../src/frontend/local_generation/tests.rs | 3 + .../local_generation/tests/durable_prefix.rs | 193 ++++++++++++++++++ .../kv_integration/config/durable_spill.rs | 4 + .../config/tests/native_spill_failures.rs | 105 ++++++++++ .../src/kv_integration/resident_offload.rs | 2 +- skippy/evals/kv-validation/README.md | 8 + todo.md | 12 ++ .../src/automation/kv_validation/execution.rs | 4 +- 8 files changed, 329 insertions(+), 2 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index ed2ebe25a4..8bc2c2addb 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -29,6 +29,9 @@ use skippy_inference_api::{InferenceBackend, generation::GenerationRequest}; use skippy_protocol::{LoadMode, StageConfig, StageKvCacheConfig, StageKvCacheMode}; use skippy_runtime::SamplingConfig; +#[path = "tests/durable_prefix.rs"] +mod durable_prefix; + // The real-model tests below are deliberately ignored by default. The // fixture contract is explicit: run them with both model-path variables set; // optionally set SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID to override the model id diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs new file mode 100644 index 0000000000..c5717f6855 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -0,0 +1,193 @@ +//! A fresh runtime must restore cold-evicted native state from committed L3. +use super::*; +use skippy_cache::{L3CacheManager, StoreLimits}; +use skippy_protocol::MessageBase; +use std::{path::Path, time::Instant}; + +fn backend_with_disk(root: &Path, disk_bytes: u64) -> Result { + let (mut backend, _) = recurrent_test_backend( + "native-durable-prefix", + "native-durable-prefix", + 512, + 64, + 8, + 512, + )?; + let manager = L3CacheManager::acquire(root, StoreLimits::new(disk_bytes, 0))?; + backend.kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &backend.config, + crate::runtime_state::loaded_model_state_kind(Some(&backend.runtime)), + crate::runtime_state::loaded_memory_cache_capabilities(Some(&backend.runtime)), + Some(manager), + None, + )? + .map(Arc::new); + Ok(backend) +} + +fn identity( + backend: &StageOpenAiBackend, + tokens: &[i32], +) -> crate::kv_integration::PrefillKvIdentity { + let config = &backend.config; + let base = MessageBase { + schema_version: 1, + run_id: config.run_id.clone(), + request_id: "durable-request".into(), + session_id: "source".into(), + stage_id: config.stage_id.clone(), + stage_index: config.stage_index, + topology_id: config.topology_id.clone(), + model_id: Some(config.model_id.clone()), + tokenizer_id: None, + chat_template_id: None, + seq: None, + }; + backend + .kv + .as_ref() + .expect("native KV enabled") + .prefill_identity(config, &base, 0, tokens) +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn native_cold_prefix_survives_runtime_restart() -> Result<()> { + let root = tempfile::tempdir()?; + let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(8); + let inputs = [11, 12, 13, 14]; + let (expected_kv, expected_recurrent, expected_output, stored) = { + let backend = backend_with_disk(root.path(), 1 << 30)?; + let kv = backend.kv.as_ref().expect("disk cache enabled"); + let stored = identity(&backend, &tokens); + let (attention, recurrent, output) = { + let mut runtime = backend.runtime.lock().unwrap(); + runtime.prefill("source", &tokens)?; + let attention = runtime + .export_kv_page("source", 0, tokens.len() as u64)? + .payload; + let recurrent = runtime.export_recurrent_state("source")?; + assert!(!attention.is_empty()); + assert!(!recurrent.is_empty()); + let record = kv + .record_resident_prefix(&mut runtime, "source", &stored, &tokens)? + .expect("native checkpoint captured"); + assert!(record.stored); + let output = inputs + .iter() + .map(|&token| runtime.decode("source", token)) + .collect::>>()?; + runtime.drop_session_timed("source")?; + runtime.ensure_session_active("eviction")?; + let evicted = + kv.evict_resident_prefix_for_tokens(&mut runtime, "eviction", u64::MAX)?; + assert_eq!(evicted.evicted_entries, 1); + (attention, recurrent, output) + }; + let l3 = kv.l3.as_ref().expect("persistent tier enabled"); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(location) = l3.locate_longest(&stored.namespace, &tokens, 1)? { + assert_eq!(location.token_count, tokens.len() as u64); + break; + } + anyhow::ensure!( + Instant::now() < deadline, + "cold offload did not commit to L3" + ); + thread::sleep(Duration::from_millis(2)); + } + (attention, recurrent, output, stored) + }; // Drop the model, runtime, cache and joined writer before reopening L3. + let backend = backend_with_disk(root.path(), 1 << 30)?; + let kv = backend + .kv + .as_ref() + .expect("disk cache enabled after restart"); + let mut runtime = backend.runtime.lock().unwrap(); + let restored = kv + .restore_exact_state(&mut runtime, "restarted", &[stored])? + .expect("fresh runtime must restore from persistent cache"); + assert_eq!(restored.source, "l3"); + assert_eq!(restored.token_count, tokens.len()); + assert_eq!( + runtime.canonical_session_position("restarted")?, + tokens.len() as u64 + ); + assert!( + runtime + .export_kv_page("restarted", 0, tokens.len() as u64)? + .payload + == expected_kv, + "attention bytes changed after L3 restore" + ); + assert!( + runtime.export_recurrent_state("restarted")? == expected_recurrent, + "recurrent bytes changed after L3 restore" + ); + let actual = inputs + .iter() + .map(|&token| runtime.decode("restarted", token)) + .collect::>>()?; + assert_eq!( + actual, expected_output, + "fixed-input continuation changed after L3 restore" + ); + Ok(()) +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn native_cold_offload_refusal_keeps_inference_usable() -> Result<()> { + let root = tempfile::tempdir()?; + let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(8); + let inputs = [11, 12, 13, 14]; + let stored = { + // One byte cannot admit either attention or recurrent checkpoint data. + let backend = backend_with_disk(root.path(), 1)?; + let kv = backend.kv.as_ref().expect("refusing disk tier enabled"); + let stored = identity(&backend, &tokens); + let mut runtime = backend.runtime.lock().unwrap(); + runtime.prefill("source", &tokens)?; + assert!( + kv.record_resident_prefix(&mut runtime, "source", &stored, &tokens)? + .is_some() + ); + let expected = inputs + .iter() + .map(|&token| runtime.decode("source", token)) + .collect::>>()?; + runtime.drop_session_timed("source")?; + runtime.ensure_session_active("reuse")?; + assert_eq!( + kv.evict_resident_prefix_for_tokens(&mut runtime, "reuse", u64::MAX)? + .evicted_entries, + 1 + ); + assert_eq!( + runtime.memory_used_cells("reuse")?, + 0, + "refused offload must not pin attention cells" + ); + runtime.prefill("reuse", &tokens)?; + let actual = inputs + .iter() + .map(|&token| runtime.decode("reuse", token)) + .collect::>>()?; + assert_eq!( + actual, expected, + "cold recomputation changed after refused offload" + ); + stored + }; // Join the writer, including the refused write, before checking persistence. + let backend = backend_with_disk(root.path(), 1)?; + let kv = backend.kv.as_ref().expect("persistent tier enabled"); + assert!( + kv.l3 + .as_ref() + .unwrap() + .locate_longest(&stored.namespace, &tokens, 1)? + .is_none() + ); + Ok(()) +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs index 371795768e..afdcc5366b 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs @@ -317,3 +317,7 @@ mod native_reservation_tests { ); } } + +#[cfg(test)] +#[path = "tests/native_spill_failures.rs"] +mod native_spill_failures; diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs new file mode 100644 index 0000000000..799bcb1a3f --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs @@ -0,0 +1,105 @@ +//! Native cold-export credits and identity claims follow the queued payload. +use super::*; +use crate::kv_integration::resident_offload::NativeOffloadClaim; +use std::sync::atomic::Ordering; + +fn pending(token: i32, bytes: usize) -> PendingDurableSpill { + PendingDurableSpill { + page_id: format!("native-{token}"), + payload: skippy_cache::ExactStatePayload::kv_recurrent( + vec![7; bytes / 2], + vec![9; bytes - bytes / 2], + ), + extra: super::super::super::ExactStateExtra::default(), + namespace: "native-test".into(), + token_ids: vec![token], + native_raw: true, + l3_cost: None, + } +} + +#[test] +fn native_spill_queue_full_and_disconnect_release_bytes_and_claims() { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let sender = DurableSpillSender::new(tx, 64); + let claims = Arc::new(Mutex::new(BTreeSet::new())); + for (token, accepted) in [(1, true), (2, false)] { + let claim = NativeOffloadClaim::acquire(&claims, "native-test", &[token]).unwrap(); + let reservation = sender.try_reserve(16).unwrap(); + assert_eq!( + sender.send_reserved(pending(token, 16), reservation, claim), + accepted + ); + assert_eq!(sender.held_bytes.load(Ordering::Acquire), 16); + assert_eq!(claims.lock().unwrap().len(), 1); + } + let active = rx.recv().unwrap(); + assert!(NativeOffloadClaim::acquire(&claims, "native-test", &[1]).is_none()); + assert_eq!(sender.held_bytes.load(Ordering::Acquire), 16); + drop(active); + drop(rx); + let claim = NativeOffloadClaim::acquire(&claims, "native-test", &[1]).unwrap(); + assert!(!sender.send_reserved(pending(1, 16), sender.try_reserve(16).unwrap(), claim)); + assert_eq!(sender.held_bytes.load(Ordering::Acquire), 0); + assert!(claims.lock().unwrap().is_empty()); + assert!(sender.try_reserve(64).is_some()); +} + +#[test] +fn native_spill_underestimated_payload_releases_reservation_and_claim() { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let sender = DurableSpillSender::new(tx, 64); + let claims = Arc::new(Mutex::new(BTreeSet::new())); + let claim = NativeOffloadClaim::acquire(&claims, "native-test", &[1]).unwrap(); + assert!(!sender.send_reserved(pending(1, 17), sender.try_reserve(16).unwrap(), claim)); + assert_eq!(sender.held_bytes.load(Ordering::Acquire), 0); + assert!(claims.lock().unwrap().is_empty()); + assert!(matches!( + rx.try_recv(), + Err(std::sync::mpsc::TryRecvError::Empty) + )); +} + +#[test] +fn native_spill_blocked_and_refused_write_retains_then_releases_credits() { + let root = tempfile::tempdir().unwrap(); + let tier = Arc::new(L3Tier::open(root.path(), 1, "native-spill-refusal".into(), 4096).unwrap()); + let received = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let pause = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let (sender, worker) = start_durable_spill_worker( + Some(tier.clone()), + false, + 64, + "native-spill-test", + received.clone(), + pause.clone(), + ) + .unwrap(); + let sender = sender.unwrap(); + let claims = Arc::new(Mutex::new(BTreeSet::new())); + let claim = NativeOffloadClaim::acquire(&claims, "native-test", &[1]).unwrap(); + assert!(sender.send_reserved(pending(1, 64), sender.try_reserve(64).unwrap(), claim)); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while received.load(Ordering::Acquire) == 0 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let writing = received.load(Ordering::Acquire) == 1; + let held = sender.held_bytes.load(Ordering::Acquire); + let refused = sender.try_reserve(1).is_none(); + let claimed = NativeOffloadClaim::acquire(&claims, "native-test", &[1]).is_none(); + let held_bytes = sender.held_bytes.clone(); + // Always release and join before asserting, including on a failed admission. + pause.store(false, Ordering::Release); + drop(sender); + worker.unwrap().join().unwrap(); + assert!(writing); + assert_eq!(held, 64); + assert!(refused && claimed); + assert_eq!(held_bytes.load(Ordering::Acquire), 0); + assert!(claims.lock().unwrap().is_empty()); + assert!( + tier.locate_longest("native-test", &[1], 1) + .unwrap() + .is_none() + ); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs index 634d44c20f..813a48017b 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -10,7 +10,7 @@ pub(super) struct NativeOffloadClaim { } impl NativeOffloadClaim { - fn acquire( + pub(in crate::kv_integration) fn acquire( claims: &Arc>>, namespace: &str, tokens: &[i32], diff --git a/skippy/evals/kv-validation/README.md b/skippy/evals/kv-validation/README.md index e5d7866c79..6b953cab8c 100644 --- a/skippy/evals/kv-validation/README.md +++ b/skippy/evals/kv-validation/README.md @@ -22,6 +22,14 @@ This foundation runs: * The unchanged strict chat-parity and growing-checkpoint Rust regressions for the catalog's two recurrent/hybrid workloads. These fixtures retain their recurrent message-boundary assertions; dense rows use the generic HTTP gate. +* For those hybrid rows, cold eviction of a 64-token native checkpoint after + releasing its source lane, followed by model/runtime/cache reload against the + same L3 directory. Require an actual L3 hit, identical attention and recurrent + payload bytes, and four matching fixed-input continuation predictions. This + runs in one test process and does not qualify fresh-process server restart. + A second model test refuses L3 writes with a one-byte disk budget, requires + native attention cells to be released, and verifies exact cold-recompute + predictions before checking that no durable entry was published. Long c4 state comparisons, L3 restart, pressure, default-budget qualification and standard-vanilla performance comparisons remain separate work in diff --git a/todo.md b/todo.md index c95e81c677..8cfb53724e 100644 --- a/todo.md +++ b/todo.md @@ -22,6 +22,18 @@ The new command passed end to end locally on the pinned Qwen3.5-4B model with all eight Metal formats. This does not mark the full four-model/backend suite, long-prefix ownership, L3 restart or throughput comparisons complete. +The hybrid rows now also require a bounded native cold-eviction/runtime-restart +regression. On local Qwen3.5-4B Metal and CPU, the 64-token checkpoint survives source +lane release, cold eviction, and fresh model/runtime/cache construction with an +L3 hit, identical attention/recurrent bytes and four identical fixed-input +continuation predictions. This is one-process runtime-restart evidence; the +fresh-process server and long-prefix L3 cases below remain open. Separate native +spill tests cover queue-full, disconnect, underestimated payload and blocked / +refused writes, checking that bytes and identity claims are released. +The model-backed refusal case also passes on both backends: a one-byte L3 budget +cannot retain a checkpoint, but eviction frees native attention cells and cold +recomputation produces identical fixed-input predictions. + ## Retain PR #2657's correctness requirements Cache-owned immutable checkpoints replace the old execution-lane pinning and diff --git a/tools/xtask/src/automation/kv_validation/execution.rs b/tools/xtask/src/automation/kv_validation/execution.rs index e2c001246e..575ee2f47a 100644 --- a/tools/xtask/src/automation/kv_validation/execution.rs +++ b/tools/xtask/src/automation/kv_validation/execution.rs @@ -109,7 +109,7 @@ pub(super) fn run(input: Cell, output: &Path) -> DynResult<()> { let passed = result.is_ok() && finish.is_ok() && Instant::now() < deadline; publish( &output.join("result.json"), - &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"scope":"KVdtype_dispatch_generic_c1_cache_plus_declared_recurrent_regressions_not_long_c4_L3_or_performance"}), + &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"scope":"KVdtype_dispatch_generic_c1_cache_plus_recurrent_runtime_L3_restart_not_long_c4_process_restart_or_performance"}), )?; archive(output)?; finish?; @@ -285,6 +285,8 @@ fn recurrent( for suffix in [ "recurrent_chat_checkpoint_preserves_cached_output_parity", "recurrent_post_decode_checkpoint_reuses_a_growing_prompt", + "durable_prefix::native_cold_prefix_survives_runtime_restart", + "durable_prefix::native_cold_offload_refusal_keeps_inference_usable", ] { let test = format!("frontend::local_generation::tests::{suffix}"); let text = child( From 5b50723e4807aa67aff9176f99d7ac9984449c48 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sat, 31 Oct 2026 18:29:44 +1100 Subject: [PATCH 13/81] perf(ggml): route indexed decode through the vector attention kernel Indexed attention only chose the vector kernel for quantized K/V, so an f16 cache sent every decode batch to the MMA kernel. Prefill chunks and verify windows keep the MMA kernel. --- ...13-feat-ggml-read-request-local-KV-indices-in-flash-att.patch | 1 - 1 file changed, 1 deletion(-) diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch index d8da32bd6a..e901d8c814 100644 --- a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch +++ b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch @@ -1461,7 +1461,6 @@ index 5fa3e5308..b74322b6f 100644 + return BEST_FATTN_KERNEL_NONE; + } + if (Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && Q->ne[1] <= 2 && -+ (ggml_is_quantized(K->type) || ggml_is_quantized(V->type)) && + K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && + ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr) { + return BEST_FATTN_KERNEL_VEC; From 0c4a0ca0ea5821f920c6c4a097b5c8dce54b5fa1 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 19:37:24 +1100 Subject: [PATCH 14/81] feat(bench): add reusable fixed-work AgentX comparison campaigns --- just/skippy.just | 10 + skippy/evals/agentx/README.md | 121 + skippy/evals/agentx/pyproject.toml | 11 + skippy/evals/agentx/tools.example.json | 19 + skippy/evals/agentx/uv.lock | 2186 +++++++++++++++++ .../src/automation/agentx/agentic_config.rs | 56 + .../src/automation/agentx/cache_decisions.rs | 411 ++++ tools/xtask/src/automation/agentx/campaign.rs | 234 ++ tools/xtask/src/automation/agentx/capacity.rs | 217 ++ tools/xtask/src/automation/agentx/command.rs | 88 + .../automation/agentx/comparison_cohort.rs | 208 ++ .../src/automation/agentx/completed_work.rs | 141 ++ .../xtask/src/automation/agentx/container.rs | 425 ++++ .../automation/agentx/contention_cohort.rs | 269 ++ .../src/automation/agentx/context_support.rs | 125 + .../src/automation/agentx/final_sweep.rs | 219 ++ .../automation/agentx/final_sweep_tests.rs | 122 + tools/xtask/src/automation/agentx/hardware.rs | 205 ++ tools/xtask/src/automation/agentx/inputs.rs | 255 ++ .../xtask/src/automation/agentx/lifecycle.rs | 865 +++++++ tools/xtask/src/automation/agentx/memory.rs | 264 ++ .../src/automation/agentx/memory/macos.rs | 56 + .../src/automation/agentx/mlflow_export.rs | 308 +++ .../src/automation/agentx/mlflow_publish.rs | 294 +++ tools/xtask/src/automation/agentx/mod.rs | 221 ++ .../src/automation/agentx/native_kv_span.rs | 170 ++ tools/xtask/src/automation/agentx/overlap.rs | 105 + .../src/automation/agentx/phase_outcome.rs | 114 + .../src/automation/agentx/prepared_launch.rs | 142 ++ .../src/automation/agentx/prepared_tools.rs | 230 ++ tools/xtask/src/automation/agentx/results.rs | 249 ++ .../automation/agentx/scheduler_profile.rs | 228 ++ .../src/automation/agentx/trace_context.rs | 168 ++ tools/xtask/src/automation/agentx/workload.rs | 265 ++ tools/xtask/src/automation/mod.rs | 1 + tools/xtask/src/cli.rs | 4 + tools/xtask/src/main.rs | 1 + .../agentx/complete-trace-records.jsonl | 16 + .../tests/fixtures/agentx/http-overlap.jsonl | 7 + .../tests/fixtures/agentx/smoke-metrics.json | 139 ++ 40 files changed, 9169 insertions(+) create mode 100644 skippy/evals/agentx/README.md create mode 100644 skippy/evals/agentx/pyproject.toml create mode 100644 skippy/evals/agentx/tools.example.json create mode 100644 skippy/evals/agentx/uv.lock create mode 100644 tools/xtask/src/automation/agentx/agentic_config.rs create mode 100644 tools/xtask/src/automation/agentx/cache_decisions.rs create mode 100644 tools/xtask/src/automation/agentx/campaign.rs create mode 100644 tools/xtask/src/automation/agentx/capacity.rs create mode 100644 tools/xtask/src/automation/agentx/command.rs create mode 100644 tools/xtask/src/automation/agentx/comparison_cohort.rs create mode 100644 tools/xtask/src/automation/agentx/completed_work.rs create mode 100644 tools/xtask/src/automation/agentx/container.rs create mode 100644 tools/xtask/src/automation/agentx/contention_cohort.rs create mode 100644 tools/xtask/src/automation/agentx/context_support.rs create mode 100644 tools/xtask/src/automation/agentx/final_sweep.rs create mode 100644 tools/xtask/src/automation/agentx/final_sweep_tests.rs create mode 100644 tools/xtask/src/automation/agentx/hardware.rs create mode 100644 tools/xtask/src/automation/agentx/inputs.rs create mode 100644 tools/xtask/src/automation/agentx/lifecycle.rs create mode 100644 tools/xtask/src/automation/agentx/memory.rs create mode 100644 tools/xtask/src/automation/agentx/memory/macos.rs create mode 100644 tools/xtask/src/automation/agentx/mlflow_export.rs create mode 100644 tools/xtask/src/automation/agentx/mlflow_publish.rs create mode 100644 tools/xtask/src/automation/agentx/mod.rs create mode 100644 tools/xtask/src/automation/agentx/native_kv_span.rs create mode 100644 tools/xtask/src/automation/agentx/overlap.rs create mode 100644 tools/xtask/src/automation/agentx/phase_outcome.rs create mode 100644 tools/xtask/src/automation/agentx/prepared_launch.rs create mode 100644 tools/xtask/src/automation/agentx/prepared_tools.rs create mode 100644 tools/xtask/src/automation/agentx/results.rs create mode 100644 tools/xtask/src/automation/agentx/scheduler_profile.rs create mode 100644 tools/xtask/src/automation/agentx/trace_context.rs create mode 100644 tools/xtask/src/automation/agentx/workload.rs create mode 100644 tools/xtask/tests/fixtures/agentx/complete-trace-records.jsonl create mode 100644 tools/xtask/tests/fixtures/agentx/http-overlap.jsonl create mode 100644 tools/xtask/tests/fixtures/agentx/smoke-metrics.json diff --git a/just/skippy.just b/just/skippy.just index 075d327839..c88bd90e94 100644 --- a/just/skippy.just +++ b/just/skippy.just @@ -8,6 +8,16 @@ skippy-kv-validate input output: skippy-kv-jy-plan input output: @just automation-run automation kv-validation jy-plan --input "{{ input }}" --output "{{ output }}" +# Install only the locked upstream client environment; final workers stay offline. +agentx-setup: + uv sync --locked --managed-python --python 3.12 --project skippy/evals/agentx + +agentx-comparison input output: + @just automation-run automation agentx comparison --input "{{ input }}" --output "{{ output }}" + +agentx-mlflow-export input output: + @just automation-run automation agentx mlflow-export --input "{{ input }}" --output "{{ output }}" + # Build the complete standalone Skippy product for local iteration. [unix] skippy backend="" cuda_arch="" rocm_arch="": diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md new file mode 100644 index 0000000000..6b4aef0eb2 --- /dev/null +++ b/skippy/evals/agentx/README.md @@ -0,0 +1,121 @@ +# Fixed complete AgentX comparison + +Benchmark-only extraction from PR #2463 source `9684f77ffd95d049eefd375366f31df66efbb56b`. +It runs the locked **external** AgentX1.0.12.post2 client; no Python implementation +or old serving/native fix is transplanted. The four exact Q4_K_M models are +owned by [the KV catalog](../kv-validation/models.json), SHA256 +`6a2b724cf32208186d80ac614e21a168bfc08ca72e55afdabc3dc39b338c9206`. + +Each model/backend campaign runs six full c1/c2/c4 sweeps in llama, Skippy, +Skippy, llama, llama, Skippy order. Each cell serves the same four intact traces: +69 requests and18,713 requested outputs, original children, think times and +turn/output identities. Missing/repeated/shortened/cancelled/error work or a +changed cohort/numerator fails. Token-count hashes prove work, not token parity. +Run the existing native and `skippy-kv-validate` correctness gates first and +retain their identities alongside the campaign. No throughput parity is implied +by successful work accounting. + +## Prepared inputs + +Build the product/runtime and independent **unpatched** standard llama-server +once per backend through their owning Just/producer workflow. Baseline source +must equal `skippy/llama_cpp/upstream.txt`. Reuse immutable prepared tools; no +campaign builds or downloads. If preparing the external client, `just +agentx-setup` installs the locked upstream environment; workers consume it +offline. Site packages/interpreter file bytes are pinned, as are the executable, +runtime, tokenizer snapshot and corpus. External directory links/editable +environments are refused; internal aliases such as `lib64 -> lib` are pinned +without traversal, and regular-file interpreter links are hashed by content. + +Create `/abs/request.paths.json` with: + +```json +{ + "schema_version": 1, + "campaign": "agentx-final-YYYYMMDD", + "workspace": "/opt/mesh-llm", + "model_key": "qwen3.5-4b-q4-k-m", + "model": "/models/Qwen3.5-4B-Q4_K_M.gguf", + "corpus": {"path": "/models/traces.jsonl", "sha256": ""}, + "tools": "REPLACE_WITH_OBJECT_FROM_tools.example.json" +} +``` + +Replace `tools` with the object in [tools.example.json](tools.example.json), +actual absolute producer paths and declared product/native source IDs. Those +IDs are provenance; pins observe the actual bytes consumed. `pin` checks the +runtime leaf/backend/ABI/native identity and the exact locked client/catalog/ +corpus. It cannot prove a binary was built from an arbitrarily declared commit. + +```sh +just automation-run automation agentx pin --input /abs/request.paths.json --output /abs/request.pinned.json +just agentx-comparison /abs/request.pinned.json /abs/new-campaign +``` + +The corpus is `semianalysisai/cc-traces-weka-062126-256k` revision +`8fecd2fc56694469f758f0afbbb6335ad3043740`, `traces.jsonl` SHA256 +`e39cd2ff3eba21d4a3664be51da743ac3d2149a1933898cafc7bfeac8147eeef`. +Weights and independent tokenizer revisions must already be cached. A fresh +output is required. Artifacts include per-cell launch/effective config, native +capacity observations, raw client records/HTTP traces, lifecycle/memory/work +receipts, scalar summaries, final result and a sibling archive+SHA receipt. +Failure retains partial evidence and returns nonzero. Clean process-tree +shutdown is required; no partial campaign becomes a successful point. + +## Capacity and backend policy + +Skippy preserves its product-auto generation-lane plan independently of offered +c1/c2/c4. It retains the128K per-request cap and records resolved lanes/context/ +configured pool separately from observed native allocation. It explicitly uses +checkpoint RAM8GiB, disk off, F16 K/V, FA, batch2048/microbatch512, no speculation, +and matched thread counts. Frontend prefill is explicitly fixed at64 and +validated in the effective config; it is not inferred from microbatch size. An explicit +`diagnostic_generation_lanes` is separately labelled and cannot quietly change +the default policy. + +Standard vanilla explicitly uses separate KV slots, parallel=C, +context=C×131072, F16 FA, batch2048/ubatch512 and cache RAM8192MiB. Each baseline +must report the expected slots/context. Unified-llama is not substituted. + +Use `backend` cuda/metal with matching prepared bundles/hosts. CPU requires +`diagnostic_cpu:true`; its report is explicitly ineligible for GPU performance +publication. Independent model campaigns can occupy equivalent idle machines; +keep each paired campaign on one host. The actual hostname guard refuses +spark-db08/spark-9f06 (also spark-000280/spark-000499). The admitted external JY +wrapper must also exclude those node IDs and enforce its lease; this command +does not invent a macOS Docker executor or change registered templates. + +## Existing MLflow experiment + +After auditing the complete campaign, make `/abs/export.json`: + +```json +{ + "report": {"path": "/abs/new-campaign/result.json", "sha256": "ACTUAL_REPORT_SHA256"}, + "archive": {"path": "/abs/new-campaign.tar.gz", "sha256": "ACTUAL_ARCHIVE_SHA256"} +} +``` + +```sh +just agentx-mlflow-export /abs/export.json /abs/new-plan.json +just automation-run automation agentx mlflow-publish --input /abs/new-plan.json --output /abs/new-publication +``` + +Export does not write MLflow. Explicit publication uses existing operator +`MLFLOW_TRACKING_URI`, `MLFLOW_TRACKING_USERNAME`, `MLFLOW_TRACKING_PASSWORD` +through a private temporary curl config, never job payloads or source. It first +GETs existing experiment6 and requires exact name `agentx-skippy-vs-llama` and +active state. There is no experiment-create call. A new idempotent campaign +root contains model/backend groups and their six arm children through +`mlflow.parentRunId`. The common campaign root remains RUNNING until a separate +eight-group audit; each publication finishes only its model/backend group. Historical source-pinned +runs and ablation parents remain separate. Identity conflicts fail. Per-arm +c1/c2/c4 scalar values, source/native/queue/runtime/tool/corpus/cohort/work +identities and archive hashes are recorded; `cache_read_tokens_avg` is an average, +not a total. Then +metrics are read back, artifacts uploaded/downloaded with matching SHA, then +publication receipt is written. A publishing failure is nonzero and retains +API evidence for retry. Publication is not a numerical-correctness certificate. + +The ordinary CI/GPU suite and registered JY templates are unchanged. This +benchmark owner does not mark the long-prefix/cancellation/L3 TODO complete. diff --git a/skippy/evals/agentx/pyproject.toml b/skippy/evals/agentx/pyproject.toml new file mode 100644 index 0000000000..2edbee2eea --- /dev/null +++ b/skippy/evals/agentx/pyproject.toml @@ -0,0 +1,11 @@ +[project] +name = "skippy-agentx-environment" +version = "0.1.0" +requires-python = ">=3.12,<3.13" +dependencies = ["agentx-harness==1.0.12.post2"] + +[tool.uv.sources] +# AgentX 1.0.12 plus late-return drain fixes and paired cache-bust namespaces +# at 6633517b9d3d83441dc110613c80e70458f3d75d. +# Built with upstream's release builder; uv.lock verifies the wheel SHA-256. +agentx-harness = { url = "https://github.com/Mesh-LLM/agentx-harness/releases/download/agentx-v1.0.12.post2/agentx_harness-1.0.12.post2-py3-none-any.whl" } diff --git a/skippy/evals/agentx/tools.example.json b/skippy/evals/agentx/tools.example.json new file mode 100644 index 0000000000..6efae5c4a6 --- /dev/null +++ b/skippy/evals/agentx/tools.example.json @@ -0,0 +1,19 @@ +{ + "backend": "cuda", + "product_source_commit": "0000000000000000000000000000000000000000", + "native_source_commit": "0000000000000000000000000000000000000000", + "native_patch_digest": "COPY_ACTUAL_MANIFEST_BUILD_LLAMA_PATCH_DIGEST", + "runtime": {"path": "/opt/kv-runtime", "sha256": ""}, + "skippy": {"path": "/opt/kv-tools/skippy", "sha256": ""}, + "llama": {"path": "/opt/standard/bin/llama-server", "sha256": ""}, + "standard_runtime": {"path": "/opt/standard/bin", "sha256": ""}, + "standard_upstream": "620d2225cc436ab0b001e3200e590e3b286ef9ab", + "client": {"path": "/opt/agentx-env/bin/agentx", "sha256": ""}, + "client_environment": {"path": "/opt/agentx-env", "sha256": ""}, + "client_lock": {"path": "/opt/mesh-llm/skippy/evals/agentx/uv.lock", "sha256": ""}, + "tokenizer": {"path": "/models/tokenizer-snapshot", "sha256": ""}, + "threads": 20, + "diagnostic_generation_lanes": null, + "diagnostic_cpu": false, + "cell_seconds": 10200 +} diff --git a/skippy/evals/agentx/uv.lock b/skippy/evals/agentx/uv.lock new file mode 100644 index 0000000000..4eba801460 --- /dev/null +++ b/skippy/evals/agentx/uv.lock @@ -0,0 +1,2186 @@ +version = 1 +revision = 5 +requires-python = "==3.12.*" + +[[package]] +name = "agentx-harness" +version = "1.0.12.post2" +source = { url = "https://github.com/Mesh-LLM/agentx-harness/releases/download/agentx-v1.0.12.post2/agentx_harness-1.0.12.post2-py3-none-any.whl" } +dependencies = [ + { name = "aiofiles" }, + { name = "aiohttp" }, + { name = "crick" }, + { name = "cyclopts" }, + { name = "dash" }, + { name = "dash-bootstrap-components" }, + { name = "datasets", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" }, + { name = "fastapi" }, + { name = "ffmpeg-python" }, + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "jinja2" }, + { name = "jmespath" }, + { name = "kaleido" }, + { name = "matplotlib" }, + { name = "msgspec" }, + { name = "numpy" }, + { name = "nvidia-ml-py" }, + { name = "optuna" }, + { name = "orjson" }, + { name = "pandas" }, + { name = "pillow" }, + { name = "plotly" }, + { name = "prometheus-client" }, + { name = "protobuf" }, + { name = "psutil" }, + { name = "pyarrow", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "pyzmq" }, + { name = "rich" }, + { name = "ruamel-yaml" }, + { name = "scipy" }, + { name = "seaborn" }, + { name = "sentencepiece" }, + { name = "setproctitle" }, + { name = "soundfile" }, + { name = "starlette-compress" }, + { name = "textual" }, + { name = "tiktoken" }, + { name = "tqdm" }, + { name = "transformers" }, + { name = "uvicorn", extra = ["standard"] }, + { name = "uvloop", marker = "sys_platform != 'win32'" }, + { name = "zstandard" }, +] +wheels = [ + { url = "https://github.com/Mesh-LLM/agentx-harness/releases/download/agentx-v1.0.12.post2/agentx_harness-1.0.12.post2-py3-none-any.whl", hash = "sha256:0f9a9e85ec7f9273bfc96de00a492daf9898acfb66cfeeb6aba85a07c89e8a2f" }, +] + +[package.metadata] +requires-dist = [ + { name = "aiofiles", specifier = "~=24.1.0" }, + { name = "aiohttp", specifier = "~=3.13.3" }, + { name = "black", marker = "extra == 'dev'", specifier = ">=25.1.0" }, + { name = "botorch", marker = "extra == 'botorch'", specifier = ">=0.10" }, + { name = "botorch", marker = "extra == 'optuna'", specifier = ">=0.10" }, + { name = "crick", specifier = "~=0.0.8" }, + { name = "cyclopts", specifier = ">=4,<5" }, + { name = "dash", specifier = "~=3.1.0" }, + { name = "dash-bootstrap-components", specifier = "~=2.0.0" }, + { name = "datasets", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'", specifier = ">=3.0,>=4.7.0" }, + { name = "deepeval", marker = "extra == 'accuracy'", specifier = ">=2.9.0,<5.0.0" }, + { name = "fastapi", specifier = ">=0.115,<1" }, + { name = "ffmpeg-python", specifier = "~=0.2.0" }, + { name = "filelock", specifier = ">=3.13" }, + { name = "gpytorch", marker = "extra == 'botorch'", specifier = ">=1.11" }, + { name = "gpytorch", marker = "extra == 'optuna'", specifier = ">=1.11" }, + { name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27.0" }, + { name = "httpx", marker = "extra == 'test'", specifier = ">=0.27.0" }, + { name = "huggingface-hub", specifier = ">=0.34.0,<2.0" }, + { name = "hypothesis", marker = "platform_machine == 'ARM64' and sys_platform == 'win32' and extra == 'dev'", specifier = ">=6.0.0,<6.156" }, + { name = "hypothesis", marker = "platform_machine == 'ARM64' and sys_platform == 'win32' and extra == 'test'", specifier = ">=6.0.0,<6.156" }, + { name = "hypothesis", marker = "(platform_machine != 'ARM64' and extra == 'dev') or (sys_platform != 'win32' and extra == 'dev')", specifier = ">=6.0.0" }, + { name = "hypothesis", marker = "(platform_machine != 'ARM64' and extra == 'test') or (sys_platform != 'win32' and extra == 'test')", specifier = ">=6.0.0" }, + { name = "jinja2", specifier = "~=3.1.5" }, + { name = "jmespath", specifier = "~=1.0.1" }, + { name = "jsonschema", marker = "extra == 'dev'", specifier = ">=4.0.0" }, + { name = "jsonschema", marker = "extra == 'test'", specifier = ">=4.0.0" }, + { name = "kaleido", specifier = "~=1.2.0" }, + { name = "latex2sympy2-extended", marker = "extra == 'accuracy'", specifier = ">=1.0.6" }, + { name = "lighteval", marker = "extra == 'accuracy'", specifier = ">=0.13.0" }, + { name = "looptime", marker = "extra == 'dev'", specifier = ">=0.5" }, + { name = "looptime", marker = "extra == 'test'", specifier = ">=0.5" }, + { name = "matplotlib", specifier = ">=3.10.0" }, + { name = "mlflow", marker = "extra == 'dev'", specifier = ">=3.10.0,<4.0.0" }, + { name = "mlflow", marker = "extra == 'mlflow'", specifier = ">=3.10.0,<4.0.0" }, + { name = "msgspec", specifier = ">=0.19.0,<1.0.0" }, + { name = "numpy", specifier = ">=1.26.4,<3" }, + { name = "nvidia-ml-py" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'dev'", specifier = ">=1.24.0,<2.0.0" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otel'", specifier = ">=1.24.0,<2.0.0" }, + { name = "opentelemetry-sdk", marker = "extra == 'dev'", specifier = ">=1.24.0,<2.0.0" }, + { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.24.0,<2.0.0" }, + { name = "optuna", specifier = ">=3.6" }, + { name = "optuna-integration", marker = "extra == 'botorch'", specifier = ">=3.6" }, + { name = "optuna-integration", marker = "extra == 'optuna'", specifier = ">=3.6" }, + { name = "orjson", specifier = "~=3.11.7" }, + { name = "pandas", specifier = "~=2.3.3" }, + { name = "pillow", specifier = "~=12.2.0" }, + { name = "plotly", specifier = "~=6.4.0" }, + { name = "pre-commit", marker = "extra == 'dev'", specifier = ">=4.2.0" }, + { name = "prometheus-client", specifier = "~=0.23.1" }, + { name = "protobuf", specifier = ">=4" }, + { name = "psutil", specifier = "~=7.0.0" }, + { name = "pyarrow", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'", specifier = ">=18.0.0" }, + { name = "pydantic", specifier = ">=2.10.0,<3.0.0" }, + { name = "pydantic-settings", specifier = ">=2.10.0,<3.0.0" }, + { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0.0" }, + { name = "pytest", marker = "extra == 'test'", specifier = ">=7.0.0" }, + { name = "pytest-asyncio", marker = "extra == 'dev'" }, + { name = "pytest-asyncio", marker = "extra == 'test'" }, + { name = "pytest-cov", marker = "extra == 'dev'" }, + { name = "pytest-cov", marker = "extra == 'test'" }, + { name = "pytest-rerunfailures", marker = "extra == 'dev'", specifier = ">=15.0" }, + { name = "pytest-rerunfailures", marker = "extra == 'test'", specifier = ">=15.0" }, + { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.0.0" }, + { name = "pytest-timeout", marker = "extra == 'test'", specifier = ">=2.0.0" }, + { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.8.0" }, + { name = "pytest-xdist", marker = "extra == 'test'", specifier = ">=3.8.0" }, + { name = "pyzmq", specifier = "~=26.4.0" }, + { name = "rich", specifier = "~=14.1.0" }, + { name = "ruamel-yaml", specifier = "~=0.18.12" }, + { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.14.0,<0.15.0" }, + { name = "scipy", specifier = ">=1.13.0" }, + { name = "seaborn", specifier = "~=0.13.2" }, + { name = "sentencepiece", specifier = ">=0.2.0" }, + { name = "setproctitle", specifier = "~=1.3.6" }, + { name = "soundfile", specifier = "~=0.13.1" }, + { name = "starlette-compress", specifier = ">=1.0.1" }, + { name = "sympy", marker = "extra == 'accuracy'", specifier = ">=1.14.0" }, + { name = "textual", specifier = "~=5.3.0" }, + { name = "tiktoken", specifier = ">=0.7.0,<1" }, + { name = "torch", marker = "extra == 'botorch'", specifier = ">=2.0" }, + { name = "torch", marker = "extra == 'optuna'", specifier = ">=2.0" }, + { name = "tqdm", specifier = ">=4.67.1" }, + { name = "transformers", specifier = ">=4.56.0" }, + { name = "trustme", marker = "(platform_machine != 'ARM64' and extra == 'dev') or (sys_platform != 'win32' and extra == 'dev')", specifier = ">=1.0.0" }, + { name = "trustme", marker = "(platform_machine != 'ARM64' and extra == 'test') or (sys_platform != 'win32' and extra == 'test')", specifier = ">=1.0.0" }, + { name = "uvicorn", extras = ["standard"], specifier = ">=0.34,<1" }, + { name = "uvloop", marker = "sys_platform != 'win32'", specifier = ">=0.22.1" }, + { name = "wandb", marker = "extra == 'dev'", specifier = ">=0.19.0,<1.0.0" }, + { name = "wandb", marker = "extra == 'wandb'", specifier = ">=0.19.0,<1.0.0" }, + { name = "zstandard", specifier = ">=0.25.0" }, +] +provides-extras = ["accuracy", "botorch", "dev", "mlflow", "optuna", "otel", "test", "wandb"] + +[[package]] +name = "aiofiles" +version = "24.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/03/a88171e277e8caa88a4c77808c20ebb04ba74cc4681bf1e9416c862de237/aiofiles-24.1.0.tar.gz", hash = "sha256:22a075c9e5a3810f0c2e48f3008c94d68c65d763b9b03857924c99e57355166c", size = 30247, upload-time = "2024-06-24T11:02:03.584Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/45/30bb92d442636f570cb5651bc661f52b610e2eec3f891a5dc3a4c3667db0/aiofiles-24.1.0-py3-none-any.whl", hash = "sha256:b4ec55f4195e3eb5d7abd1bf7e061763e864dd4954231fb8539a0ef8bb8260e5", size = 15896, upload-time = "2024-06-24T11:02:01.529Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.13.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/77/9a/152096d4808df8e4268befa55fba462f440f14beab85e8ad9bf990516918/aiohttp-3.13.5.tar.gz", hash = "sha256:9d98cc980ecc96be6eb4c1994ce35d28d8b1f5e5208a23b421187d1209dbb7d1", size = 7858271, upload-time = "2026-03-31T22:01:03.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/6f/353954c29e7dcce7cf00280a02c75f30e133c00793c7a2ed3776d7b2f426/aiohttp-3.13.5-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:023ecba036ddd840b0b19bf195bfae970083fd7024ce1ac22e9bba90464620e9", size = 748876, upload-time = "2026-03-31T21:57:36.319Z" }, + { url = "https://files.pythonhosted.org/packages/f5/1b/428a7c64687b3b2e9cd293186695affc0e1e54a445d0361743b231f11066/aiohttp-3.13.5-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:15c933ad7920b7d9a20de151efcd05a6e38302cbf0e10c9b2acb9a42210a2416", size = 499557, upload-time = "2026-03-31T21:57:38.236Z" }, + { url = "https://files.pythonhosted.org/packages/29/47/7be41556bfbb6917069d6a6634bb7dd5e163ba445b783a90d40f5ac7e3a7/aiohttp-3.13.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ab2899f9fa2f9f741896ebb6fa07c4c883bfa5c7f2ddd8cf2aafa86fa981b2d2", size = 500258, upload-time = "2026-03-31T21:57:39.923Z" }, + { url = "https://files.pythonhosted.org/packages/67/84/c9ecc5828cb0b3695856c07c0a6817a99d51e2473400f705275a2b3d9239/aiohttp-3.13.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a60eaa2d440cd4707696b52e40ed3e2b0f73f65be07fd0ef23b6b539c9c0b0b4", size = 1749199, upload-time = "2026-03-31T21:57:41.938Z" }, + { url = "https://files.pythonhosted.org/packages/f0/d3/3c6d610e66b495657622edb6ae7c7fd31b2e9086b4ec50b47897ad6042a9/aiohttp-3.13.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:55b3bdd3292283295774ab585160c4004f4f2f203946997f49aac032c84649e9", size = 1721013, upload-time = "2026-03-31T21:57:43.904Z" }, + { url = "https://files.pythonhosted.org/packages/49/a0/24409c12217456df0bae7babe3b014e460b0b38a8e60753d6cb339f6556d/aiohttp-3.13.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c2b2355dc094e5f7d45a7bb262fe7207aa0460b37a0d87027dcf21b5d890e7d5", size = 1781501, upload-time = "2026-03-31T21:57:46.285Z" }, + { url = "https://files.pythonhosted.org/packages/98/9d/b65ec649adc5bccc008b0957a9a9c691070aeac4e41cea18559fef49958b/aiohttp-3.13.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b38765950832f7d728297689ad78f5f2cf79ff82487131c4d26fe6ceecdc5f8e", size = 1878981, upload-time = "2026-03-31T21:57:48.734Z" }, + { url = "https://files.pythonhosted.org/packages/57/d8/8d44036d7eb7b6a8ec4c5494ea0c8c8b94fbc0ed3991c1a7adf230df03bf/aiohttp-3.13.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b18f31b80d5a33661e08c89e202edabf1986e9b49c42b4504371daeaa11b47c1", size = 1767934, upload-time = "2026-03-31T21:57:51.171Z" }, + { url = "https://files.pythonhosted.org/packages/31/04/d3f8211f273356f158e3464e9e45484d3fb8c4ce5eb2f6fe9405c3273983/aiohttp-3.13.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:33add2463dde55c4f2d9635c6ab33ce154e5ecf322bd26d09af95c5f81cfa286", size = 1566671, upload-time = "2026-03-31T21:57:53.326Z" }, + { url = "https://files.pythonhosted.org/packages/41/db/073e4ebe00b78e2dfcacff734291651729a62953b48933d765dc513bf798/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:327cc432fdf1356fb4fbc6fe833ad4e9f6aacb71a8acaa5f1855e4b25910e4a9", size = 1705219, upload-time = "2026-03-31T21:57:55.385Z" }, + { url = "https://files.pythonhosted.org/packages/48/45/7dfba71a2f9fd97b15c95c06819de7eb38113d2cdb6319669195a7d64270/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7c35b0bf0b48a70b4cb4fc5d7bed9b932532728e124874355de1a0af8ec4bc88", size = 1743049, upload-time = "2026-03-31T21:57:57.341Z" }, + { url = "https://files.pythonhosted.org/packages/18/71/901db0061e0f717d226386a7f471bb59b19566f2cae5f0d93874b017271f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:df23d57718f24badef8656c49743e11a89fd6f5358fa8a7b96e728fda2abf7d3", size = 1749557, upload-time = "2026-03-31T21:57:59.626Z" }, + { url = "https://files.pythonhosted.org/packages/08/d5/41eebd16066e59cd43728fe74bce953d7402f2b4ddfdfef2c0e9f17ca274/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:02e048037a6501a5ec1f6fc9736135aec6eb8a004ce48838cb951c515f32c80b", size = 1558931, upload-time = "2026-03-31T21:58:01.972Z" }, + { url = "https://files.pythonhosted.org/packages/30/e6/4a799798bf05740e66c3a1161079bda7a3dd8e22ca392481d7a7f9af82a6/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31cebae8b26f8a615d2b546fee45d5ffb76852ae6450e2a03f42c9102260d6fe", size = 1774125, upload-time = "2026-03-31T21:58:04.007Z" }, + { url = "https://files.pythonhosted.org/packages/84/63/7749337c90f92bc2cb18f9560d67aa6258c7060d1397d21529b8004fcf6f/aiohttp-3.13.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:888e78eb5ca55a615d285c3c09a7a91b42e9dd6fc699b166ebd5dee87c9ccf14", size = 1732427, upload-time = "2026-03-31T21:58:06.337Z" }, + { url = "https://files.pythonhosted.org/packages/98/de/cf2f44ff98d307e72fb97d5f5bbae3bfcb442f0ea9790c0bf5c5c2331404/aiohttp-3.13.5-cp312-cp312-win32.whl", hash = "sha256:8bd3ec6376e68a41f9f95f5ed170e2fcf22d4eb27a1f8cb361d0508f6e0557f3", size = 433534, upload-time = "2026-03-31T21:58:08.712Z" }, + { url = "https://files.pythonhosted.org/packages/aa/ca/eadf6f9c8fa5e31d40993e3db153fb5ed0b11008ad5d9de98a95045bed84/aiohttp-3.13.5-cp312-cp312-win_amd64.whl", hash = "sha256:110e448e02c729bcebb18c60b9214a87ba33bac4a9fa5e9a5f139938b56c6cb1", size = 460446, upload-time = "2026-03-31T21:58:10.945Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "alembic" +version = "1.20.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mako" }, + { name = "sqlalchemy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ed/aa/02910bdb8e2f1444f6654d5b296cd827d126f82209050ee7b1000f92ac4b/alembic-1.20.0.tar.gz", hash = "sha256:db505480647bc60386c5369402f4a57a506b7539c9e9ef5e270d45cbbe4939bf", size = 2093272, upload-time = "2026-09-11T19:09:11.126Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/27/78a89b55b0904d222183164e079b4ca56208e94eff1d35ad1f1ad5be9b06/alembic-1.20.0-py3-none-any.whl", hash = "sha256:77eb101048d95f982c0353e9233404889dcd7a6fc244c107836c0e2fc9cf7d9d", size = 268719, upload-time = "2026-09-11T19:09:12.88Z" }, +] + +[[package]] +name = "annotated-doc" +version = "0.0.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758, upload-time = "2026-07-28T13:50:58.129Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "anyio" +version = "4.15.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + +[[package]] +name = "brotli" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f7/16/c92ca344d646e71a43b8bb353f0a6490d7f6e06210f8554c8f874e454285/brotli-1.2.0.tar.gz", hash = "sha256:e310f77e41941c13340a95976fe66a8a95b01e783d430eeaf7a2f87e0a57dd0a", size = 7388632, upload-time = "2025-11-05T18:39:42.86Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/ee/b0a11ab2315c69bb9b45a2aaed022499c9c24a205c3a49c3513b541a7967/brotli-1.2.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:35d382625778834a7f3061b15423919aa03e4f5da34ac8e02c074e4b75ab4f84", size = 861543, upload-time = "2025-11-05T18:38:24.183Z" }, + { url = "https://files.pythonhosted.org/packages/e1/2f/29c1459513cd35828e25531ebfcbf3e92a5e49f560b1777a9af7203eb46e/brotli-1.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7a61c06b334bd99bc5ae84f1eeb36bfe01400264b3c352f968c6e30a10f9d08b", size = 444288, upload-time = "2025-11-05T18:38:25.139Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6f/feba03130d5fceadfa3a1bb102cb14650798c848b1df2a808356f939bb16/brotli-1.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acec55bb7c90f1dfc476126f9711a8e81c9af7fb617409a9ee2953115343f08d", size = 1528071, upload-time = "2025-11-05T18:38:26.081Z" }, + { url = "https://files.pythonhosted.org/packages/2b/38/f3abb554eee089bd15471057ba85f47e53a44a462cfce265d9bf7088eb09/brotli-1.2.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:260d3692396e1895c5034f204f0db022c056f9e2ac841593a4cf9426e2a3faca", size = 1626913, upload-time = "2025-11-05T18:38:27.284Z" }, + { url = "https://files.pythonhosted.org/packages/03/a7/03aa61fbc3c5cbf99b44d158665f9b0dd3d8059be16c460208d9e385c837/brotli-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:072e7624b1fc4d601036ab3f4f27942ef772887e876beff0301d261210bca97f", size = 1419762, upload-time = "2025-11-05T18:38:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/21/1b/0374a89ee27d152a5069c356c96b93afd1b94eae83f1e004b57eb6ce2f10/brotli-1.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:adedc4a67e15327dfdd04884873c6d5a01d3e3b6f61406f99b1ed4865a2f6d28", size = 1484494, upload-time = "2025-11-05T18:38:29.29Z" }, + { url = "https://files.pythonhosted.org/packages/cf/57/69d4fe84a67aef4f524dcd075c6eee868d7850e85bf01d778a857d8dbe0a/brotli-1.2.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7a47ce5c2288702e09dc22a44d0ee6152f2c7eda97b3c8482d826a1f3cfc7da7", size = 1593302, upload-time = "2025-11-05T18:38:30.639Z" }, + { url = "https://files.pythonhosted.org/packages/d5/3b/39e13ce78a8e9a621c5df3aeb5fd181fcc8caba8c48a194cd629771f6828/brotli-1.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:af43b8711a8264bb4e7d6d9a6d004c3a2019c04c01127a868709ec29962b6036", size = 1487913, upload-time = "2025-11-05T18:38:31.618Z" }, + { url = "https://files.pythonhosted.org/packages/62/28/4d00cb9bd76a6357a66fcd54b4b6d70288385584063f4b07884c1e7286ac/brotli-1.2.0-cp312-cp312-win32.whl", hash = "sha256:e99befa0b48f3cd293dafeacdd0d191804d105d279e0b387a32054c1180f3161", size = 334362, upload-time = "2025-11-05T18:38:32.939Z" }, + { url = "https://files.pythonhosted.org/packages/1c/4e/bc1dcac9498859d5e353c9b153627a3752868a9d5f05ce8dedd81a2354ab/brotli-1.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:b35c13ce241abdd44cb8ca70683f20c0c079728a36a996297adb5334adfc1c44", size = 369115, upload-time = "2025-11-05T18:38:33.765Z" }, +] + +[[package]] +name = "brotlicffi" +version = "1.2.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/71/97/7845739a36828ffe751a1c6b240692f552fd7ecf65026c51326c0a4aa369/brotlicffi-1.2.0.2.tar.gz", hash = "sha256:5e0fbd13644cf1f6015e75fa5e0ad8fdce1048d9c9ff90b0ce826174b249ee35", size = 478755, upload-time = "2026-08-21T17:29:18.415Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/71/c27f24b8334f65f2492601c7764338f156cb904d2ffe0061e6004a76d9cc/brotlicffi-1.2.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:d5a8ffa154f16660ab818d78045b55fa6f9970f1ca4c38998766e99c672071cb", size = 438885, upload-time = "2026-08-21T17:29:04.113Z" }, + { url = "https://files.pythonhosted.org/packages/ef/22/d8fd1a4d09b7ab563b89380395e09151d2ef1344be31594df6a6987d4028/brotlicffi-1.2.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ec6b1af7b7a8ce788354f2c603651ada0fba166ec31ab879e2eec462a3e6dbf4", size = 1534365, upload-time = "2026-08-21T17:29:05.878Z" }, + { url = "https://files.pythonhosted.org/packages/06/78/076419ed6c2c6aa3eaac6fd6b076502b4be89d50625fcdc513cd4aeca718/brotlicffi-1.2.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22916101de0e7ff535f2edf54b52a85591853b8ae9a98737643defdd3c063a3a", size = 1536851, upload-time = "2026-08-21T17:29:07.599Z" }, + { url = "https://files.pythonhosted.org/packages/35/dd/31ae9945cbd605339fb51c9a609f7dbb182cd361adeabc1d470142357206/brotlicffi-1.2.0.2-cp39-abi3-win32.whl", hash = "sha256:df1d34c4ad9adbf7f63a6b42f7d0e4dfd259c88141b85145b57abecc1abc3b24", size = 342379, upload-time = "2026-08-21T17:29:09.05Z" }, + { url = "https://files.pythonhosted.org/packages/95/ae/afd54e744df93b51cc29f6a19beccf9998b25743d7177697390de10479d1/brotlicffi-1.2.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:489ca4da3ee65926d72bf01584b61088a9da6bdd1bb01b2040901e1beaffa8f0", size = 379761, upload-time = "2026-08-21T17:29:10.687Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" }, + { url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" }, + { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" }, + { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" }, + { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" }, + { url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" }, + { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" }, + { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" }, + { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" }, + { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "choreographer" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "logistro" }, + { name = "platformdirs" }, + { name = "simplejson" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/21/6b1a021b5fd16696bef7e12093ada05bce6fc3a354d529f67381fc3e83d1/choreographer-1.4.0.tar.gz", hash = "sha256:97ed6d2b44b71271b6cd9fc87816d23bef4fd5eca9855dc24dfa0033ebf08c77", size = 57382, upload-time = "2026-09-16T23:31:23.005Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/24/96b041b800d1de465758106353bedc1e682c5671b3a18142e71e67613996/choreographer-1.4.0-py3-none-any.whl", hash = "sha256:8acba7ce8e912e1193628eea5bbfd76ac3d63328e3195b2527c04675f16780f7", size = 57999, upload-time = "2026-09-16T23:31:21.791Z" }, +] + +[[package]] +name = "click" +version = "8.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "colorlog" +version = "6.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8c/55/ba79756cb90c8d69d599d57785398ac87bba7b19c80e87f4e8a562197c93/colorlog-6.12.0.tar.gz", hash = "sha256:2a7924c1dadf18b22a0eb8b06d1c7b01d5341707ec1641eb6fcc4fde0c3e8e5f", size = 18151, upload-time = "2026-07-23T13:40:40.71Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/19/0b6647bf5e331521e55d2b63bfbdc210bd9cd605189273f03614a05f702d/colorlog-6.12.0-py3-none-any.whl", hash = "sha256:30d392604e9110045a2c2aeefc27d7a017abbab63f3a8aee594eac0801df784e", size = 12239, upload-time = "2026-07-23T13:40:39.562Z" }, +] + +[[package]] +name = "contourpy" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/ba/01bde9753bdbba04a6da9d2bff3881f021bc708f654655e95fae26d3b3a3/contourpy-1.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b", size = 297302, upload-time = "2026-09-11T19:02:45.103Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f5/c5bf67522d49a2222f3154fe46879451d26f0e35ece41770758a64ea78cb/contourpy-1.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8", size = 284921, upload-time = "2026-09-11T19:02:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cc/cb989599eec12fda312e127eb8e04a8b21a7a6c94bf7ff1bc68273334a42/contourpy-1.4.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0", size = 356332, upload-time = "2026-09-11T19:02:51.408Z" }, + { url = "https://files.pythonhosted.org/packages/47/fb/6f620d7602507817b0b4c21dd790ed68688f1f4ae9c29aacf21f08db5cf1/contourpy-1.4.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b", size = 405878, upload-time = "2026-09-11T19:02:54.093Z" }, + { url = "https://files.pythonhosted.org/packages/32/4e/693c6d6bdece679f0953775eef3a1b66d56be55478d936e7deb1f3004422/contourpy-1.4.0-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c", size = 408296, upload-time = "2026-09-11T19:02:56.528Z" }, + { url = "https://files.pythonhosted.org/packages/78/f9/b6831508960d559581c448532ba4df312217072975486dbf2b24fcc5b76f/contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591", size = 383243, upload-time = "2026-09-11T19:02:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/f2/21/52903825a0ae7bb625e8bd30a09816d4c3c5d6174a469c10a616166cf780/contourpy-1.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3", size = 1357306, upload-time = "2026-09-11T19:03:01.036Z" }, + { url = "https://files.pythonhosted.org/packages/d8/79/d68b1ce8539e4071518fed9523f558398f34dcd078b8927b109c72dad2ef/contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f", size = 1427243, upload-time = "2026-09-11T19:03:03.866Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f0/b75a10e9d0616b97a30de277b6dfe83f1879880854c7330337309530eb48/contourpy-1.4.0-cp312-cp312-win32.whl", hash = "sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2", size = 347345, upload-time = "2026-09-11T19:03:06.192Z" }, + { url = "https://files.pythonhosted.org/packages/50/a9/dab08786bb4d77ef9a046b3c1be923be4e73c5d07d91f5a54e8ea9b09e41/contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c", size = 234083, upload-time = "2026-09-11T19:03:08.122Z" }, + { url = "https://files.pythonhosted.org/packages/47/b9/3ba509755a970dbde5948e7142ac21f266be72f38017cc4087a05fdceee1/contourpy-1.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c", size = 559521, upload-time = "2026-09-11T19:03:10.047Z" }, +] + +[[package]] +name = "crick" +version = "0.0.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/d3/8a60c78612fc2d708b94dac7a2dbef4c0de048d64565336a2c0b53c7a872/crick-0.0.8.tar.gz", hash = "sha256:973b8315fdd72bdeb5fdf4d6b2f444753fc0ebd6380f38f8e1138f8ff8797d99", size = 478217, upload-time = "2024-12-23T16:23:16.096Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/b5/6e976250002b5ef1183de0ec996c0deefd6094d1521fc4cd3ebf733a1c21/crick-0.0.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03ccd477b6bdfa17f1a7b6091b22340d845c0da3fa841f222fcacc3cb536f7b0", size = 685403, upload-time = "2024-12-23T16:22:42.578Z" }, + { url = "https://files.pythonhosted.org/packages/98/bd/b23d05b47a8d61cd95a99e72bb3cc121ea5c5749a406f45036c413ff7839/crick-0.0.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3d519d7db779b80a6b34daf30ae3c8d1969c8621c96d8ddf7cc93b8791b0fa2", size = 1809811, upload-time = "2024-12-23T16:22:45.198Z" }, + { url = "https://files.pythonhosted.org/packages/f8/b7/1bad9997eb286c25a70189c7cc8baf5b03f8e23b59ed755fef520ca0ff4a/crick-0.0.8-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac3f5164254dcaeed565a01e9428168634f205e64bc6b36fb215e0118d7adefb", size = 1744173, upload-time = "2024-12-23T16:22:47.897Z" }, + { url = "https://files.pythonhosted.org/packages/7a/34/0b4c102c8e4cd8c45b60e1b8d2637c6a40d39c5bcd68a010af9a49f638cb/crick-0.0.8-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:01bde2f7e4ce536a9608a1223d1706001ef869644d9f51993ef26813df8a757c", size = 1787266, upload-time = "2024-12-23T16:22:49.26Z" }, + { url = "https://files.pythonhosted.org/packages/41/10/ca0d5cc259fb612b8d31138997967e1d95107edfb147f2e9597ce7093ce6/crick-0.0.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:672904bc747d59a7a69682e78859fe56544d307ed79a32c5848905eabb7f85b3", size = 1827607, upload-time = "2024-12-23T16:22:51.896Z" }, + { url = "https://files.pythonhosted.org/packages/ca/d5/37eaabc8f35ff308e7d16a247d712b4aa8941dd18825a1585025659a6e65/crick-0.0.8-cp312-cp312-win32.whl", hash = "sha256:030983579c9789f4c88cdeccbd3333b1d901987bf3e345f6618bd1fd63e85b3d", size = 649917, upload-time = "2024-12-23T16:22:54.923Z" }, + { url = "https://files.pythonhosted.org/packages/ed/87/b2b9e74580b5238054b85e2b632ba2c34c28a3a304370803d1a5f698d51b/crick-0.0.8-cp312-cp312-win_amd64.whl", hash = "sha256:4a133c79a63df906c0095fb3239e3abeeb101cb30e4a027a015d24e7f2a3dc6c", size = 679572, upload-time = "2024-12-23T16:22:58.141Z" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "cyclopts" +version = "4.25.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "docstring-parser" }, + { name = "rich" }, + { name = "rich-rst" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c1/08/a444f3cca86cb27bc256831fc8c42b578390f4087bf6631cccb5334bd9ed/cyclopts-4.25.3.tar.gz", hash = "sha256:7d3a067bc7699a1a65fe2ea0b092a925855bb711a05adc1e65c5b9ba307acea4", size = 202814, upload-time = "2026-09-17T16:25:16.892Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/cc/e879da3d54cf727f90e6d90118e132672c3913338b566740486f8797190d/cyclopts-4.25.3-py3-none-any.whl", hash = "sha256:40e76b3153ea90e885abd8d3a4d8184db5a5eec2fde8540025aae8d72fc973fc", size = 242748, upload-time = "2026-09-17T16:25:15.509Z" }, +] + +[[package]] +name = "dash" +version = "3.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flask" }, + { name = "importlib-metadata" }, + { name = "nest-asyncio" }, + { name = "plotly" }, + { name = "requests" }, + { name = "retrying" }, + { name = "setuptools" }, + { name = "typing-extensions" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/7c/8569c50a4c07fabee6b2428a1515c0c92247e2127367b438a9f99d69723c/dash-3.1.1.tar.gz", hash = "sha256:916b31cec46da0a3339da0e9df9f446126aa7f293c0544e07adf9fe4ba060b18", size = 7544441, upload-time = "2025-06-30T15:31:30.518Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/df/267614cbc1003f6982d7078fd5c7591778f75e07bf36d4771fcb2eab8ff1/dash-3.1.1-py3-none-any.whl", hash = "sha256:66fff37e79c6aa114cd55aea13683d1e9afe0e3f96b35388baca95ff6cfdad23", size = 7885616, upload-time = "2025-06-30T15:31:22.768Z" }, +] + +[[package]] +name = "dash-bootstrap-components" +version = "2.0.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/d4/5b7da808ff5acb3a6ca702f504d8ef05bc7d4c475b18dadefd783b1120c3/dash_bootstrap_components-2.0.4.tar.gz", hash = "sha256:c3206c0923774bbc6a6ddaa7822b8d9aa5326b0d3c1e7cd795cc975025fe2484", size = 115599, upload-time = "2025-08-20T19:42:09.449Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/38/1efeec8b4d741c09ccd169baf8a00c07a0176b58e418d4cd0c30dffedd22/dash_bootstrap_components-2.0.4-py3-none-any.whl", hash = "sha256:767cf0084586c1b2b614ccf50f79fe4525fdbbf8e3a161ed60016e584a14f5d1", size = 204044, upload-time = "2025-08-20T19:42:07.928Z" }, +] + +[[package]] +name = "datasets" +version = "5.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"] }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow" }, + { name = "pyyaml" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/17/e6/b5d8c77f13cc6269660b0f2691e8875777b9d94972e281b7b2c25f25bd9d/datasets-5.1.0.tar.gz", hash = "sha256:1561347daa8841b51351ef2ad1647b4ee4af406852c0f7bd1df587ac1ca7888e", size = 687306, upload-time = "2026-10-05T15:32:32.053Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/cc/7f624629846c709ef1c68aa61bfb8d0ae2638cbe265104a1c2f7a630949e/datasets-5.1.0-py3-none-any.whl", hash = "sha256:86fd08b280485aab82894d2c81842c4151d93b575efea0054315104cb7bc3cec", size = 604432, upload-time = "2026-10-05T15:32:29.892Z" }, +] + +[[package]] +name = "dill" +version = "0.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/81/e1/56027a71e31b02ddc53c7d65b01e68edf64dea2932122fe7746a516f75d5/dill-0.4.1.tar.gz", hash = "sha256:423092df4182177d4d8ba8290c8a5b640c66ab35ec7da59ccfa00f6fa3eea5fa", size = 187315, upload-time = "2026-01-19T02:36:56.85Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/77/dc8c558f7593132cf8fefec57c4f60c83b16941c574ac5f619abb3ae7933/dill-0.4.1-py3-none-any.whl", hash = "sha256:1e1ce33e978ae97fcfcff5638477032b801c46c7c65cf717f95fbc2248f79a9d", size = 120019, upload-time = "2026-01-19T02:36:55.663Z" }, +] + +[[package]] +name = "docstring-parser" +version = "0.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" }, +] + +[[package]] +name = "fastapi" +version = "0.143.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/d5/b0aeb0b303650ac87b0411de4aaf3f901b06042dcc3fb00f30b97b7ff585/fastapi-0.143.3.tar.gz", hash = "sha256:b9ab567ee57afb4454004ce04c889f8f0160ac47946b99795887cd6e88484848", size = 469834, upload-time = "2026-10-16T14:14:13.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/1a/03d246befcf307219bb2161c97d8c5d314f84125bf7dd245730a28589828/fastapi-0.143.3-py3-none-any.whl", hash = "sha256:75e8bd68e2f52f77d29b2879749c257d64de2d85282d25270caf2bfccce5efe5", size = 144849, upload-time = "2026-10-16T14:14:11.763Z" }, +] + +[[package]] +name = "ffmpeg-python" +version = "0.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "future" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dd/5e/d5f9105d59c1325759d838af4e973695081fbbc97182baf73afc78dec266/ffmpeg-python-0.2.0.tar.gz", hash = "sha256:65225db34627c578ef0e11c8b1eb528bb35e024752f6f10b78c011f6f64c4127", size = 21543, upload-time = "2019-07-06T00:19:08.989Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/0c/56be52741f75bad4dc6555991fabd2e07b432d333da82c11ad701123888a/ffmpeg_python-0.2.0-py3-none-any.whl", hash = "sha256:ac441a0404e053f8b6a1113a77c0f452f1cfc62f6344a769475ffdc0f56c23c5", size = 25024, upload-time = "2019-07-06T00:19:07.215Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f4/a9/1af41b37c3279712b22cdc63aac78a52432202b6fe1f9666a2a3d2831fb4/filelock-4.2.0.tar.gz", hash = "sha256:7a60906c75227cf04d0c273afadc8219400f11aeb13cc69591d4f6cdc6c8036e", size = 569667, upload-time = "2026-10-14T20:57:13.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/a3/9bc26acff301fe1aaea1cc3d82a1d57e0a34df3e1cadbfa91ac2dbcdde5c/filelock-4.2.0-py3-none-any.whl", hash = "sha256:2ff5690882e8cdb00ef31fb3d01a3094c29f30985426c59495afb1733f3b7238", size = 135032, upload-time = "2026-10-14T20:57:11.349Z" }, +] + +[[package]] +name = "flask" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blinker" }, + { name = "click" }, + { name = "itsdangerous" }, + { name = "jinja2" }, + { name = "markupsafe" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" }, +] + +[[package]] +name = "fonttools" +version = "4.67.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/36/102e180f8f5dbaee88b26595b01ca8aa80bf4e62128d9aa94265b3996c96/fonttools-4.67.0.tar.gz", hash = "sha256:3cb57e6600ca77c0b1729cf8adc23bc0652633a37f18cfa934d9c7bc3de25519", size = 3750028, upload-time = "2026-10-14T13:20:28.294Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/50/f674402869f11a89868c4755ae86cd2fcfd67ca6193c6f5d1b479b1267b9/fonttools-4.67.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:fcb9743140419410161acfe7ec205fb0a8a703acfccb85b586becb5a97c047c9", size = 3108316, upload-time = "2026-10-14T13:18:39.162Z" }, + { url = "https://files.pythonhosted.org/packages/e3/c8/5963603c5f9bbc28bde3a29dd7cdbe0bfcbee414b0f7eccec04ae477e1b6/fonttools-4.67.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ad813967410ba6d24a52850df59b164ee17883f17b96a91b4b0ac6e9d7b5a118", size = 2598450, upload-time = "2026-10-14T13:18:42.136Z" }, + { url = "https://files.pythonhosted.org/packages/25/6d/f8e5924917a6b5c0296fb507f748c139a34972f66e91d89159d5c98e27b2/fonttools-4.67.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:768a33bbe6ec5ba8f19979f938752f06d4e614cb554fd47abd7830f2007660e3", size = 5427391, upload-time = "2026-10-14T13:18:44.248Z" }, + { url = "https://files.pythonhosted.org/packages/c1/e0/ec9e4cc868c514deb02233aa1047a6aeb9350d3ee012862f58eec10ef834/fonttools-4.67.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:eb3c98cac93aac4b9f6e3ce2008325340b234cc9b0338ca6b513f31962a1e278", size = 5408233, upload-time = "2026-10-14T13:18:46.616Z" }, + { url = "https://files.pythonhosted.org/packages/cd/4a/fe409cb3ab32f322de92e08e6362cd06bf6dd5f0cee5980d823849e9bd11/fonttools-4.67.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e0ca4c8438dd6320f5850c9bbee3b3980455ee3bac602a9a0299caf9e799a0e8", size = 5364778, upload-time = "2026-10-14T13:18:48.926Z" }, + { url = "https://files.pythonhosted.org/packages/de/5b/2a8dede092113be56329dd210deb6b34c55df2f3d7270934ffece8c7d0bb/fonttools-4.67.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2a09d33a9264a6b29efca9dc633b53969aaedb250a9c8521d60f51280cef65ca", size = 5528522, upload-time = "2026-10-14T13:18:51.297Z" }, + { url = "https://files.pythonhosted.org/packages/6c/de/d3baf686e4ac5726a24819a670747c51571c774dcfa41cc0528e5e8c1a2d/fonttools-4.67.0-cp312-cp312-win32.whl", hash = "sha256:e8a8545cbd58bd29494ffe81e3cb35f8a29332a8e495c42bec334145ce8cd65b", size = 2446090, upload-time = "2026-10-14T13:18:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/c1/3a/625a6dd0173e88dbea1826405b4bcbfa06c6ca095310ed720caba36b2e43/fonttools-4.67.0-cp312-cp312-win_amd64.whl", hash = "sha256:2bfab2f5d1d255dec82f4bd082a1c10e77df808e42210890f50a9c30bf91570e", size = 2497985, upload-time = "2026-10-14T13:18:55.245Z" }, + { url = "https://files.pythonhosted.org/packages/3d/61/4161946319472aaa9b897bd18ad5108a5b10f5ebaa503d921a001ac4fff9/fonttools-4.67.0-py3-none-any.whl", hash = "sha256:4304f03ed7f4ba000a8dcc941ad854bfa52e2f3b6112b8f099b6f431cf98e701", size = 1213142, upload-time = "2026-10-14T13:20:26.258Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/29/948b9aa87e75820a38650af445d2ef2b6b8a6fab1a23b6bb9e4ef0be2d59/frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1", size = 87782, upload-time = "2025-10-06T05:36:06.649Z" }, + { url = "https://files.pythonhosted.org/packages/64/80/4f6e318ee2a7c0750ed724fa33a4bdf1eacdc5a39a7a24e818a773cd91af/frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b", size = 50594, upload-time = "2025-10-06T05:36:07.69Z" }, + { url = "https://files.pythonhosted.org/packages/2b/94/5c8a2b50a496b11dd519f4a24cb5496cf125681dd99e94c604ccdea9419a/frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4", size = 50448, upload-time = "2025-10-06T05:36:08.78Z" }, + { url = "https://files.pythonhosted.org/packages/6a/bd/d91c5e39f490a49df14320f4e8c80161cfcce09f1e2cde1edd16a551abb3/frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383", size = 242411, upload-time = "2025-10-06T05:36:09.801Z" }, + { url = "https://files.pythonhosted.org/packages/8f/83/f61505a05109ef3293dfb1ff594d13d64a2324ac3482be2cedc2be818256/frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4", size = 243014, upload-time = "2025-10-06T05:36:11.394Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cb/cb6c7b0f7d4023ddda30cf56b8b17494eb3a79e3fda666bf735f63118b35/frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8", size = 234909, upload-time = "2025-10-06T05:36:12.598Z" }, + { url = "https://files.pythonhosted.org/packages/31/c5/cd7a1f3b8b34af009fb17d4123c5a778b44ae2804e3ad6b86204255f9ec5/frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b", size = 250049, upload-time = "2025-10-06T05:36:14.065Z" }, + { url = "https://files.pythonhosted.org/packages/c0/01/2f95d3b416c584a1e7f0e1d6d31998c4a795f7544069ee2e0962a4b60740/frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52", size = 256485, upload-time = "2025-10-06T05:36:15.39Z" }, + { url = "https://files.pythonhosted.org/packages/ce/03/024bf7720b3abaebcff6d0793d73c154237b85bdf67b7ed55e5e9596dc9a/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29", size = 237619, upload-time = "2025-10-06T05:36:16.558Z" }, + { url = "https://files.pythonhosted.org/packages/69/fa/f8abdfe7d76b731f5d8bd217827cf6764d4f1d9763407e42717b4bed50a0/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3", size = 250320, upload-time = "2025-10-06T05:36:17.821Z" }, + { url = "https://files.pythonhosted.org/packages/f5/3c/b051329f718b463b22613e269ad72138cc256c540f78a6de89452803a47d/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143", size = 246820, upload-time = "2025-10-06T05:36:19.046Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/58282e8f98e444b3f4dd42448ff36fa38bef29e40d40f330b22e7108f565/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608", size = 250518, upload-time = "2025-10-06T05:36:20.763Z" }, + { url = "https://files.pythonhosted.org/packages/8f/96/007e5944694d66123183845a106547a15944fbbb7154788cbf7272789536/frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa", size = 239096, upload-time = "2025-10-06T05:36:22.129Z" }, + { url = "https://files.pythonhosted.org/packages/66/bb/852b9d6db2fa40be96f29c0d1205c306288f0684df8fd26ca1951d461a56/frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf", size = 39985, upload-time = "2025-10-06T05:36:23.661Z" }, + { url = "https://files.pythonhosted.org/packages/b8/af/38e51a553dd66eb064cdf193841f16f077585d4d28394c2fa6235cb41765/frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746", size = 44591, upload-time = "2025-10-06T05:36:24.958Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1dc65480ab147339fecc70797e9c2f69d9cea9cf38934ce08df070fdb9cb/frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd", size = 40102, upload-time = "2025-10-06T05:36:26.333Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2026.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[package]] +name = "future" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a7/b2/4140c69c6a66432916b26158687e821ba631a4c9273c474343badf84d3ba/future-1.0.0.tar.gz", hash = "sha256:bd2968309307861edae1458a4f8a4f3598c03be43b97521076aebf5d94c07b05", size = 1228490, upload-time = "2024-02-21T11:52:38.461Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl", hash = "sha256:929292d34f5872e70396626ef385ec22355a1fae8ad29e1a734c3e43f9fbc216", size = 491326, upload-time = "2024-02-21T11:52:35.956Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "hf-xet" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/27/06d899ea7bd721d272f84aac98bdb238de98af4cc767a69056d967d68c71/hf_xet-1.7.0.tar.gz", hash = "sha256:d406ec79053c0871817f700c2ac8c36ba0d87f9c34b7458b0f0063bb218b0466", size = 985689, upload-time = "2026-10-06T20:18:43.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/0b/b03be21ffaada749ba0d3197d8aefbf1aa698bac149580421c15239b299e/hf_xet-1.7.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e3e88a7a75d7d95cbee1f37dc31341d6201124cf21c6c4b1dfab8ccba9b09e0f", size = 3796096, upload-time = "2026-10-06T20:18:28.43Z" }, + { url = "https://files.pythonhosted.org/packages/c3/47/a26ebdce7056a61e931f228439bc0ab08cbec239d1690f965e5e637cba79/hf_xet-1.7.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:59fba37039233c7fcbe196817d6cdcf1b40dfb17b410f229d85b0cf0a1848da4", size = 3560352, upload-time = "2026-10-06T20:18:30.365Z" }, + { url = "https://files.pythonhosted.org/packages/a3/4c/2bf3b66c215d409655f28de1622393dde04c9461280d48c7924bb3b2decd/hf_xet-1.7.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2814a6e999d13464c4d679b788cc5d784eb5a4edfc638a31f10e9a11ab531ef8", size = 4212180, upload-time = "2026-10-06T20:18:32.292Z" }, + { url = "https://files.pythonhosted.org/packages/49/0c/a2f703a5a78267556e89e03316fa0805c86b72b50829bc67665746e8ebf0/hf_xet-1.7.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:fcfd6c22418e57dd5b3aea649e813b2e2cfb2aebf317b210d90f1fe4b3018b52", size = 3990011, upload-time = "2026-10-06T20:18:34.21Z" }, + { url = "https://files.pythonhosted.org/packages/a4/77/e52e4201b1cbf571530a61cc57f70182045a39a230089ee5f1df182a4de2/hf_xet-1.7.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:80f79dae613ce9e0ea1fd1ae15616ca9ac74aed4c770aabc199c4f03ebecc863", size = 4190628, upload-time = "2026-10-06T20:18:36.062Z" }, + { url = "https://files.pythonhosted.org/packages/6c/dc/03a21b89f118664a0926ff25b0f8e44a519bf22724a6a8fc7a9abbc188b6/hf_xet-1.7.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0a9e802f33bf50c851abe45fc5380e61f959e2d369647d6742b79ad9d6c27cab", size = 4418814, upload-time = "2026-10-06T20:18:37.888Z" }, + { url = "https://files.pythonhosted.org/packages/4d/59/b35106dfa71b6eef605dc88bd038fe99c7f86fb132a15b60d0bf2f235b2c/hf_xet-1.7.0-cp38-abi3-win_amd64.whl", hash = "sha256:2b7bb5727889b0f2436dbaaad8fc4c3e66b8240d992716989e0c086b4278b1bc", size = 3822644, upload-time = "2026-10-06T20:18:40.052Z" }, + { url = "https://files.pythonhosted.org/packages/48/cd/072313585f74fe9d441e2eb5e0a4703c30586cd709810ea369675f61b74e/hf_xet-1.7.0-cp38-abi3-win_arm64.whl", hash = "sha256:acc3851cf2576a8fb2ae926da863f4efabe21303cf292e9a44332802ab0dcc6a", size = 3662436, upload-time = "2026-10-06T20:18:42.205Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httptools" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/ec/deed52912ab7ca6c0b12859330c571c60c61d7267b341b28951fcbf13694/httptools-0.9.0.tar.gz", hash = "sha256:d484ebb7e3a3f3597b0f645fbd1b85633674ca808c1f5ba11c2caf7c66f5c8b6", size = 282523, upload-time = "2026-10-09T19:57:04.301Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/ed/0916b8b7ebd1deeaf22acba71b68c57b4b6b69aa1918f3812dea208b4276/httptools-0.9.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f9ccc9884241efceb4547a92955d128574c864681f11b7ea3ecbde295fafbe8b", size = 119039, upload-time = "2026-10-09T19:54:32.556Z" }, + { url = "https://files.pythonhosted.org/packages/c2/0b/9b6de4a01a563a904d0826c9069c824b330e1816df26c9bdf93f60b50857/httptools-0.9.0-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:45b3002392948dcf578029c89f6318e1289a993a1a5ec38a4161560fab60f811", size = 115051, upload-time = "2026-10-09T19:54:33.908Z" }, + { url = "https://files.pythonhosted.org/packages/85/3f/642113e9882f53158ecddf58003d25f18ded2c210ed23bf6eb663d4d51c3/httptools-0.9.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3e3201fe4d46e0d15d7ff9fafc94a605da9eb82d2c5b9837f0368acb325481f1", size = 552848, upload-time = "2026-10-09T19:54:35.434Z" }, + { url = "https://files.pythonhosted.org/packages/95/4c/3ecc59c99c28652d8d08d9b5be65770a14d2cadc616dad94224cee2b0e7e/httptools-0.9.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:58a1b0ec4cbb930e69669f9771715b2c7898d3cdf064d9811f7a66afef96b544", size = 549181, upload-time = "2026-10-09T19:54:37.099Z" }, + { url = "https://files.pythonhosted.org/packages/43/ce/21f5b2759590b7054e38d3b704a3c6b853c3395c370b3d6f16c45aea0fc0/httptools-0.9.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c58dc91aefb31adad500aa68054334f429b840b36dd29e34e834101044cb2ef", size = 569121, upload-time = "2026-10-09T19:54:38.772Z" }, + { url = "https://files.pythonhosted.org/packages/52/c3/7c523aa8d0fa7a57010a3e1bbdebc209585009076465f3d1ae6a3f54b814/httptools-0.9.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6b900073e7b8481ef1aaf4f6c1789d210a1db01a9da8789821578cfeb4c2d540", size = 487649, upload-time = "2026-10-09T19:54:40.398Z" }, + { url = "https://files.pythonhosted.org/packages/94/e2/d90d60002692b8afcbc06fb49ca3a4365b32abed6c40fb2b612c67721a00/httptools-0.9.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6c12d0393a903b58bc5f5a7406d6c5290acfb8284290d68547ce620c06f7d133", size = 529583, upload-time = "2026-10-09T19:54:42.296Z" }, + { url = "https://files.pythonhosted.org/packages/46/c0/19172874cde0344a20c85877a0b2d0dcfca31111729ad8a79e8b4ac4e207/httptools-0.9.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:29b0d823e3c1e7cd1093a5dc889245db693ef13ada624cd66e2262421ef38867", size = 552414, upload-time = "2026-10-09T19:54:44.19Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b8/02ea7910f69e5371986b025fb3b410592106df54e977a5732fd1d95917b5/httptools-0.9.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:6ebd39ee26db460cfe5ab8b71a15d1149b289139a0d3981522757d6af620887e", size = 482400, upload-time = "2026-10-09T19:54:46.064Z" }, + { url = "https://files.pythonhosted.org/packages/de/97/f05eac916d44cbbfe43668a6a40ab93e7fd8f94d5120d1ce2d8e55c69871/httptools-0.9.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4efbee349138a3fee7a4cc3a95abd2d499fae70dd5bff9fed9138d6f570f4283", size = 536148, upload-time = "2026-10-09T19:54:47.695Z" }, + { url = "https://files.pythonhosted.org/packages/b6/e9/9435dfcb7f1a1d6ebdc79a902164dfca70e33774c80bb60d25c630c31ef1/httptools-0.9.0-cp312-cp312-win32.whl", hash = "sha256:36fac804b8cfd6b935ae64f71349f833d2b6298404626d017a2c57bb942bc643", size = 86274, upload-time = "2026-10-09T19:54:49.1Z" }, + { url = "https://files.pythonhosted.org/packages/8b/69/813f1bf90be507d4166c437be1a413574d0e0abf36e2fec10c266661b0ee/httptools-0.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:7e32b83bd8c2f8b6fa726ef34e63e21c4d7eddc277d40d4ef7245ea3ed28e5b6", size = 92446, upload-time = "2026-10-09T19:54:50.498Z" }, + { url = "https://files.pythonhosted.org/packages/ae/e0/1d29e328c4cafe843403341e1455e0aec18b0e6910fbb14f12b36b563f19/httptools-0.9.0-cp312-cp312-win_arm64.whl", hash = "sha256:813a32f94991b9627795528053c73a57d2ce3eb98ede89f0e1c7a31095938e81", size = 88676, upload-time = "2026-10-09T19:54:51.844Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "1.33.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "httpx" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/25/2a/484d112c0d8fc5f665d7b65137ac9cdb2953c982391598c3597968a12ee7/huggingface_hub-1.33.0.tar.gz", hash = "sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e", size = 1043548, upload-time = "2026-09-24T09:49:29.971Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/16/963096d224b80909432dc16561a615fd33d2d13beef3ce4c63fa25e40867/huggingface_hub-1.33.0-py3-none-any.whl", hash = "sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899", size = 846435, upload-time = "2026-09-24T09:49:28.059Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "importlib-metadata" +version = "9.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "jmespath" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/2a/e867e8531cf3e36b41201936b7fa7ba7b5702dbef42922193f05c8976cd6/jmespath-1.0.1.tar.gz", hash = "sha256:90261b206d6defd58fdd5e85f478bf633a2901798906be2ad389150c5c60edbe", size = 25843, upload-time = "2022-06-17T18:00:12.224Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/b4/b9b800c45527aadd64d5b442f9b932b00648617eb5d63d2c7a6587b7cafc/jmespath-1.0.1-py3-none-any.whl", hash = "sha256:02e2e4cc71b5bcab88332eebf907519190dd9e6e82107fa7f83b1003a6252980", size = 20256, upload-time = "2022-06-17T18:00:10.251Z" }, +] + +[[package]] +name = "kaleido" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "choreographer" }, + { name = "logistro" }, + { name = "orjson" }, + { name = "packaging" }, + { name = "pytest-timeout" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/ad/76eec859b71eda803a88ea50ed3f270281254656bb23d19eb0a39aa706a0/kaleido-1.2.0.tar.gz", hash = "sha256:fa621a14423e8effa2895a2526be00af0cf21655be1b74b7e382c171d12e71ef", size = 64160, upload-time = "2025-11-04T21:24:23.833Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4b/97/f6de8d4af54d6401d6581a686cce3e3e2371a79ba459a449104e026c08bc/kaleido-1.2.0-py3-none-any.whl", hash = "sha256:c27ed82b51df6b923d0e656feac221343a0dbcd2fb9bc7e6b1db97f61e9a1513", size = 68997, upload-time = "2025-11-04T21:24:21.704Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/9b/65b302742389c6f96f2956bef5decf26011309feb2fc5d79613af18adea4/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:63fb7294b768f444eb4b068965f2662f28c2fd4161e23bd60fcf3ff27b74c046", size = 123876, upload-time = "2026-08-28T10:25:27.44Z" }, + { url = "https://files.pythonhosted.org/packages/71/74/c21f339956f6f691b2ed7e31d5f3ae767304df6c460192739fc830853051/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ebdef3eae5336568147c39a55be6a2036ffde53faa9ca2d978989ae7c2da12c", size = 66487, upload-time = "2026-08-28T10:25:28.728Z" }, + { url = "https://files.pythonhosted.org/packages/84/e5/bdb34e21523e01dceda064d63713f3bdec91388af24fba1eca7ea5e85864/kiwisolver-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1798e83840c3f627246104c4d8a9639c60fa068adf9ce92b61791781fa8a68c1", size = 64660, upload-time = "2026-08-28T10:25:30.071Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" }, + { url = "https://files.pythonhosted.org/packages/6f/35/09c58daac34e6f6ea5c6dee0094b422118e5a7c265586008a95fd135ac5f/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002", size = 1278499, upload-time = "2026-08-28T10:25:33.375Z" }, + { url = "https://files.pythonhosted.org/packages/19/32/739765e24fbad29d13f83e546ea4abc215a78cea9d677ca09025b027724d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048", size = 1296677, upload-time = "2026-08-28T10:25:35.059Z" }, + { url = "https://files.pythonhosted.org/packages/df/32/03304d1010e2cc45e5b3b52cef7e43fed3a2a5cd6c87a89b4a88e1d85b5d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7", size = 1346037, upload-time = "2026-08-28T10:25:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/3e/57/4c49377bfd274450dd72ecaa13eaac32ea804a03363e4d1db0c5aa999ceb/kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083", size = 988248, upload-time = "2026-08-28T10:25:38.299Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c3/38df144a08b6c5d75ca4504e5cc3141bb3bfef64c04f4ef48204f42711b6/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148", size = 2228722, upload-time = "2026-08-28T10:25:40.038Z" }, + { url = "https://files.pythonhosted.org/packages/e7/11/3221838a89cd64d9b386353e000cd8a296069a20fbe3584507fdfd5bebae/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c", size = 2325216, upload-time = "2026-08-28T10:25:41.699Z" }, + { url = "https://files.pythonhosted.org/packages/83/d4/075c219230697bb5db910d37262b9bacf880f92b4811a02ab81ed073a253/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858", size = 1977689, upload-time = "2026-08-28T10:25:43.559Z" }, + { url = "https://files.pythonhosted.org/packages/bb/08/1d219c3c2dd960983d0d4da623d916e9de6385df2b0bab3d1af0e9b8fccc/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6", size = 2491443, upload-time = "2026-08-28T10:25:45.242Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" }, + { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" }, + { url = "https://files.pythonhosted.org/packages/94/61/ef0daa157c8bb23672f7423e0d14c39db1dc6ef8ed47e6bc54c9c1bef3bf/kiwisolver-1.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:ad8b9671348d7c8716715652ae11f85ed0eb99e265a2df2ca490577d69860b2c", size = 68324, upload-time = "2026-08-28T10:25:49.81Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c4/1407df7512a5b36cc79840e01710dc575733c461b13ab866cae77eaf87f3/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:482676e5bd48d70ac99d9fc78863469845421e01184fa83f1f9366dc49f7e974", size = 134002, upload-time = "2026-08-28T10:28:08.881Z" }, + { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c1/69f00d627949580e43d57af0aa465df46868d7c29801c137a55374101294/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f", size = 73362, upload-time = "2026-08-28T10:28:12.449Z" }, +] + +[[package]] +name = "linkify-it-py" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/98/7a1a5f31fd5c7ba93e963b168e244b8e3dd705b3d2a718e3c3307583bf57/linkify_it_py-2.2.0.tar.gz", hash = "sha256:907acd2d17ac1fbb9ddb62c8957ccbd6158cac602231a15c3b0cd1e215f03cee", size = 32939, upload-time = "2026-08-29T07:07:08.305Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/d4/1152d1c7ab42d8b908be64fd200ddc870dc9d4925e951198702084aa1a7d/linkify_it_py-2.2.0-py3-none-any.whl", hash = "sha256:3adc40eb5af300b2605fcfdb968c24e1d780a90f1f2221af7c15e5111e94d443", size = 21971, upload-time = "2026-08-29T07:07:07.164Z" }, +] + +[[package]] +name = "logistro" +version = "2.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/08/90/bfd7a6fab22bdfafe48ed3c4831713cb77b4779d18ade5e248d5dbc0ca22/logistro-2.0.1.tar.gz", hash = "sha256:8446affc82bab2577eb02bfcbcae196ae03129287557287b6a070f70c1985047", size = 8398, upload-time = "2025-11-01T02:41:18.81Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/6aa79ba3570bddd1bf7e951c6123f806751e58e8cce736bad77b2cf348d7/logistro-2.0.1-py3-none-any.whl", hash = "sha256:06ffa127b9fb4ac8b1972ae6b2a9d7fde57598bf5939cd708f43ec5bba2d31eb", size = 8555, upload-time = "2025-11-01T02:41:17.587Z" }, +] + +[[package]] +name = "mako" +version = "1.4.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5a/09/e07c4b5579a79f4b16f8d4f29f6c54514ac787c4ad506b8c4f28a0e6b0bf/mako-1.4.3.tar.gz", hash = "sha256:cd6537fe88d5fec315c55c2f8529bc4ce7a9a352ad7db3eeaa6a66e2dd4ec37a", size = 412799, upload-time = "2026-09-22T20:54:31.509Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/a0/053d6af3e8f871e0073b4a36732d9e65be77a72e5434c31b94f6af78a6bb/mako-1.4.3-py3-none-any.whl", hash = "sha256:723296007c870bfd6b3f0c3230dba7198096e5269297ebf5e4eff9e7ffa39d4f", size = 80164, upload-time = "2026-09-22T20:54:33.128Z" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + +[package.optional-dependencies] +linkify = [ + { name = "linkify-it-py" }, +] +plugins = [ + { name = "mdit-py-plugins" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/09/4c59d56b8461ae8eb0d8ba34bb25b7e618547044679d58a82ef9b2479fc1/markupsafe-3.0.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6", size = 11658, upload-time = "2026-10-02T23:04:51.876Z" }, + { url = "https://files.pythonhosted.org/packages/a2/f0/d6613774d86fbf6d145751d43c59875e47a6f9f17daee0aef173bd36d90e/markupsafe-3.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f", size = 12050, upload-time = "2026-10-02T23:04:52.931Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f2/8f18e0b806eb13c1f8d07d917a720831ead54253a6dec011fbc78098a6f8/markupsafe-3.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b", size = 24363, upload-time = "2026-10-02T23:04:53.895Z" }, + { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525, upload-time = "2026-10-02T23:04:54.905Z" }, + { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733, upload-time = "2026-10-02T23:04:56.229Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001, upload-time = "2026-10-02T23:04:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f8/bffee5e7d2a3deb59748a797650a48af7e672025cf641a79344a771ad106/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c", size = 23793, upload-time = "2026-10-02T23:04:59.686Z" }, + { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640, upload-time = "2026-10-02T23:05:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074, upload-time = "2026-10-02T23:05:01.813Z" }, + { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563, upload-time = "2026-10-02T23:05:03.239Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" }, + { url = "https://files.pythonhosted.org/packages/c8/52/7632a53360671a9b750cdbabaf9cdd89f18b42248b8e4cb42c0b0296e459/markupsafe-3.0.4-cp312-cp312-win32.whl", hash = "sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237", size = 14108, upload-time = "2026-10-02T23:05:05.513Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/4c24208776a65878d656996945aacfbfe010d3720d1a98fc0eb8491fc03b/markupsafe-3.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9", size = 14174, upload-time = "2026-10-02T23:05:07.617Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.11.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/ce/1bfcc4873b121597791ad74032943b123218c0613af0b97e8dd05e916fb1/matplotlib-3.11.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef752769cd962f39ea0b6ffc82d1ea43a0012c5a6157c7a075212fa509cfcff2", size = 9476466, upload-time = "2026-09-11T19:03:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c4/7f5f3601ee69baf072c0c7d3ce60c03e0618621c5a56c34a62a460e29d11/matplotlib-3.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ef31985c4dedb5f1424e1aec6849a47dd37689cb7fa3c20b1b82187f26806261", size = 9305583, upload-time = "2026-09-11T19:03:22.39Z" }, + { url = "https://files.pythonhosted.org/packages/b8/90/2b3fd67ee273163faeda6d514be70b5596eaa0fd77b60ffc294ad0b34f5f/matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27", size = 9860353, upload-time = "2026-09-11T19:03:25.049Z" }, + { url = "https://files.pythonhosted.org/packages/f4/84/32549e7a462dc311aed2ab62e5d2538028840b5c53a8be0195c789937c3d/matplotlib-3.11.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b9a7ad579856284135e401ecc918c5f8a017ee30539298862a109f51b971710", size = 10670348, upload-time = "2026-09-11T19:03:28.108Z" }, + { url = "https://files.pythonhosted.org/packages/84/39/02e21b74f7439bd643d717ea846006d46e309e6d29b632b57751265311d6/matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2", size = 10810580, upload-time = "2026-09-11T19:03:31.402Z" }, + { url = "https://files.pythonhosted.org/packages/04/93/0d239bde12b308262265c2d98909b2f0ecad2b5deeae96241642e822e9c7/matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43", size = 9349409, upload-time = "2026-09-11T19:03:34.195Z" }, + { url = "https://files.pythonhosted.org/packages/49/a8/06baf901c02246c8a222b655cc4540ef9c15e1549a04e07927f9cde716c3/matplotlib-3.11.2-cp312-cp312-win_arm64.whl", hash = "sha256:643ff850d8e0f5b8319337f87ed3cb59506afb3df3cc48de777d85871233be7b", size = 9028084, upload-time = "2026-09-11T19:03:37.032Z" }, +] + +[[package]] +name = "mdit-py-plugins" +version = "0.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/59/fc/f8d0863f8862f25602c0404d75568e89fb6b4109804645e5cdfb1be5cf56/mdit_py_plugins-0.6.1.tar.gz", hash = "sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0", size = 56114, upload-time = "2026-05-13T09:03:38.91Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/69/6da5581c6a7fede7dc261bf4e67d6adca4196f176b43288b55b3db395b6e/mdit_py_plugins-0.6.1-py3-none-any.whl", hash = "sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d", size = 66663, upload-time = "2026-05-13T09:03:37.76Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[package]] +name = "msgspec" +version = "0.22.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/e6/6dcf9306ff3c5e486578f3bf29ed11dfbdbbc2a8bf0caf7e07d392887fda/msgspec-0.22.0.tar.gz", hash = "sha256:0a13624a4969159fe35d8c2a3d377b2b61bbd8585e327440d5e52725affcce38", size = 343188, upload-time = "2026-09-29T14:14:11.422Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/87/3e017dca361d09ed1cd09dc981a6df21b32e830fbec3470f7486d38b6be5/msgspec-0.22.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ab1e9e7531e353653b906cdd12a0220cc288a1e8e3436aabc65f4508d91b14d9", size = 201301, upload-time = "2026-09-29T14:12:38.048Z" }, + { url = "https://files.pythonhosted.org/packages/fb/02/109165edaafb895668d87177972a32ade9126a54f3736123d8e44be9096d/msgspec-0.22.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b60b43425a47eb9cfe987f6874e354ca7c760e58e295b4e2273ff03574df28a1", size = 193044, upload-time = "2026-09-29T14:12:39.46Z" }, + { url = "https://files.pythonhosted.org/packages/54/a5/65de05f8804492f76ea121b21a125cdf1d97ec461c677bfa0ba354d6fbdd/msgspec-0.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5a169b5b03f0f2c7a296c002647db1dab75d2cd501bca34e32b71cab0261b56", size = 224035, upload-time = "2026-09-29T14:12:40.876Z" }, + { url = "https://files.pythonhosted.org/packages/4a/cc/aa1a47f8c92280d37498a5ea56a2a36606d034383e3e6472d64cbb56cf85/msgspec-0.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99c401861c5bb3a57f7d6423ea7ed4352cd57aa3f04f4fbe9f3e3e4564a10f08", size = 230377, upload-time = "2026-09-29T14:12:42.796Z" }, + { url = "https://files.pythonhosted.org/packages/61/50/f8bcdb3d613a4a4b92704297a12eba5c985cf572a64ee1a004d265759c69/msgspec-0.22.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:08826f5e5b0fa2f7a88592c396a243cfcc63d37e19f9d4fbe3b3f1be2fbdc404", size = 237390, upload-time = "2026-09-29T14:12:44.282Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8a/473fa423f8fdd1b810b8652594323d7301df6920b62844d860daa0feff34/msgspec-0.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21460f54cee9208239b1a8421fdf25bffc77293e1daba88f585711ad839b9758", size = 227733, upload-time = "2026-09-29T14:12:45.839Z" }, + { url = "https://files.pythonhosted.org/packages/03/1d/272ce23adae6c71b3f763aed3ee6e115cccc56124ed8ee0e3e3d2681e2c8/msgspec-0.22.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cfc3d9557de9c806318725b702f3e664db33167bb42892079b693c69893fd33b", size = 236783, upload-time = "2026-09-29T14:12:47.234Z" }, + { url = "https://files.pythonhosted.org/packages/f6/26/29e0b9a8605c8819a3c718158e345a616ac42c092dd7d7ab248c2f2b0a72/msgspec-0.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b25dcbc108783cb72503ed705b9fbb8c3cb02ee5801923f44b5f038c91cc365", size = 232728, upload-time = "2026-09-29T14:12:48.792Z" }, + { url = "https://files.pythonhosted.org/packages/e1/a6/99597c281d716da6c662b48dcc3f734669f716b41d5df2af367dac9e7c21/msgspec-0.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:6ad64f5c260866b0d543f89f50cee43628989c1433c5de7ce820281fa28a2611", size = 192885, upload-time = "2026-09-29T14:12:50.274Z" }, + { url = "https://files.pythonhosted.org/packages/46/80/85fff923d448b886ec3a85900c578d9367f08dad54fe48879495b4c6d055/msgspec-0.22.0-cp312-cp312-win_arm64.whl", hash = "sha256:0922714feff5300aacd8ecd65fa828317ce4bf5212b3139258c0bfc0253cd80e", size = 191223, upload-time = "2026-09-29T14:12:51.699Z" }, +] + +[[package]] +name = "multidict" +version = "6.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/99/1d4d69c3512d0ddbfa3a1b69cfd9a151012ab2eb4eabbb096201b1f0b7d8/multidict-6.9.1.tar.gz", hash = "sha256:0f06e60fa190aa7abd0914c2a766736fdc8e9f34878c4346338534b73d1b20e2", size = 182404, upload-time = "2026-09-21T17:59:05.362Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/0d/4b5afb6d3e545c9af0cdfe2db8f6f4c6664568c23d863d888674e447e6a4/multidict-6.9.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:29138fef49828542e859828107e42e50d0e587c513b7eb4b2d92bade2b0860fe", size = 98360, upload-time = "2026-09-21T17:55:11.508Z" }, + { url = "https://files.pythonhosted.org/packages/89/ab/1b9ca66251899981b21138b87da9d5a9c2c81af12b1ea7d19466972f7fe2/multidict-6.9.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:19e31815d41cefc365489e591d105d2baceb2f65aa75d29471fbdbda8651e006", size = 59979, upload-time = "2026-09-21T17:55:12.866Z" }, + { url = "https://files.pythonhosted.org/packages/36/eb/6ae44062466c26c8469ef43f2481a6a48d8cea0587b2d54514ec92e2adfd/multidict-6.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6ed30be8918e18c8bed0a2e8b70639ecf02feb61ed00ca2e41cfcb2a50fa3f42", size = 57736, upload-time = "2026-09-21T17:55:14.223Z" }, + { url = "https://files.pythonhosted.org/packages/b9/5c/a67817593019257a4ac8b0d1b4c426030e637c047b0692ef405439ecea7a/multidict-6.9.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:637f4ae36264bd7b8d9a60193acddc1d735ad52e8ed53a19931ea6d921fea8e5", size = 333097, upload-time = "2026-09-21T17:55:15.591Z" }, + { url = "https://files.pythonhosted.org/packages/90/bf/599ae2e6222822d88a247a8a7ae82fe6fd25d5700757b79603d5edafe6a0/multidict-6.9.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:35fc236507fb1b3138f0af5ecd5f94ed752d4d6d826248eae425f86204013eea", size = 334196, upload-time = "2026-09-21T17:55:17.015Z" }, + { url = "https://files.pythonhosted.org/packages/15/10/d8aac5acacbe7f5c117866c776ec26d5f15a868759b6f37ad8e7ed3b5b02/multidict-6.9.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e58952f04772f59f11c6e007471449809a30165188669bca8fdb19dde40a8f24", size = 317465, upload-time = "2026-09-21T17:55:18.412Z" }, + { url = "https://files.pythonhosted.org/packages/19/0a/714f796f7293a8b1c5c3f465a26996231d5450c54e85d64ef1258c091134/multidict-6.9.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d35a4f1c63f07fbb8c8f9946dea98b21eddf6c57421585f71d91864be3ba2a24", size = 345914, upload-time = "2026-09-21T17:55:20.306Z" }, + { url = "https://files.pythonhosted.org/packages/da/b1/e37fbf769c567be277bcf32df6234035a4384677fcc1bd852752be3d6b93/multidict-6.9.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b5f8771aaaed7f80e84a4e471d2f29ab6721e4595075e54d03ae1ed951b2000a", size = 351163, upload-time = "2026-09-21T17:55:22.21Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5b/db08419c1e1f7c9d60cfd2787b2b517d7ae4ebbda8281b48a33eb5141467/multidict-6.9.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:976fd7689d69ec78d67d31d38d396d8adb562f7e8368279f76aed4aa451fa06d", size = 336881, upload-time = "2026-09-21T17:55:23.699Z" }, + { url = "https://files.pythonhosted.org/packages/9b/07/cc9bc8a62651d2d53ab93ee4993b3a71b7cb78eb8ebfc9c757a5b6698617/multidict-6.9.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:95052e8777a86bae87c0bd0b5ab22d809e3d1d02bf69e3e66ddda5ba75a05805", size = 303405, upload-time = "2026-09-21T17:55:25.305Z" }, + { url = "https://files.pythonhosted.org/packages/b6/0c/8e912afafa70e944dbb8bec4b66ca6e008511395278c0d3dd0e89567536a/multidict-6.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1a8adfcaf96f587ab138476eaddef95f29b8a2a8a9afbfea8d2fd62180995d02", size = 324265, upload-time = "2026-09-21T17:55:26.989Z" }, + { url = "https://files.pythonhosted.org/packages/66/6a/62c2af80fb085e6234805017af857b8e913dfac7a55e9c1349c27768c58a/multidict-6.9.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1a53de2772cfb74559df2eb4456ec4eeb908435ec55a84b69370d9d745d62aa8", size = 322085, upload-time = "2026-09-21T17:55:28.732Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6b/35bf801b336fd960811207203ffdcdc24acc3558b3e7ff2e1c914b141e70/multidict-6.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:0f2ce963299d42fa3f22a90adc0fdf174792ffef5ff4c7ffb68260548fb05580", size = 338107, upload-time = "2026-09-21T17:55:30.303Z" }, + { url = "https://files.pythonhosted.org/packages/80/41/495ef65bf5bba29d142d81b3fe1b8154b919bed70e96491b1e93c3c26f0f/multidict-6.9.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5b30ddf7234e611ca877575b62840e6af5977f92f1f9d532eedbb05a44ff8004", size = 339631, upload-time = "2026-09-21T17:55:32.012Z" }, + { url = "https://files.pythonhosted.org/packages/19/bd/057fdff5f4e04dcd40a960e38f77d19d3c4b67dd243ffa5f43718edb29fc/multidict-6.9.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:63ada7ee2e9345695f9e9bc4c65d72222253f07b1ac94fd0e37555cc6f3c7f60", size = 302080, upload-time = "2026-09-21T17:55:33.817Z" }, + { url = "https://files.pythonhosted.org/packages/3f/de/9ace933ee8dad808632523726f42255b09600087219e3d4ead7369820910/multidict-6.9.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3c95601ed98fad3f6e2f8fe809c3b526b0fab31ef525e00a155e227f3d17f58a", size = 341107, upload-time = "2026-09-21T17:55:35.471Z" }, + { url = "https://files.pythonhosted.org/packages/d8/ac/7c1204406097bfc5c283d4a3287d61166807d189917567df4c1318484fc4/multidict-6.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c148e8b596000dd3e4bfe206e70f3e666be18d72032e0012555f2373c52e35d6", size = 333482, upload-time = "2026-09-21T17:55:37.002Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c0/a70c32ea3299ebe00f44533740cb46905717c51faf29bbd3ce8bb5886d9d/multidict-6.9.1-cp312-cp312-win32.whl", hash = "sha256:f9dad513626a33670f17cddc6078e30e311f444c957e8dbfc5b2b4603c8b4edb", size = 52548, upload-time = "2026-09-21T17:55:38.529Z" }, + { url = "https://files.pythonhosted.org/packages/d7/2e/8c9c2591df01e5692ad1bf92febb082a17b1c6c3a19aa8b7ff49988fd989/multidict-6.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:a16a1dc8529f9e734a41c3b856f3eae7ebacdc061dde3f8a844e0c7889c97203", size = 59622, upload-time = "2026-09-21T17:55:39.86Z" }, + { url = "https://files.pythonhosted.org/packages/d0/95/59f4472ec512bc180fd207899594c7803ece96262ff9aaa3a4b6d7da6940/multidict-6.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:361f7206cf341ba94fb015688f5c8b480f8e63bd58a4c14a48aeca7851a241cc", size = 54930, upload-time = "2026-09-21T17:55:41.155Z" }, + { url = "https://files.pythonhosted.org/packages/be/59/e26cb779be4c591d1a910f59d29aca9fba4de70349840a833beba2652371/multidict-6.9.1-py3-none-any.whl", hash = "sha256:7bf6478188f4e47bf5686e8a33da4ae28bf43b1b2528d9ee144d28492bfac60b", size = 19176, upload-time = "2026-09-21T17:59:03.501Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.19" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/f2/e783ac7f2aeeed14e9e12801f22529cc7e6b7ab80928d6dcce4e9f00922d/multiprocess-0.70.19.tar.gz", hash = "sha256:952021e0e6c55a4a9fe4cd787895b86e239a40e76802a789d6305398d3975897", size = 2079989, upload-time = "2026-01-19T06:47:39.744Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/45/8004d1e6b9185c1a444d6b55ac5682acf9d98035e54386d967366035a03a/multiprocess-0.70.19-py310-none-any.whl", hash = "sha256:97404393419dcb2a8385910864eedf47a3cadf82c66345b44f036420eb0b5d87", size = 134948, upload-time = "2026-01-19T06:47:32.325Z" }, + { url = "https://files.pythonhosted.org/packages/86/c2/dec9722dc3474c164a0b6bcd9a7ed7da542c98af8cabce05374abab35edd/multiprocess-0.70.19-py311-none-any.whl", hash = "sha256:928851ae7973aea4ce0eaf330bbdafb2e01398a91518d5c8818802845564f45c", size = 144457, upload-time = "2026-01-19T06:47:33.711Z" }, + { url = "https://files.pythonhosted.org/packages/71/70/38998b950a97ea279e6bd657575d22d1a2047256caf707d9a10fbce4f065/multiprocess-0.70.19-py312-none-any.whl", hash = "sha256:3a56c0e85dd5025161bac5ce138dcac1e49174c7d8e74596537e729fd5c53c28", size = 150281, upload-time = "2026-01-19T06:47:35.037Z" }, + { url = "https://files.pythonhosted.org/packages/7e/82/69e539c4c2027f1e1697e09aaa2449243085a0edf81ae2c6341e84d769b6/multiprocess-0.70.19-py39-none-any.whl", hash = "sha256:0d4b4397ed669d371c81dcd1ef33fd384a44d6c3de1bd0ca7ac06d837720d3c5", size = 133477, upload-time = "2026-01-19T06:47:38.619Z" }, +] + +[[package]] +name = "narwhals" +version = "2.27.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/21/f64d6b2dbea7bf3f8c38cdc786dcc6ef012ca3d173ad208c782c9a7bedf6/narwhals-2.27.1.tar.gz", hash = "sha256:aed93076a3ea42d9c32c88e4eb5ea422a21937011cbe1f480f9572a523c82094", size = 735013, upload-time = "2026-10-10T06:52:18.113Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/89/5d4c86da1130d9059681e5b6cd7645df5c10279a6a079c5c37dcb2cc6f3f/narwhals-2.27.1-py3-none-any.whl", hash = "sha256:d057df13f5852b8e157596e82eb5e955fad267425df5e420e0ee9863da483b31", size = 483211, upload-time = "2026-10-10T06:52:16.32Z" }, +] + +[[package]] +name = "nest-asyncio" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418, upload-time = "2024-01-21T14:25:19.227Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195, upload-time = "2024-01-21T14:25:17.223Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/95/b0/c7453d0b6e2073c3264468b106ee1563750cecc910965e67357e3698c83e/numpy-2.5.4.tar.gz", hash = "sha256:9a94cf751c9ad8ebaa835bcd3d40dacf8534ad086b88c38029b65123c7999d2a", size = 20866315, upload-time = "2026-10-10T20:05:31.422Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d0/97/ba2074e92b7befea137e77ea8471e768bbd87c339b7e8c9f5a931949f977/numpy-2.5.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c6342f54c67093cae5c0227eb0eb772fdb79f2a2c37a6eb278b9909ee06aa356", size = 17001609, upload-time = "2026-10-10T20:02:40.843Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a9/bac826765e971d8e16e2064e9ac7525fd69b40ac17c905033a7f5442023f/numpy-2.5.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b11e8fda06a7d69f15ebf542660b74466c2e51094800c1fb794f47ad4faeef17", size = 12015718, upload-time = "2026-10-10T20:02:43.45Z" }, + { url = "https://files.pythonhosted.org/packages/31/2f/5ea3570fcb8ccd0882bea99436a513b2c85dad8f774a2057849130a8fb99/numpy-2.5.4-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:9cb18a327b49c5c337f972b03682f6a49855525faaf3c0d3e9c96cd0fd8880a8", size = 5451717, upload-time = "2026-10-10T20:02:46.169Z" }, + { url = "https://files.pythonhosted.org/packages/34/f2/b4fc1bafca03868220b5eaf729d2f21ebd7d7b151c0f9e144fe212bbca35/numpy-2.5.4-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:aec3fc4b32ff82421274f5d205c559c51c840c8df66a78efd7f3612dd005a26a", size = 6789926, upload-time = "2026-10-10T20:02:48.139Z" }, + { url = "https://files.pythonhosted.org/packages/dc/96/8319e2457ae4333c62c815c7006b869a4f60985c1e01024c2f8c6c040fe5/numpy-2.5.4-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fe4d21ab149f15e4e6043dfb0de87e6e5f34ac176cde83060e9802981fca2ac2", size = 15695312, upload-time = "2026-10-10T20:02:50.115Z" }, + { url = "https://files.pythonhosted.org/packages/43/a3/c799c62e19c337e6d3770b08e475887fb30ce8477d3c09efca6b2f0228a6/numpy-2.5.4-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fbde6962867ee75b48b0ee29b2b9372ec5d617799dbaf38e82dc0596f2f7738a", size = 16727283, upload-time = "2026-10-10T20:02:53.186Z" }, + { url = "https://files.pythonhosted.org/packages/39/6b/3604e53fb00314d0dc1b94ec9125a1484f649c0a17480b1f0f0c7a9d6250/numpy-2.5.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:381a7a3d2e65e64c0ec302795ab9dc12bb1e73f150904699c153716177eebdaf", size = 17047890, upload-time = "2026-10-10T20:02:56.038Z" }, + { url = "https://files.pythonhosted.org/packages/4a/7a/e8b58a5289a0d464c52885de47c35a935cdd70c03a4c3ab94a5126416dd0/numpy-2.5.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b89d0aaae2fe498c648f4c4795c084db535af5bd98ef942b2a3681fb74ce8645", size = 18485839, upload-time = "2026-10-10T20:02:59.018Z" }, + { url = "https://files.pythonhosted.org/packages/6f/c9/47094f597015009f310b8c900def59065ef1ff5a6fe7b51fc65ec58ec2c6/numpy-2.5.4-cp312-cp312-win32.whl", hash = "sha256:9968ab7e49b93ac6e1c3b2239732183152c9150f16308d30b66a372cffe3483c", size = 6138936, upload-time = "2026-10-10T20:03:01.626Z" }, + { url = "https://files.pythonhosted.org/packages/12/33/fefe62073dc8acfd0f2b9ed7c003af2f50aa61555e113e6db02b8f79f145/numpy-2.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:a7b1b6353e36a7e50de2973a38d705c88ee93adcf120673cee7f45a4a3fa223a", size = 12573091, upload-time = "2026-10-10T20:03:04.349Z" }, + { url = "https://files.pythonhosted.org/packages/1a/07/161270b0c2eec56e4c905f6d6d22e1b836887b2cb189d3f5820aa588e9dd/numpy-2.5.4-cp312-cp312-win_arm64.whl", hash = "sha256:aa1cce2ff3f8d953de38b76bf44602caeb69f101430208f64a10067f7cb4b1d3", size = 10521630, upload-time = "2026-10-10T20:03:06.767Z" }, +] + +[[package]] +name = "nvidia-ml-py" +version = "13.615.71" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/30/b25216758be3d3e2834825d8193609e2d71c770a8bd7984438c058c90268/nvidia_ml_py-13.615.71.tar.gz", hash = "sha256:bebe4e48f51b1dc75028c0815cb7bfa14a31a5bb80be70c9d980c6036953fc3d", size = 57485, upload-time = "2026-09-25T15:15:28.226Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/a1/1681dfa1c904d4e3e72e51b55a0ff012d50b766843ef832d584abe2113c6/nvidia_ml_py-13.615.71-py3-none-any.whl", hash = "sha256:959bf4adf6fe1308e4bd739e722236b0d1ec8392e2cefad33ff70c311380b9b6", size = 58132, upload-time = "2026-09-25T15:15:26.54Z" }, +] + +[[package]] +name = "opentelemetry-api" +version = "1.45.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, +] + +[[package]] +name = "optuna" +version = "5.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "alembic" }, + { name = "colorlog" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "sqlalchemy" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/6d/7bd33b5ed3a83f1c1517fb20c54c7dbf59e6c76430d9b26d3205074ff6b0/optuna-5.0.0.tar.gz", hash = "sha256:358bb878b7b1e20e90dc944ac4261796dd3d5c2b7860aa960a08fc10e0b5beff", size = 508726, upload-time = "2026-09-07T05:16:21.136Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/e5/7c5e8cdda8c9f0cd8aca0a376dee9cff6b8c30692cf614960d9e80f59689/optuna-5.0.0-py3-none-any.whl", hash = "sha256:5fff892ae6baf4948c810c5b8635ec67e08efb0709b41cb73b14e30391d44720", size = 442352, upload-time = "2026-09-07T05:16:19.943Z" }, +] + +[[package]] +name = "orjson" +version = "3.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/0c/964746fcafbd16f8ff53219ad9f6b412b34f345c75f384ad434ceaadb538/orjson-3.11.9.tar.gz", hash = "sha256:4fef17e1f8722c11587a6ef18e35902450221da0028e65dbaaa543619e68e48f", size = 5599163, upload-time = "2026-05-06T15:11:08.309Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/6d/11867a3ffa3a3608d84a4de51ef4dd0896d6b5cc9132fbe1daf593e677bc/orjson-3.11.9-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:9ef6fe90aadef185c7b128859f40beb24720b4ecea95379fc9000931179c3a49", size = 228515, upload-time = "2026-05-06T15:09:57.265Z" }, + { url = "https://files.pythonhosted.org/packages/24/75/05912954c8b288f34fcf5cd4b9b071cb4f6e77b9961e175e56ebb258089f/orjson-3.11.9-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:e5c9b8f28e726e97d97696c826bc7bea5d71cecd63576dba92924a32c1961291", size = 128409, upload-time = "2026-05-06T15:09:59.063Z" }, + { url = "https://files.pythonhosted.org/packages/ab/86/1c3a47df3bc8191ea9ac51603bbb872a95167a364320c269f2557911f406/orjson-3.11.9-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:26a473dbb4162108b27901492546f83c76fdcea3d0eadff00ae7a07e18dcce09", size = 132106, upload-time = "2026-05-06T15:10:00.798Z" }, + { url = "https://files.pythonhosted.org/packages/d7/cf/b33b5f3e695ae7d63feef9d915c37cc3b8f465493dcd4f8e0b4c697a2366/orjson-3.11.9-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:011382e2a60fda9d46f1cdee31068cfc52ffe952b587d683ec0463002802a0f4", size = 127864, upload-time = "2026-05-06T15:10:02.15Z" }, + { url = "https://files.pythonhosted.org/packages/31/6a/6cf69385a58208024fcb8c014e2141b8ce838aba6492b589f8acfff97fab/orjson-3.11.9-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c2d3dc759490128c5c1711a53eeaa8ee1d437fd0038ffd2b6008abf46db3f882", size = 135213, upload-time = "2026-05-06T15:10:03.515Z" }, + { url = "https://files.pythonhosted.org/packages/e8/f8/0b1bd3e8f2efcdd376af5c8cfd79eaf13f018080c0089c80ebd724e3c7fb/orjson-3.11.9-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d8ea516b3726d190e1b4297e6f4e7a8650347ae053868a18163b4dd3641d1fff", size = 145994, upload-time = "2026-05-06T15:10:05.083Z" }, + { url = "https://files.pythonhosted.org/packages/f3/59/dab79f61044c529d2c81aecdc589b1f833a1c8dec11ba3b1c2498a02ca7e/orjson-3.11.9-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:380cdce7ba24989af81d0a7013d0aaec5d0e2a21734c0e2681b1bc4f141957fe", size = 132744, upload-time = "2026-05-06T15:10:06.853Z" }, + { url = "https://files.pythonhosted.org/packages/0e/a4/82b7a2fe5d8a67a59ed831b24d59a3d46ea7d207b66e1602d376541d94a6/orjson-3.11.9-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be4fa4f0af7fa18951f7ab3fc2148e223af211bf03f59e1c6034ec3f97f21d61", size = 134014, upload-time = "2026-05-06T15:10:08.213Z" }, + { url = "https://files.pythonhosted.org/packages/50/c7/375e83a76851b73b2e39f3bcf0e5a19e2b89bad13e5bca97d0b293d27f24/orjson-3.11.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a8f5f8bc7ce7d59f08d9f99fa510c06496164a24cb5f3d34537dbd9ca30132e2", size = 141509, upload-time = "2026-05-06T15:10:09.595Z" }, + { url = "https://files.pythonhosted.org/packages/7f/7c/49d5d82a3d3097f641f094f552131f1e2723b0b8cb0fa2874ab65ecfffa6/orjson-3.11.9-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:4d7fde5501b944f83b3e665e1b31343ff6e154b15560a16b7130ea1e594a4206", size = 415127, upload-time = "2026-05-06T15:10:11.049Z" }, + { url = "https://files.pythonhosted.org/packages/3a/dc/7446c538590d55f455647e5f3c61fc33f7108714e7afcffa6a2a033f8350/orjson-3.11.9-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:cde1a448023ba7d5bb4c01c5afb48894380b5e4956e0627266526587ef4e535f", size = 148025, upload-time = "2026-05-06T15:10:12.842Z" }, + { url = "https://files.pythonhosted.org/packages/df/e5/4d2d8af06f788329b4f78f8cc3679bb395392fcaa1e4d8d3c33e85308fa4/orjson-3.11.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:71e63adb0e1f1ed5d9e168f50a91ceb93ae6420731d222dc7da5c69409aa47aa", size = 136943, upload-time = "2026-05-06T15:10:14.405Z" }, + { url = "https://files.pythonhosted.org/packages/06/69/850264ccf6d80f6b174620d30a87f65c9b1490aba33fe6b62798e618cad3/orjson-3.11.9-cp312-cp312-win32.whl", hash = "sha256:2d057a602cdd19a0ad680417527c45b6961a095081c0f46fe0e03e304aac6470", size = 131606, upload-time = "2026-05-06T15:10:15.791Z" }, + { url = "https://files.pythonhosted.org/packages/b9/d5/973a43fc9c55e20f2051e9830997649f669be0cb3ca52192087c0143f118/orjson-3.11.9-cp312-cp312-win_amd64.whl", hash = "sha256:59e403b1cc5a676da8eaf31f6254801b7341b3e29efa85f92b48d272637e77be", size = 127101, upload-time = "2026-05-06T15:10:17.129Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ae/495470f0e4a18f73fa10b7f6b84b464ec4cc5291c4e0c7c2a6c400bef006/orjson-3.11.9-cp312-cp312-win_arm64.whl", hash = "sha256:9af678d6488357948f1f84c6cd1c1d397c014e1ae2f98ae082a44eb48f602624", size = 126736, upload-time = "2026-05-06T15:10:18.645Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "2.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "pytz" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846, upload-time = "2025-09-29T23:19:48.856Z" }, + { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618, upload-time = "2025-09-29T23:39:08.659Z" }, + { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212, upload-time = "2025-09-29T23:19:59.765Z" }, + { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693, upload-time = "2025-09-29T23:20:14.098Z" }, + { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002, upload-time = "2025-09-29T23:20:26.76Z" }, + { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971, upload-time = "2025-09-29T23:20:41.344Z" }, + { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722, upload-time = "2025-09-29T23:20:54.139Z" }, +] + +[[package]] +name = "pillow" +version = "12.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819, upload-time = "2026-04-01T14:46:17.687Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279, upload-time = "2026-04-01T14:43:13.246Z" }, + { url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490, upload-time = "2026-04-01T14:43:15.584Z" }, + { url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462, upload-time = "2026-04-01T14:43:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744, upload-time = "2026-04-01T14:43:20.716Z" }, + { url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371, upload-time = "2026-04-01T14:43:23.443Z" }, + { url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215, upload-time = "2026-04-01T14:43:26.758Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783, upload-time = "2026-04-01T14:43:29.56Z" }, + { url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112, upload-time = "2026-04-01T14:43:32.091Z" }, + { url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489, upload-time = "2026-04-01T14:43:34.601Z" }, + { url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129, upload-time = "2026-04-01T14:43:37.213Z" }, + { url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612, upload-time = "2026-04-01T14:43:39.421Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.13.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/91/4a03cfdb03314cfca262921797fff04ff4054bd86a160aed76eddf8aa12b/platformdirs-4.13.3.tar.gz", hash = "sha256:5e567f664eb087ab8521c0179cd8d1bd60857d271136567a39719e28e2d383ce", size = 61559, upload-time = "2026-10-16T01:16:16.573Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" }, +] + +[[package]] +name = "plotly" +version = "6.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "narwhals" }, + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/e6/b768650072837505804bed4790c5449ba348a3b720e27ca7605414e998cd/plotly-6.4.0.tar.gz", hash = "sha256:68c6db2ed2180289ef978f087841148b7efda687552276da15a6e9b92107052a", size = 7012379, upload-time = "2025-11-04T17:59:26.45Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/ae/89b45ccccfeebc464c9233de5675990f75241b8ee4cd63227800fdf577d1/plotly-6.4.0-py3-none-any.whl", hash = "sha256:a1062eafbdc657976c2eedd276c90e184ccd6c21282a5e9ee8f20efca9c9a4c5", size = 9892458, upload-time = "2025-11-04T17:59:22.622Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "prometheus-client" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/23/53/3edb5d68ecf6b38fcbcc1ad28391117d2a322d9a1a3eff04bfdb184d8c3b/prometheus_client-0.23.1.tar.gz", hash = "sha256:6ae8f9081eaaaf153a2e959d2e6c4f4fb57b12ef76c8c7980202f1e57b48b2ce", size = 80481, upload-time = "2025-09-18T20:47:25.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/db/14bafcb4af2139e046d03fd00dea7873e48eafe18b7d2797e73d6681f210/prometheus_client-0.23.1-py3-none-any.whl", hash = "sha256:dd1913e6e76b59cfe44e7a4b83e01afc9873c1bdfd2ed8739f1e76aeca115f99", size = 61145, upload-time = "2025-09-18T20:47:23.875Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/cd/348d58f142aebc4873345c6b31087629182ca6e0f2b3caeaa528cf882eba/propcache-0.5.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b28f41fa3b8c6900457f858ec5b03998f3a6d535fbc1bb2edec5961ea05ec429", size = 87285, upload-time = "2026-09-16T00:14:29.362Z" }, + { url = "https://files.pythonhosted.org/packages/df/f4/f3ffaee281b276da854ac1d7a6a506d26cbc62ea2e623756f1d0a4a1ba1a/propcache-0.5.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:dcbf346a318a5e30063f547630b02bb787ce2f45b6368d5da143660b6a3835d8", size = 50984, upload-time = "2026-09-16T00:14:30.473Z" }, + { url = "https://files.pythonhosted.org/packages/25/88/1d7df7201750b37765ef2b23bc1c526c028dadde80afa0f57a118fc01182/propcache-0.5.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:87a3caecf8095e48dc72f84bfa42e23a848cf410cc9cc13031fba4869b706a21", size = 52460, upload-time = "2026-09-16T00:14:31.692Z" }, + { url = "https://files.pythonhosted.org/packages/83/4f/48865bd02a16ee5236bc46166b2946f37b93e07b0eae355dac0be0b216ca/propcache-0.5.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60a64cbccaa11b7760ce705a14ada17ba459e7ca9f23ba587eb013821032d7ef", size = 251768, upload-time = "2026-09-16T00:14:32.908Z" }, + { url = "https://files.pythonhosted.org/packages/b0/19/3742a5eed62317b03b4002ee865dc9fd720308bdd0da1f29a5786c630311/propcache-0.5.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a74bfa37147cc08fb29df10bd9c16f40fa7f860cd3a6d2fff853323a94f6e17f", size = 257723, upload-time = "2026-09-16T00:14:34.267Z" }, + { url = "https://files.pythonhosted.org/packages/cb/d5/ee6350fb0be9122bb6c67082a876d34b90d980d100c106af4b81023e04f4/propcache-0.5.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a4d7a54719b67338a305dca2ce6aafe366817df94ddfd4b5514374356f5ca546", size = 265597, upload-time = "2026-09-16T00:14:35.56Z" }, + { url = "https://files.pythonhosted.org/packages/85/9f/83a07b6ec0e043c050cfdd35fb0cf1b7897b91d554d6eea293740309afe7/propcache-0.5.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2814ecd8e818f487bee4b0f921bc4d1c176cc5fc71ac0f072d0fa67eda4ac14b", size = 250424, upload-time = "2026-09-16T00:14:36.894Z" }, + { url = "https://files.pythonhosted.org/packages/33/2c/a763a8251f50fba042af0fb1f02bfec4b31381e40aff760db2be7b2e1f84/propcache-0.5.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6af4693716bfb03f1752ef1b30faa593db2c01d5272e9b8564a1549452a979ab", size = 216748, upload-time = "2026-09-16T00:14:38.369Z" }, + { url = "https://files.pythonhosted.org/packages/6a/e2/4d11bea8fd6a777149c6c20645f873952eab5de3a2497aa11648ec9ab6ab/propcache-0.5.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4fbc1a15dc8cd1689508758d626b372b1f09d28d9577667feaf9e6bfcd8efcbc", size = 246533, upload-time = "2026-09-16T00:14:39.82Z" }, + { url = "https://files.pythonhosted.org/packages/9f/36/6683597de4907e70c717e3588c541202c66086a72ff3db58be49de66e72c/propcache-0.5.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:cdee8205a44d0be91bbac4c41b95d86641b72dfc7aef1279400e4fda3f26a937", size = 238173, upload-time = "2026-09-16T00:14:41.259Z" }, + { url = "https://files.pythonhosted.org/packages/85/84/cb08d79f1762daafeb2b030c470cd0c725c97b8ad67412457c6f35c53e9d/propcache-0.5.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:9a2a8a50a93dee0268a860a07fa3b4bd968f8ce4dbd794957da772f395368526", size = 251128, upload-time = "2026-09-16T00:14:42.652Z" }, + { url = "https://files.pythonhosted.org/packages/c2/0d/41b848036db6621370c1f2e5471a7da8149c730f8552a5257567721f4576/propcache-0.5.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:7ffafcbfc7b549ab940047e505c831eabac5e67de53e1bc174adbc5285c55944", size = 214821, upload-time = "2026-09-16T00:14:44.112Z" }, + { url = "https://files.pythonhosted.org/packages/f1/b7/adfae4bf9c63bccf12e2d9690a175c6579047a6eec3b5a6a5f51428c15e2/propcache-0.5.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d1f5a500bfcbb2c0ab85e98a0dcd70f5899d34efe365a0187700369a79603031", size = 254793, upload-time = "2026-09-16T00:14:45.429Z" }, + { url = "https://files.pythonhosted.org/packages/51/6f/eeca9647245d5f92e87d53e5f14335bb42fce1a7e6842c8045b364eded8b/propcache-0.5.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8a235f73d6e020855dc29dff012d920c02ee0feab8d73a24185a7569f4be1161", size = 247134, upload-time = "2026-09-16T00:14:46.976Z" }, + { url = "https://files.pythonhosted.org/packages/5d/a9/424e38838793d37160b4379c702f61c74c598fc6cd17204adbe3c554f7a8/propcache-0.5.4-cp312-cp312-win32.whl", hash = "sha256:b3083bfe87f95c756e610bd8025f26cbd1cd4aaa03a422f2d65efb7a97cd53d8", size = 43073, upload-time = "2026-09-16T00:14:48.338Z" }, + { url = "https://files.pythonhosted.org/packages/58/7b/6e8ef26f6d510a7916064fec68d55fcbfbdf7eb01e377480d66a122152d8/propcache-0.5.4-cp312-cp312-win_amd64.whl", hash = "sha256:98914de2c4d7f0f9f4a8c6ea4bf05841f4175796941e3ef7d47eb718f22311fb", size = 46190, upload-time = "2026-09-16T00:14:49.99Z" }, + { url = "https://files.pythonhosted.org/packages/08/b9/72028c5b56ced97f456de6aefa79435ca64d7f77af78ea8cf3c76fc5195f/propcache-0.5.4-cp312-cp312-win_arm64.whl", hash = "sha256:8876b39961e33d912afe3c1bee18ee564fdad0206f873cc15d522756b7f50737", size = 43075, upload-time = "2026-09-16T00:14:51.155Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "protobuf" +version = "7.36.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/89/5b8517baa72f84a67b8a307ba953c91057af618bf40bf676f3c03551f8f0/protobuf-7.36.2.tar.gz", hash = "sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb", size = 512737, upload-time = "2026-09-17T20:07:59.326Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/72/98342feb672507c8f3a69e34b4fa8961f608edba5c1a48a6f47156d92cb5/protobuf-7.36.2-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e", size = 456039, upload-time = "2026-09-17T20:07:51.542Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ea/91fdf7c2b8bbd49cde056f00a9df6773532987e1c00fe2830b895af95c7e/protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e", size = 344219, upload-time = "2026-09-17T20:07:52.914Z" }, + { url = "https://files.pythonhosted.org/packages/17/ab/5fd5f8ece73fad885c5a09aa849b32d70472f954ba3a92d3bb5974ea953b/protobuf-7.36.2-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf", size = 357223, upload-time = "2026-09-17T20:07:53.985Z" }, + { url = "https://files.pythonhosted.org/packages/db/f3/3996583dd2906297a637af12114deddf7658af6e683fedb83be061983fb5/protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2", size = 343223, upload-time = "2026-09-17T20:07:54.931Z" }, + { url = "https://files.pythonhosted.org/packages/fc/1b/dcc64f358fcb51811b58ae40b3d28f820725f116d86487cc20bd4b130701/protobuf-7.36.2-cp310-abi3-win32.whl", hash = "sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728", size = 442998, upload-time = "2026-09-17T20:07:55.826Z" }, + { url = "https://files.pythonhosted.org/packages/8a/55/b77bda4e5e5f5971fb51b07663694690e9afdb9402136c16a522bd621cad/protobuf-7.36.2-cp310-abi3-win_amd64.whl", hash = "sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353", size = 456514, upload-time = "2026-09-17T20:07:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" }, +] + +[[package]] +name = "psutil" +version = "7.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2a/80/336820c1ad9286a4ded7e845b2eccfcb27851ab8ac6abece774a6ff4d3de/psutil-7.0.0.tar.gz", hash = "sha256:7be9c3eba38beccb6495ea33afd982a44074b78f28c434a1f51cc07fd315c456", size = 497003, upload-time = "2025-02-13T21:54:07.946Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/e6/2d26234410f8b8abdbf891c9da62bee396583f713fb9f3325a4760875d22/psutil-7.0.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25", size = 238051, upload-time = "2025-02-13T21:54:12.36Z" }, + { url = "https://files.pythonhosted.org/packages/04/8b/30f930733afe425e3cbfc0e1468a30a18942350c1a8816acfade80c005c4/psutil-7.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:39db632f6bb862eeccf56660871433e111b6ea58f2caea825571951d4b6aa3da", size = 239535, upload-time = "2025-02-13T21:54:16.07Z" }, + { url = "https://files.pythonhosted.org/packages/2a/ed/d362e84620dd22876b55389248e522338ed1bf134a5edd3b8231d7207f6d/psutil-7.0.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fcee592b4c6f146991ca55919ea3d1f8926497a713ed7faaf8225e174581e91", size = 275004, upload-time = "2025-02-13T21:54:18.662Z" }, + { url = "https://files.pythonhosted.org/packages/bf/b9/b0eb3f3cbcb734d930fdf839431606844a825b23eaf9a6ab371edac8162c/psutil-7.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b1388a4f6875d7e2aff5c4ca1cc16c545ed41dd8bb596cefea80111db353a34", size = 277986, upload-time = "2025-02-13T21:54:21.811Z" }, + { url = "https://files.pythonhosted.org/packages/eb/a2/709e0fe2f093556c17fbafda93ac032257242cabcc7ff3369e2cb76a97aa/psutil-7.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5f098451abc2828f7dc6b58d44b532b22f2088f4999a937557b603ce72b1993", size = 279544, upload-time = "2025-02-13T21:54:24.68Z" }, + { url = "https://files.pythonhosted.org/packages/50/e6/eecf58810b9d12e6427369784efe814a1eec0f492084ce8eb8f4d89d6d61/psutil-7.0.0-cp37-abi3-win32.whl", hash = "sha256:ba3fcef7523064a6c9da440fc4d6bd07da93ac726b5733c29027d7dc95b39d99", size = 241053, upload-time = "2025-02-13T21:54:34.31Z" }, + { url = "https://files.pythonhosted.org/packages/50/1b/6921afe68c74868b4c9fa424dad3be35b095e16687989ebbb50ce4fceb7c/psutil-7.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:4cf3d4eb1aa9b348dec30105c55cd9b7d4629285735a102beb4441e38db90553", size = 244885, upload-time = "2025-02-13T21:54:37.486Z" }, +] + +[[package]] +name = "pyarrow" +version = "26.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/34/17c34cb38e5d940e38f0f0d9fdfa0e8a506676409ea9b85aff7e3079f831/pyarrow-26.0.0.tar.gz", hash = "sha256:0cccd36e00ea3afeb52ded61f2721ce71f604853d70c45365c58324eb773d6ae", size = 1239433, upload-time = "2026-10-09T08:26:25.315Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/60/6793778f2617cce469383dac0ba08c4f2401cf342df0c7b9ca53939d9b46/pyarrow-26.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:90ddaf7c625307ad52f31a9b25c34fe5e4897c7529ee3481135822b2b6842ff1", size = 36333953, upload-time = "2026-10-09T08:14:00.387Z" }, + { url = "https://files.pythonhosted.org/packages/db/81/f944cc63ce8a753e5fbff25de6d1d475ebd7fffdf9cf98c65130294fc896/pyarrow-26.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:ee341973f78a0b46e073d065e88e75026a9c584051e97f98a0d05d96c6bac7dd", size = 38688456, upload-time = "2026-10-09T08:14:04.344Z" }, + { url = "https://files.pythonhosted.org/packages/f5/2d/7e5c722fa5d5d9f3b75e62fe11694b34217664d4f05ac88031197166b277/pyarrow-26.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:01c863a18bd9c8412453dd0d92de6d0ee7b2b3d6fb079d9734a4b2a3c8bd4453", size = 50867603, upload-time = "2026-10-09T08:14:09.115Z" }, + { url = "https://files.pythonhosted.org/packages/88/e4/9cd356d906e71bd79b0c3fc5c9a54e01a0020dcf14c152ccfbcb503c7298/pyarrow-26.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6a628922ba20705fa964ca73e4ef959c2fb2f14b9bbec5589a6a1e68e6257c85", size = 53931932, upload-time = "2026-10-09T08:14:24.051Z" }, + { url = "https://files.pythonhosted.org/packages/bb/e4/5bae3133b7fe04c24907a20f3bc1fba388cbbde659199e7b76445982047a/pyarrow-26.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:954d971b363b16ee41f89389a4053315dc71265f2ce5c2468eb0a910b1166268", size = 54444720, upload-time = "2026-10-09T08:14:31.214Z" }, + { url = "https://files.pythonhosted.org/packages/ba/b4/ee422493bb6dafdbef776cfe2c2a73106a1063a79bf4e78d1e5f51176885/pyarrow-26.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5d5768d03426abe6526d5274adefa00abf00a7f81118c46e98b5a46390f5549e", size = 57388949, upload-time = "2026-10-09T08:14:38.964Z" }, + { url = "https://files.pythonhosted.org/packages/54/3c/1783aab1dac28e175dcf26dfc7123725efc474caecaed91e8a34cb89cad0/pyarrow-26.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:cc903e1069e9dd5e9dcf780324c0112e27e051e422ecfaff574fb33ed65d9160", size = 28567581, upload-time = "2026-10-09T08:14:44.279Z" }, +] + +[[package]] +name = "pycparser" +version = "3.11" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/da/a8/c5fdbeee588bb8ada9458774f43adf1bdd30bd59157055142183e769a024/pycparser-3.11.tar.gz", hash = "sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc", size = 113796, upload-time = "2026-10-09T12:56:59.539Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/11/0e6f11117525ff0eec40ebac3d313376f102df93ca44ad9e893ee85e4f89/pycparser-3.11-py3-none-any.whl", hash = "sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80", size = 51178, upload-time = "2026-10-09T12:56:58.131Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7c/0b/8e10b2e693af8ec54346a14caf36221334775975a747c9ceaa3f8371d96d/pydantic-2.14.1.tar.gz", hash = "sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26", size = 900362, upload-time = "2026-10-11T18:37:55.396Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/ea/a56b9fe5066f3537b7882f77e9c5dfb26d8c2eefdaed9b5fc73d57b4dc22/pydantic-2.14.1-py3-none-any.whl", hash = "sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454", size = 488106, upload-time = "2026-10-11T18:37:53.437Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/24/af4ec4be49fbc810f35b0bdcacc3d433b56bbfa469fd3bfd4ae116cd9bf1/pydantic_core-2.50.1.tar.gz", hash = "sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09", size = 513515, upload-time = "2026-10-11T18:35:44.82Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/94/101b49a6c63f99586755690696eae14532772587d9e39e93f7b8d28a49da/pydantic_core-2.50.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0", size = 2222428, upload-time = "2026-10-11T18:32:20.228Z" }, + { url = "https://files.pythonhosted.org/packages/db/a3/f8b1b39349c33037c73d7a1b794c9c29d8f07d5bd2b74399c1375a529cc6/pydantic_core-2.50.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e", size = 2025779, upload-time = "2026-10-11T18:32:21.723Z" }, + { url = "https://files.pythonhosted.org/packages/d2/2d/862a7d115305cc621358e51ba13f296e0ffdf4fbd984be9f63bc7862730b/pydantic_core-2.50.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41", size = 2048429, upload-time = "2026-10-11T18:32:23.3Z" }, + { url = "https://files.pythonhosted.org/packages/c0/7d/fed95d18bf2b5abe2d5ab2bbec4184bfc22b6805994a33ccdae8edffd25a/pydantic_core-2.50.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3", size = 2173274, upload-time = "2026-10-11T18:32:24.697Z" }, + { url = "https://files.pythonhosted.org/packages/93/1e/c6f22ceac65dc3d291ff79bea0eb74cbd1de8b128f01fee48af03bcea1e1/pydantic_core-2.50.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5", size = 2360403, upload-time = "2026-10-11T18:32:26.281Z" }, + { url = "https://files.pythonhosted.org/packages/2c/97/190b5b6bfe4c72f265feb657913eb30749193927a5ad7b83cfa7866a25a2/pydantic_core-2.50.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6", size = 2439799, upload-time = "2026-10-11T18:32:27.844Z" }, + { url = "https://files.pythonhosted.org/packages/90/24/48cd98388e4ac2c08d0800af36d15413db15e20387f1038123a2c86cb2f6/pydantic_core-2.50.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e", size = 2160157, upload-time = "2026-10-11T18:32:29.553Z" }, + { url = "https://files.pythonhosted.org/packages/00/86/d909133d0b9979ed14c20f110f21124a0e346caf071bd66ac5af3009062b/pydantic_core-2.50.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a", size = 2229523, upload-time = "2026-10-11T18:32:31.027Z" }, + { url = "https://files.pythonhosted.org/packages/90/31/4b43f08131b2098e73a852fd932063385f3103b33839fd9d1abdb89e673d/pydantic_core-2.50.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9", size = 2242700, upload-time = "2026-10-11T18:32:32.622Z" }, + { url = "https://files.pythonhosted.org/packages/88/77/de39658569dc7a4c293d110a89629f61145e7538f00d1e4280c28debefd3/pydantic_core-2.50.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff", size = 2278452, upload-time = "2026-10-11T18:32:34.165Z" }, + { url = "https://files.pythonhosted.org/packages/46/bd/1eeb9e4e791e81210ef9096f58080b32ba15b5b13c108d50aaa3f8ce9f73/pydantic_core-2.50.1-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4", size = 2450098, upload-time = "2026-10-11T18:32:35.547Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e6/b2accfdff17e5a88d6358536702146de00f9339adaa4d5bbe1ee93cb4832/pydantic_core-2.50.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2", size = 2476839, upload-time = "2026-10-11T18:32:37.119Z" }, + { url = "https://files.pythonhosted.org/packages/3b/7e/c8a83eb5d2cd42c2e13507150fb777b1edea5a018adc9cbf2858a1d08285/pydantic_core-2.50.1-cp312-cp312-win32.whl", hash = "sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e", size = 2101425, upload-time = "2026-10-11T18:32:38.593Z" }, + { url = "https://files.pythonhosted.org/packages/c5/17/8bbd530b8659e9d963f5b16f6cb8e159f4cd174b4d6304e48969ab12dba8/pydantic_core-2.50.1-cp312-cp312-win_amd64.whl", hash = "sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498", size = 2172522, upload-time = "2026-10-11T18:32:40.112Z" }, + { url = "https://files.pythonhosted.org/packages/af/9f/a79d690b127e4e3cff143d031538ab9aa715f6b2fbeecbd07cd6f2bf9fb7/pydantic_core-2.50.1-cp312-cp312-win_arm64.whl", hash = "sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1", size = 2161366, upload-time = "2026-10-11T18:32:41.606Z" }, + { url = "https://files.pythonhosted.org/packages/a5/09/1bcf160f3cd6333e2a76982fae5963e5032de0bcaaba38464223dc266bfe/pydantic_core-2.50.1-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242", size = 2217070, upload-time = "2026-10-11T18:35:15.688Z" }, + { url = "https://files.pythonhosted.org/packages/3d/81/f02de95eec7794dfc7a5bc69a834f0e834b31b3009014ce6de903855f775/pydantic_core-2.50.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5", size = 2039027, upload-time = "2026-10-11T18:35:18.07Z" }, + { url = "https://files.pythonhosted.org/packages/4d/16/227746ed3771d9bf2304568b55134849ece34e13b38b1d76de763015c77f/pydantic_core-2.50.1-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295", size = 2109009, upload-time = "2026-10-11T18:35:20.218Z" }, + { url = "https://files.pythonhosted.org/packages/e5/b9/7664d1592a0e5a74903f357cd5b28ceb7336f3473256c5a4e8c8432f1881/pydantic_core-2.50.1-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61", size = 2269883, upload-time = "2026-10-11T18:35:22.48Z" }, +] + +[[package]] +name = "pydantic-settings" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/3b/a5d2294799b53b448319978cfb5bd139d5a9d45e862af91661614f14c922/pydantic_settings-2.16.0.tar.gz", hash = "sha256:5b6c578049ede4db0e2ef3b4eaa4ad4069cfa9211f83fb38df899dfade50a614", size = 301031, upload-time = "2026-10-14T12:44:09.998Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/f4/b987bf8c51e5b19a95fa66d1ee596074141e085d9c2ddf97920803c7029b/pydantic_settings-2.16.0-py3-none-any.whl", hash = "sha256:7e73acf7f61936a15e5a3b6eedaea29f133357faf7272f2607ba479b049dd7f2", size = 80364, upload-time = "2026-10-14T12:44:08.233Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "pytest-timeout" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "python-dotenv" +version = "1.2.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/74/26/2fbeedb218a787a5eea551c7532cac4e009f83d689dd2faa0d0353473f86/python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0", size = 60824, upload-time = "2026-10-01T05:36:10Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, +] + +[[package]] +name = "pytz" +version = "2026.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/14/21/d83d6ef28c4c912c4bb4d1dcf591f7b8c6bde87b9c66f9f454677314e16d/pytz-2026.5.tar.gz", hash = "sha256:fa23724b9c486543b9ff54a327ee7569ac83ade54bb9afd0fc18676620401c86", size = 318572, upload-time = "2026-10-04T02:37:58.719Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/ef/c66110d46fb800dda0bf33164182dfadabe26a90e4476844d502a23dca8e/pytz-2026.5-py2.py3-none-any.whl", hash = "sha256:e658af3757f9e26a9d25dd2aff38335acd92bc9104f890a894b2c1ba28311b03", size = 506342, upload-time = "2026-10-04T02:37:56.814Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, +] + +[[package]] +name = "pyzmq" +version = "26.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "implementation_name == 'pypy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/11/b9213d25230ac18a71b39b3723494e57adebe36e066397b961657b3b41c1/pyzmq-26.4.0.tar.gz", hash = "sha256:4bd13f85f80962f91a651a7356fe0472791a5f7a92f227822b5acf44795c626d", size = 278293, upload-time = "2025-04-04T12:05:44.049Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/44/a778555ebfdf6c7fc00816aad12d185d10a74d975800341b1bc36bad1187/pyzmq-26.4.0-cp312-cp312-macosx_10_15_universal2.whl", hash = "sha256:5227cb8da4b6f68acfd48d20c588197fd67745c278827d5238c707daf579227b", size = 1341586, upload-time = "2025-04-04T12:03:41.954Z" }, + { url = "https://files.pythonhosted.org/packages/9c/4f/f3a58dc69ac757e5103be3bd41fb78721a5e17da7cc617ddb56d973a365c/pyzmq-26.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1c07a7fa7f7ba86554a2b1bef198c9fed570c08ee062fd2fd6a4dcacd45f905", size = 665880, upload-time = "2025-04-04T12:03:43.45Z" }, + { url = "https://files.pythonhosted.org/packages/fe/45/50230bcfb3ae5cb98bee683b6edeba1919f2565d7cc1851d3c38e2260795/pyzmq-26.4.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ae775fa83f52f52de73183f7ef5395186f7105d5ed65b1ae65ba27cb1260de2b", size = 902216, upload-time = "2025-04-04T12:03:45.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/59/56bbdc5689be5e13727491ad2ba5efd7cd564365750514f9bc8f212eef82/pyzmq-26.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:66c760d0226ebd52f1e6b644a9e839b5db1e107a23f2fcd46ec0569a4fdd4e63", size = 859814, upload-time = "2025-04-04T12:03:47.188Z" }, + { url = "https://files.pythonhosted.org/packages/81/b1/57db58cfc8af592ce94f40649bd1804369c05b2190e4cbc0a2dad572baeb/pyzmq-26.4.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:ef8c6ecc1d520debc147173eaa3765d53f06cd8dbe7bd377064cdbc53ab456f5", size = 855889, upload-time = "2025-04-04T12:03:49.223Z" }, + { url = "https://files.pythonhosted.org/packages/e8/92/47542e629cbac8f221c230a6d0f38dd3d9cff9f6f589ed45fdf572ffd726/pyzmq-26.4.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:3150ef4084e163dec29ae667b10d96aad309b668fac6810c9e8c27cf543d6e0b", size = 1197153, upload-time = "2025-04-04T12:03:50.591Z" }, + { url = "https://files.pythonhosted.org/packages/07/e5/b10a979d1d565d54410afc87499b16c96b4a181af46e7645ab4831b1088c/pyzmq-26.4.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:4448c9e55bf8329fa1dcedd32f661bf611214fa70c8e02fee4347bc589d39a84", size = 1507352, upload-time = "2025-04-04T12:03:52.473Z" }, + { url = "https://files.pythonhosted.org/packages/ab/58/5a23db84507ab9c01c04b1232a7a763be66e992aa2e66498521bbbc72a71/pyzmq-26.4.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e07dde3647afb084d985310d067a3efa6efad0621ee10826f2cb2f9a31b89d2f", size = 1406834, upload-time = "2025-04-04T12:03:54Z" }, + { url = "https://files.pythonhosted.org/packages/22/74/aaa837b331580c13b79ac39396601fb361454ee184ca85e8861914769b99/pyzmq-26.4.0-cp312-cp312-win32.whl", hash = "sha256:ba034a32ecf9af72adfa5ee383ad0fd4f4e38cdb62b13624278ef768fe5b5b44", size = 577992, upload-time = "2025-04-04T12:03:55.815Z" }, + { url = "https://files.pythonhosted.org/packages/30/0f/55f8c02c182856743b82dde46b2dc3e314edda7f1098c12a8227eeda0833/pyzmq-26.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:056a97aab4064f526ecb32f4343917a4022a5d9efb6b9df990ff72e1879e40be", size = 640466, upload-time = "2025-04-04T12:03:57.231Z" }, + { url = "https://files.pythonhosted.org/packages/e4/29/073779afc3ef6f830b8de95026ef20b2d1ec22d0324d767748d806e57379/pyzmq-26.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:2f23c750e485ce1eb639dbd576d27d168595908aa2d60b149e2d9e34c9df40e0", size = 556342, upload-time = "2025-04-04T12:03:59.218Z" }, +] + +[[package]] +name = "regex" +version = "2026.9.29" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/f2/af1da9d3ceed77bfcdce40427d49ba0be94e4fe84245e3bfef68c10e75b6/regex-2026.9.29.tar.gz", hash = "sha256:8b5fcc4771732191b2b7d1dd68d8f0353f47f8d90b6150f6dce58bf1112442cb", size = 419199, upload-time = "2026-09-29T00:49:58.298Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/84/48/3fdcde9a0baa84d7d25571223265d6e434e114763b438601d54a8028bf3e/regex-2026.9.29-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dc79d36d0618752265f0d575915bdc5c5130ecb9c9f6b3bcefeae32e4bdfafcf", size = 497903, upload-time = "2026-09-29T00:46:38.938Z" }, + { url = "https://files.pythonhosted.org/packages/2e/1c/4ee3e97c76f53940488dfe7a7e18705e78daac8cd7fb161d246b9e328449/regex-2026.9.29-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3a21a9509d0ee88e7a70e1ad228cd2f0e0fd1e187458db132e8a8d18c97daf9d", size = 296416, upload-time = "2026-09-29T00:46:40.406Z" }, + { url = "https://files.pythonhosted.org/packages/37/14/f3f0ba083d2094392d5eabf56db5ea6ba469fd6e927afd187042054ea68a/regex-2026.9.29-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f57dc6b8fef170f105d2cf5cdce254f47b137d7755086cf7050f47e16582abba", size = 293633, upload-time = "2026-09-29T00:46:41.959Z" }, + { url = "https://files.pythonhosted.org/packages/c9/72/67e7a8ce17f1aea49df215564048efb49cc8c2b31a0e0fc30f36838f8516/regex-2026.9.29-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f93bc1c3486ef3747e07c9d7c1d0a147b8fbaab975f80e348aed6f71309dfaca", size = 805885, upload-time = "2026-09-29T00:46:43.373Z" }, + { url = "https://files.pythonhosted.org/packages/f6/78/25436bcfd4d2260b4b4090094d55d7ab53ec8a1ab4865a0b8bcb33c7d5c0/regex-2026.9.29-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e1d3a4cb7993b708f0ada8d0c84590efd853f169e7147d2202c9da503180242", size = 878344, upload-time = "2026-09-29T00:46:45.328Z" }, + { url = "https://files.pythonhosted.org/packages/97/e6/a09ec3a23ae41d6179880e67f0aace9284b2d95f2d7b326eff203f8eec5e/regex-2026.9.29-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dabee8f4935e731fb46b2a3091bdda0d3d94b3bbfb907d2b4f12eefce4009619", size = 919181, upload-time = "2026-09-29T00:46:47.041Z" }, + { url = "https://files.pythonhosted.org/packages/26/83/d2fbd2e4e3afb1167daa825187d196f313cbaa1a4768f311fb041bb0e3d2/regex-2026.9.29-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:39ab5894d971f9ac68baa6eca5c50387db579cfcacf36ae8df3feceb1815e6d0", size = 807783, upload-time = "2026-09-29T00:46:48.894Z" }, + { url = "https://files.pythonhosted.org/packages/46/0b/eb429a7016610d44fc89a597163f8c9127505f0d7dc724dc9effbb6a3ac0/regex-2026.9.29-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c1a9a6651197fbed6f0212591418b9def774fc3f8324f78d1bf0e6a63e5f8aa1", size = 783465, upload-time = "2026-09-29T00:46:50.64Z" }, + { url = "https://files.pythonhosted.org/packages/1b/07/58a3c0153c7476898430f6a7cf3d9062a1d17fbea4f43399ecaf411c7b4c/regex-2026.9.29-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:87fb80cbe3557e27e7b28b995c2b2eedf689b8886f941ab93e0e288f0976518a", size = 793519, upload-time = "2026-09-29T00:46:52.396Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/161b94d39164520e21a7befe0245569bf7fda4c7cf1fc4e2df2b5def49da/regex-2026.9.29-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3c5c2ef13797466aa64170cbb66ad98a32351dd4127694cea7199f80f213750d", size = 869293, upload-time = "2026-09-29T00:46:54.128Z" }, + { url = "https://files.pythonhosted.org/packages/8f/07/3b02ed829aa2decdc1955d222bd1e2f99d1c8bb4873bbb9a66b2f0a36bff/regex-2026.9.29-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:59b49507f47479e299a9e1bc41b5cb83a7afda0540625f1dbae886615978acbf", size = 770239, upload-time = "2026-09-29T00:46:56.106Z" }, + { url = "https://files.pythonhosted.org/packages/42/5b/ba61f6fe062eb8562e742367d177bb75370434138ef6c9d2a27114f8d613/regex-2026.9.29-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:0dd8af32e9f7b56b7f95cc1fd79b23054c3bdc172392ae560acc24d57b7ffe71", size = 861973, upload-time = "2026-09-29T00:46:57.665Z" }, + { url = "https://files.pythonhosted.org/packages/cc/27/767259b20e8a842948990f5e99138d6c077248fd42f8b5468b1d9ca4b814/regex-2026.9.29-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:db5e82ba15c142425b8406690032df89e39cca4a2e8afbbb9a3d84edc2373ac3", size = 796470, upload-time = "2026-09-29T00:46:59.236Z" }, + { url = "https://files.pythonhosted.org/packages/a0/05/2566c4ba849b68a8ab81a6bf428fa79d20aae7ddee83979103c0381df254/regex-2026.9.29-cp312-cp312-win32.whl", hash = "sha256:d0c3082bf79bcd6a614d55916590ad4b8f93200e10b97f463ea5d9d07c9b5f23", size = 269327, upload-time = "2026-09-29T00:47:01.135Z" }, + { url = "https://files.pythonhosted.org/packages/93/19/489bc8db91196381c935752df01ba3f607140daece33b78d88573f028e64/regex-2026.9.29-cp312-cp312-win_amd64.whl", hash = "sha256:fdd88ed5e20b1bcdd234421e454962c971aa44b653bdb7f1ea9ef683e90fb649", size = 280334, upload-time = "2026-09-29T00:47:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/0b/47/fb88ba779d0e5e7d4b0ec1aceeb13845948a2cb876bd572a2d1dfdba090b/regex-2026.9.29-cp312-cp312-win_arm64.whl", hash = "sha256:4fe97894d1b306c919b4e50def1e6f6c522f4d03a7283811f4d108f1ce5d3ac2", size = 279614, upload-time = "2026-09-29T00:47:06.541Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "retrying" +version = "1.4.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c8/5a/b17e1e257d3e6f2e7758930e1256832c9ddd576f8631781e6a072914befa/retrying-1.4.2.tar.gz", hash = "sha256:d102e75d53d8d30b88562d45361d6c6c934da06fab31bd81c0420acb97a8ba39", size = 11411, upload-time = "2025-08-03T03:35:25.189Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/f3/6cd296376653270ac1b423bb30bd70942d9916b6978c6f40472d6ac038e7/retrying-1.4.2-py3-none-any.whl", hash = "sha256:bbc004aeb542a74f3569aeddf42a2516efefcdaff90df0eb38fbfbf19f179f59", size = 10859, upload-time = "2025-08-03T03:35:23.829Z" }, +] + +[[package]] +name = "rich" +version = "14.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fe/75/af448d8e52bf1d8fa6a9d089ca6c07ff4453d86c65c145d0a300bb073b9b/rich-14.1.0.tar.gz", hash = "sha256:e497a48b844b0320d45007cdebfeaeed8db2a4f4bcf49f15e455cfc4af11eaa8", size = 224441, upload-time = "2025-07-25T07:32:58.125Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/30/3c4d035596d3cf444529e0b2953ad0466f6049528a879d27534700580395/rich-14.1.0-py3-none-any.whl", hash = "sha256:536f5f1785986d6dbdea3c75205c473f970777b4a0d6c6dd1b696aa05a3fa04f", size = 243368, upload-time = "2025-07-25T07:32:56.73Z" }, +] + +[[package]] +name = "rich-rst" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pygments" }, + { name = "rich" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cf/0e/faf7c7e36630561e3e9611730c47510cd972dd5fde8f95941ff78f76accd/rich_rst-2.2.0.tar.gz", hash = "sha256:b1e6a67f8f694a6f36035624bf73e2b1a0a4be13edaf3ba5e654d9758b61073a", size = 326270, upload-time = "2026-09-27T19:12:42.163Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/4e/716b42bf066e180c1235783b46f095a5d871d05dca7006d2295aac29c491/rich_rst-2.2.0-py3-none-any.whl", hash = "sha256:1ea1c43813dc4a8d86475fce27ffb74e0ada3d4656c9f8130ba2a59868055fe9", size = 279274, upload-time = "2026-09-27T19:12:40.548Z" }, +] + +[[package]] +name = "ruamel-yaml" +version = "0.18.17" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ruamel-yaml-clib", marker = "platform_python_implementation == 'CPython'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3a/2b/7a1f1ebcd6b3f14febdc003e658778d81e76b40df2267904ee6b13f0c5c6/ruamel_yaml-0.18.17.tar.gz", hash = "sha256:9091cd6e2d93a3a4b157ddb8fabf348c3de7f1fb1381346d985b6b247dcd8d3c", size = 149602, upload-time = "2025-12-17T20:02:55.757Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/fe/b6045c782f1fd1ae317d2a6ca1884857ce5c20f59befe6ab25a8603c43a7/ruamel_yaml-0.18.17-py3-none-any.whl", hash = "sha256:9c8ba9eb3e793efdf924b60d521820869d5bf0cb9c6f1b82d82de8295e290b9d", size = 121594, upload-time = "2025-12-17T20:02:07.657Z" }, +] + +[[package]] +name = "ruamel-yaml-clib" +version = "0.2.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ea/97/60fda20e2fb54b83a61ae14648b0817c8f5d84a3821e40bfbdae1437026a/ruamel_yaml_clib-0.2.15.tar.gz", hash = "sha256:46e4cc8c43ef6a94885f72512094e482114a8a706d3c555a34ed4b0d20200600", size = 225794, upload-time = "2025-11-16T16:12:59.761Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/4b/5fde11a0722d676e469d3d6f78c6a17591b9c7e0072ca359801c4bd17eee/ruamel_yaml_clib-0.2.15-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cb15a2e2a90c8475df45c0949793af1ff413acfb0a716b8b94e488ea95ce7cff", size = 149088, upload-time = "2025-11-16T16:13:22.836Z" }, + { url = "https://files.pythonhosted.org/packages/85/82/4d08ac65ecf0ef3b046421985e66301a242804eb9a62c93ca3437dc94ee0/ruamel_yaml_clib-0.2.15-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:64da03cbe93c1e91af133f5bec37fd24d0d4ba2418eaf970d7166b0a26a148a2", size = 134553, upload-time = "2025-11-16T16:13:24.151Z" }, + { url = "https://files.pythonhosted.org/packages/b9/cb/22366d68b280e281a932403b76da7a988108287adff2bfa5ce881200107a/ruamel_yaml_clib-0.2.15-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f6d3655e95a80325b84c4e14c080b2470fe4f33b6846f288379ce36154993fb1", size = 737468, upload-time = "2025-11-16T20:22:47.335Z" }, + { url = "https://files.pythonhosted.org/packages/71/73/81230babf8c9e33770d43ed9056f603f6f5f9665aea4177a2c30ae48e3f3/ruamel_yaml_clib-0.2.15-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71845d377c7a47afc6592aacfea738cc8a7e876d586dfba814501d8c53c1ba60", size = 753349, upload-time = "2025-11-16T16:13:26.269Z" }, + { url = "https://files.pythonhosted.org/packages/61/62/150c841f24cda9e30f588ef396ed83f64cfdc13b92d2f925bb96df337ba9/ruamel_yaml_clib-0.2.15-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:11e5499db1ccbc7f4b41f0565e4f799d863ea720e01d3e99fa0b7b5fcd7802c9", size = 788211, upload-time = "2025-11-16T16:13:27.441Z" }, + { url = "https://files.pythonhosted.org/packages/30/93/e79bd9cbecc3267499d9ead919bd61f7ddf55d793fb5ef2b1d7d92444f35/ruamel_yaml_clib-0.2.15-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4b293a37dc97e2b1e8a1aec62792d1e52027087c8eea4fc7b5abd2bdafdd6642", size = 743203, upload-time = "2025-11-16T16:13:28.671Z" }, + { url = "https://files.pythonhosted.org/packages/8d/06/1eb640065c3a27ce92d76157f8efddb184bd484ed2639b712396a20d6dce/ruamel_yaml_clib-0.2.15-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:512571ad41bba04eac7268fe33f7f4742210ca26a81fe0c75357fa682636c690", size = 747292, upload-time = "2025-11-16T20:22:48.584Z" }, + { url = "https://files.pythonhosted.org/packages/a5/21/ee353e882350beab65fcc47a91b6bdc512cace4358ee327af2962892ff16/ruamel_yaml_clib-0.2.15-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5e9f630c73a490b758bf14d859a39f375e6999aea5ddd2e2e9da89b9953486a", size = 771624, upload-time = "2025-11-16T16:13:29.853Z" }, + { url = "https://files.pythonhosted.org/packages/57/34/cc1b94057aa867c963ecf9ea92ac59198ec2ee3a8d22a126af0b4d4be712/ruamel_yaml_clib-0.2.15-cp312-cp312-win32.whl", hash = "sha256:f4421ab780c37210a07d138e56dd4b51f8642187cdfb433eb687fe8c11de0144", size = 100342, upload-time = "2025-11-16T16:13:31.067Z" }, + { url = "https://files.pythonhosted.org/packages/b3/e5/8925a4208f131b218f9a7e459c0d6fcac8324ae35da269cb437894576366/ruamel_yaml_clib-0.2.15-cp312-cp312-win_amd64.whl", hash = "sha256:2b216904750889133d9222b7b873c199d48ecbb12912aca78970f84a5aa1a4bc", size = 119013, upload-time = "2025-11-16T16:13:32.164Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scipy" +version = "1.18.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7e/74/66de6258867beb2ef08f35f9f2ac017a52cacd5081714d239ff1a442d458/scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307", size = 30781235, upload-time = "2026-08-21T23:28:50.599Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/f7/240c110c08693826b4513a52f5717d62ec7c7af72f2920821247c03b17b3/scipy-1.18.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:457fd7a2a8edeb044ab6ffbc0aa03ff6cd18491356e5e0c834d76ce621b916d1", size = 31111061, upload-time = "2026-08-21T23:23:44.522Z" }, + { url = "https://files.pythonhosted.org/packages/05/4a/78c6285577c375e7cf27277ea8ee6961224327f1e1a0c44af5f17f23635c/scipy-1.18.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:e708533e8b2ae2497d65346538a7dcc92814410b25b81432eac66de0f2af8265", size = 28733332, upload-time = "2026-08-21T23:23:50.015Z" }, + { url = "https://files.pythonhosted.org/packages/a5/f6/a5b82f8abbe14d134691b8b903696f701d25a081353a29dc655c364d9e62/scipy-1.18.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7bbf207c4453ce1ad2e00b17313852b33310b83090c2311bdaf97f93c0380d12", size = 20475078, upload-time = "2026-08-21T23:23:54.138Z" }, + { url = "https://files.pythonhosted.org/packages/23/22/0858a0bbd6b3e825ceb8cd9baf9eaf3b2f2b1d77727eb6be40500bcdc92f/scipy-1.18.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:78c0665edead396b1abb4897c41a5c1d9bf090c8a637a4c20a61678e0a264e66", size = 23108904, upload-time = "2026-08-21T23:23:57.824Z" }, + { url = "https://files.pythonhosted.org/packages/75/9a/2e71719f31eaefe0e3a1706c4a1ded94e664bfd95ffca2b219a671faee01/scipy-1.18.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c085faa2cfa879c5141df483f836f4d691045a078224a670fa570fa01612d89", size = 34025113, upload-time = "2026-08-21T23:24:02.209Z" }, + { url = "https://files.pythonhosted.org/packages/df/64/ff35eb9e54894cf471ff4716abd3c81eb0a0626869217ce3e6ba4ccf17d7/scipy-1.18.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f55fa87b6c612ecd6b058f167c53231b1d14e412efe361d3d6e38b3631c73218", size = 35344199, upload-time = "2026-08-21T23:24:07.844Z" }, + { url = "https://files.pythonhosted.org/packages/d3/af/c5538be1792f7034c12c7db6ee67cace58253c7b87b122d68253eaf5de89/scipy-1.18.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c35d74ce0e193ff740c2f2be2ac913ddc232fe6c1ff40b26cfecb9c670c63314", size = 35639587, upload-time = "2026-08-21T23:24:13.05Z" }, + { url = "https://files.pythonhosted.org/packages/91/4c/075e4f66471bac101141ac739e9e135549be1bae584571bd03a530c056e1/scipy-1.18.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d2924a03db38dc2e848bca2fe9f077dafb891480b91a00a0963a8cf86dfc31c1", size = 37480330, upload-time = "2026-08-21T23:24:19.608Z" }, + { url = "https://files.pythonhosted.org/packages/39/e7/979fd14e75008623df31ba70d6bb144700f68feadcea042021c06a05bf82/scipy-1.18.1-cp312-cp312-win_amd64.whl", hash = "sha256:5e4d44984abc0020154ea81b247adeddcc3ac5527b975ff798bd1ba0adc513c2", size = 36658278, upload-time = "2026-08-21T23:24:25.463Z" }, + { url = "https://files.pythonhosted.org/packages/c7/0b/e1525354ff9d7d5feb6d1b31af6d14072e5c91e9607b421fa1ec889660b3/scipy-1.18.1-cp312-cp312-win_arm64.whl", hash = "sha256:d65d448389b8436493abcf629cc94ad0cf32aecaf06e1acca1de53cc795f2f12", size = 24400588, upload-time = "2026-08-21T23:24:30.579Z" }, +] + +[[package]] +name = "seaborn" +version = "0.13.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "matplotlib" }, + { name = "numpy" }, + { name = "pandas" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/86/59/a451d7420a77ab0b98f7affa3a1d78a313d2f7281a57afb1a34bae8ab412/seaborn-0.13.2.tar.gz", hash = "sha256:93e60a40988f4d65e9f4885df477e2fdaff6b73a9ded434c1ab356dd57eefff7", size = 1457696, upload-time = "2024-01-25T13:21:52.551Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/11/00d3c3dfc25ad54e731d91449895a79e4bf2384dc3ac01809010ba88f6d5/seaborn-0.13.2-py3-none-any.whl", hash = "sha256:636f8336facf092165e27924f223d3c62ca560b1f2bb5dff7ab7fad265361987", size = 294914, upload-time = "2024-01-25T13:21:49.598Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/33/ea3cb3839607eb175da835244a798f797f478c5ddf0e8ecdf57ea85a4c70/sentencepiece-0.2.2.tar.gz", hash = "sha256:3d2b5e824b5622038dc7b490897efe05ebbbb9e7350fc142f3ecc8789ef9bdf6", size = 8218435, upload-time = "2026-07-12T08:39:34.701Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/13/7a562289c8d5b49ebdf3f9c1e8ab67cf14a8743b1d90c8f406bfdec36b72/sentencepiece-0.2.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1edb10e520e4bddf74d85b0f5ae74cc2d60c2b448885080bfb618bc2b3a49f6b", size = 2188384, upload-time = "2026-07-12T08:38:28.486Z" }, + { url = "https://files.pythonhosted.org/packages/85/d1/912f14fd5eae168aba726ffb6a9a2dc1c71fe7676c53da6f5c442b886d4a/sentencepiece-0.2.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f7c06c751c19d923435a54bff4f7e66e728fad160e8da28254f133abc9725820", size = 1441553, upload-time = "2026-07-12T08:38:30.552Z" }, + { url = "https://files.pythonhosted.org/packages/bd/44/caa9cab5f261a019e2808bc5046152775dc57352ba9cbae7525e9e7a1ed4/sentencepiece-0.2.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:38111ed1f79268f399c505028023d5eaaf0ab4e5eafceb709468b0d3323e7838", size = 1347176, upload-time = "2026-07-12T08:38:32.211Z" }, + { url = "https://files.pythonhosted.org/packages/19/90/cd798935668cff71d309d8ff10385844ecf216b1fe454f1993ed8bf2cb91/sentencepiece-0.2.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cbce24284f51f71d10a42b7b9c964dcb9048b28f1c8e5db40bcbcb6f428cba6a", size = 1325200, upload-time = "2026-07-12T08:38:33.689Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2d/37e3da037318a70066ded0d51bc2a7f35491ae6338dd993d5eb1503fc3b5/sentencepiece-0.2.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c8a168b040bc61681293f79a949b5d911c8e25086f4260285b8d97ab5f1195da", size = 1397736, upload-time = "2026-07-12T08:38:35.771Z" }, + { url = "https://files.pythonhosted.org/packages/8d/11/753fca2e6b109be3ab7867abf357dfe48677fe726ae5a5363d0b54ca9450/sentencepiece-0.2.2-cp312-cp312-win_amd64.whl", hash = "sha256:7c6e7bf684dc12145bfa685d3060beaea55139134ba848289bee514ed42e7383", size = 1248030, upload-time = "2026-07-12T08:38:37.604Z" }, + { url = "https://files.pythonhosted.org/packages/e2/0a/70efbe861ca182d7d4b6e1a20f58e043400848fa9f2915229f082e221648/sentencepiece-0.2.2-cp312-cp312-win_arm64.whl", hash = "sha256:76ff5814db72e7462dece042d7593cdf102b8ec82c2b1cc201a2add34ee3050d", size = 1187325, upload-time = "2026-07-12T08:38:39.348Z" }, +] + +[[package]] +name = "setproctitle" +version = "1.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/b0/6b8a516c5a9e9630bd5293db78314ac012f690305fe93beadea388626efb/setproctitle-1.3.8.tar.gz", hash = "sha256:cafe209d064a6efb88cb45a03e97981ff8832802b2b5d009dde0197a3b7b41c8", size = 27214, upload-time = "2026-10-01T21:09:27.121Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/36/e7a4b93d7457ed12a1a2b49b042c25848a8847b15f7808159f2ccce91fdd/setproctitle-1.3.8-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f9a49d8103df362272c625641a4f7b104ae584db21d0f1eec3b7a5d0d7750ed8", size = 18121, upload-time = "2026-10-01T20:59:05.288Z" }, + { url = "https://files.pythonhosted.org/packages/57/be/6a10d95bba71fd5f441dda01ae374ebcaeaa637a09f72b95e8cc59443958/setproctitle-1.3.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:823d7d8790a4f8484c7fa65468fcd9d009f13ffe5f0bc89ec0e0d2c165ac0335", size = 13126, upload-time = "2026-10-01T20:59:06.865Z" }, + { url = "https://files.pythonhosted.org/packages/cb/21/4df9fbc0c72b9bca39b5d53eff6813dc1738a1562983e0c614054e9dbb8d/setproctitle-1.3.8-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4a765e0c80a2453480be27c4fc22ba1c0771867040c5f91e4221940d78a4abfb", size = 32929, upload-time = "2026-10-01T20:59:09.199Z" }, + { url = "https://files.pythonhosted.org/packages/5f/07/1476dafdbf5d124a05ae4856272908c0796fa65844376a32bb066f04afda/setproctitle-1.3.8-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f61345393548bc72844d837d62fcf63444b0f5dac418544beb6d4f628a1c5df3", size = 33765, upload-time = "2026-10-01T20:59:15.018Z" }, + { url = "https://files.pythonhosted.org/packages/81/c6/db7b3b859ba0fad54d6a352c3f99a29691f11be133649f61a30a3798f2b0/setproctitle-1.3.8-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba59516fcab4b621b80966a32f1195770696c113a948d00845f35b762e335db7", size = 35614, upload-time = "2026-10-01T20:59:17.439Z" }, + { url = "https://files.pythonhosted.org/packages/c2/76/1acfd4b72d5e1cb56ce44b028325d12fedd3410bfac02e15d3de03fa049a/setproctitle-1.3.8-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f523d34ad72b811be61e5027a046ad4670b54fc3c6384056f06b59f77d671af0", size = 32215, upload-time = "2026-10-01T20:59:19.993Z" }, + { url = "https://files.pythonhosted.org/packages/d8/a4/ce856b9aea7bcf1be539b1811e9bd937ca3cd1edf99516a66b71132cfcc3/setproctitle-1.3.8-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c667cc9c4cd949814b4ba8be70632a6454637647f3feea2724e02d3d3e35c66d", size = 33169, upload-time = "2026-10-01T20:59:22.201Z" }, + { url = "https://files.pythonhosted.org/packages/88/40/d96d641620e0cf4d8ec09571e5be293aa45f66cde574fc9c069b0ecbeb9f/setproctitle-1.3.8-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0d2f756ede847e05e7759af4f2d87dedf3ed34004092216be85acd8301b1d385", size = 34429, upload-time = "2026-10-01T20:59:24.228Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3c/ef0eef79863fad43ba6aca4fd96ab3b16358e8e37fd6d794bc8f7b88bf6a/setproctitle-1.3.8-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:191888bdf7c223c8b00eaa935947de0904165dee5e84d2055aecbb473d9c3f51", size = 31401, upload-time = "2026-10-01T20:59:26.32Z" }, + { url = "https://files.pythonhosted.org/packages/bb/97/7c667a2eae40a693b26186b34384ce9035f4563b7053e2e254f7738da75a/setproctitle-1.3.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:9c7b9b6ba3d0f6e504be5978854966168fb95b17ce126eab9a6132fe15f3e540", size = 32724, upload-time = "2026-10-01T20:59:28.481Z" }, + { url = "https://files.pythonhosted.org/packages/77/6f/33460cd16f81cbb367b55ce5e55bcee14ee05e16c8dddac83fddce308cc6/setproctitle-1.3.8-cp312-cp312-win32.whl", hash = "sha256:349499c0b21a940c3cb93d938013d40313711911e2fbaecd4700e2b7c236ca57", size = 12106, upload-time = "2026-10-01T20:59:29.924Z" }, + { url = "https://files.pythonhosted.org/packages/87/92/243fa4a41c565eea22c9e7e5c14cceb3a6d1e10e2586da94692a30cef2a5/setproctitle-1.3.8-cp312-cp312-win_amd64.whl", hash = "sha256:f599401675bdcac21176ca385ea3139fc04c1f8e26724dc59f4fc9df1d1528ef", size = 12939, upload-time = "2026-10-01T20:59:31.622Z" }, +] + +[[package]] +name = "setuptools" +version = "84.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/44/f5da03a8ef95d369145c5bb53050e7877c9f3d312e128605fd9504829143/setuptools-84.0.0.tar.gz", hash = "sha256:f4695c21257f0d9b537ec2692c941d02ee143b7cc1276941349a546573b2ef73", size = 1168449, upload-time = "2026-08-08T18:27:58.365Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/95/9c/c510029fc6ef33a6275cd2c5d3cecd6613dfd6aa401d57c54f1c18852ccf/setuptools-84.0.0-py3-none-any.whl", hash = "sha256:51a52592b3b99e102b609654876bd65f19f999935166d1352678931132b0c670", size = 818216, upload-time = "2026-08-08T18:27:56.719Z" }, +] + +[[package]] +name = "shellingham" +version = "1.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, +] + +[[package]] +name = "simplejson" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/f0/ea064bba6c9afda0168ddb834f1c75a93351031e25aee35c046108e7f292/simplejson-4.2.0.tar.gz", hash = "sha256:55b121b70a560f4610bd3a355ab2015aca4f39978f6a82353f24d2013fe85861", size = 123986, upload-time = "2026-10-03T03:34:23.27Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/24/87a310dcd8bd02876bbc33164d41f1d7b78a14ae98210b187cae22f560fc/simplejson-4.2.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:aa067739b28c661deb4421ee9ec1d7bad5ee06b7c50f8cf0d009e7945abe7d52", size = 117330, upload-time = "2026-10-03T03:32:06.623Z" }, + { url = "https://files.pythonhosted.org/packages/4d/cf/b1fc78e122ab98a2bae6fd6d66dec18d1ed436cafb875278f4d9e7677cbd/simplejson-4.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f458e7a2dd3d1b8b90dc12900c9e5a0f8b863fa7b02286fee13086962244f70a", size = 95482, upload-time = "2026-10-03T03:32:07.969Z" }, + { url = "https://files.pythonhosted.org/packages/27/ec/bad733020b3eef7e8414385fdfd4ba6afd5b8a56a0c4eb4eaa21be380f2a/simplejson-4.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c490ec62ed1b66a27afd5085e743e7f93b745c515257373de8433f4d51e5c3bb", size = 95297, upload-time = "2026-10-03T03:32:09.864Z" }, + { url = "https://files.pythonhosted.org/packages/2d/29/fb579920d8ec86ebb1f9a8cc8c9d17f3dcdb32a885dbd8332d21aa855575/simplejson-4.2.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8c1e156ad810704994439719b9c03694e267052d4938ca188d91a1769d6f742b", size = 198576, upload-time = "2026-10-03T03:32:11.003Z" }, + { url = "https://files.pythonhosted.org/packages/8e/7d/11fee9bebb22944c9e294139d5035cfa584f692192dabf3659e9c9bc0148/simplejson-4.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8910997afb7bae918b1ccf766e106e37707c8f8b4c61ac6ce433c4c86c5848f", size = 196424, upload-time = "2026-10-03T03:32:12.299Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/cfb4d64d68e589f93aa83ecdf0ab9e62c787d7a5ef41c8a31f74eb62857c/simplejson-4.2.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0767e82c062486211af7ee88cbe4732ca24250ce8127ffebd47732455439b69", size = 203804, upload-time = "2026-10-03T03:32:13.758Z" }, + { url = "https://files.pythonhosted.org/packages/7f/12/0e752142cdfbbd442f9ac614eb92b61c3def9a6fdd7aad4771ec9acc4abe/simplejson-4.2.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:797f086f589395e701ab077e9996dc0522a0b60158993e703e42749c4a17127c", size = 188048, upload-time = "2026-10-03T03:32:15.5Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ff/4da29e068b788803681f17693153ed7f472c4190400eb724698b8e3dcd4b/simplejson-4.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2f53916dc840f4424dbafca0da7e8a3bafa7372ce7e1866c764966e36271f7bb", size = 193244, upload-time = "2026-10-03T03:32:16.694Z" }, + { url = "https://files.pythonhosted.org/packages/3b/4a/8e4167770b595ad5f7d2e20f0605e83f3467fa0ca6b85d50ee09019c4607/simplejson-4.2.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:703f532ec018562bb0c8eaf4b4851f5736c0f60d02e23ba8736ce885fa361eda", size = 201201, upload-time = "2026-10-03T03:32:18.001Z" }, + { url = "https://files.pythonhosted.org/packages/c6/5a/b8095e99e96a0f33f49d4da723d3a8f3b4295a13362c6fc26810f5dc51c4/simplejson-4.2.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:2c1772c43537c7cc616fc217344acb00dec8312cfa76e725b6c5a6a4d5f80fb5", size = 186277, upload-time = "2026-10-03T03:32:19.326Z" }, + { url = "https://files.pythonhosted.org/packages/3d/87/fd79ac0e3841cc173f4b44d9158d595eaac072603691b505dafab6bde0aa/simplejson-4.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:471f30cd51ffdda1a0c421dc9963ada31e9d29bd688a3198041d2c69d18d65c4", size = 195937, upload-time = "2026-10-03T03:32:20.615Z" }, + { url = "https://files.pythonhosted.org/packages/c5/3f/45f19753465fa2ec337259b608236620e44a6aa410c1167edda010f30ce1/simplejson-4.2.0-cp312-cp312-win32.whl", hash = "sha256:85bde07e265b39be9593c0dd5e144c2308aa51d2dd1c18f495b46fa942f336d7", size = 92129, upload-time = "2026-10-03T03:32:21.839Z" }, + { url = "https://files.pythonhosted.org/packages/78/f0/08a6cffc4545112ca4c9918110e8c5227146a69fd270b0c64ff22a445ac6/simplejson-4.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:733acb0a25795becbbb6c5564f5c1c2e839889a931a72249fb0cc1c176659d83", size = 93961, upload-time = "2026-10-03T03:32:22.996Z" }, + { url = "https://files.pythonhosted.org/packages/e9/4c/9acdf4ae4f41c09a09ad17427e5ee912f35aa56ea1d1723a9d927d659d4e/simplejson-4.2.0-py3-none-any.whl", hash = "sha256:c2a2e5f43287cbe3413f7b73b04d5a6f75c7bd93d783e628f5978853a2ef738d", size = 72826, upload-time = "2026-10-03T03:34:21.667Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "skippy-agentx-environment" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "agentx-harness" }, +] + +[package.metadata] +requires-dist = [{ name = "agentx-harness", url = "https://github.com/Mesh-LLM/agentx-harness/releases/download/agentx-v1.0.12.post2/agentx_harness-1.0.12.post2-py3-none-any.whl" }] + +[[package]] +name = "soundfile" +version = "0.13.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e1/41/9b873a8c055582859b239be17902a85339bec6a30ad162f98c9b0288a2cc/soundfile-0.13.1.tar.gz", hash = "sha256:b2c68dab1e30297317080a5b43df57e302584c49e2942defdde0acccc53f0e5b", size = 46156, upload-time = "2025-01-25T09:17:04.831Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/28/e2a36573ccbcf3d57c00626a21fe51989380636e821b341d36ccca0c1c3a/soundfile-0.13.1-py2.py3-none-any.whl", hash = "sha256:a23c717560da2cf4c7b5ae1142514e0fd82d6bbd9dfc93a50423447142f2c445", size = 25751, upload-time = "2025-01-25T09:16:44.235Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ab/73e97a5b3cc46bba7ff8650a1504348fa1863a6f9d57d7001c6b67c5f20e/soundfile-0.13.1-py2.py3-none-macosx_10_9_x86_64.whl", hash = "sha256:82dc664d19831933fe59adad199bf3945ad06d84bc111a5b4c0d3089a5b9ec33", size = 1142250, upload-time = "2025-01-25T09:16:47.583Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e5/58fd1a8d7b26fc113af244f966ee3aecf03cb9293cb935daaddc1e455e18/soundfile-0.13.1-py2.py3-none-macosx_11_0_arm64.whl", hash = "sha256:743f12c12c4054921e15736c6be09ac26b3b3d603aef6fd69f9dde68748f2593", size = 1101406, upload-time = "2025-01-25T09:16:49.662Z" }, + { url = "https://files.pythonhosted.org/packages/58/ae/c0e4a53d77cf6e9a04179535766b3321b0b9ced5f70522e4caf9329f0046/soundfile-0.13.1-py2.py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:9c9e855f5a4d06ce4213f31918653ab7de0c5a8d8107cd2427e44b42df547deb", size = 1235729, upload-time = "2025-01-25T09:16:53.018Z" }, + { url = "https://files.pythonhosted.org/packages/57/5e/70bdd9579b35003a489fc850b5047beeda26328053ebadc1fb60f320f7db/soundfile-0.13.1-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:03267c4e493315294834a0870f31dbb3b28a95561b80b134f0bd3cf2d5f0e618", size = 1313646, upload-time = "2025-01-25T09:16:54.872Z" }, + { url = "https://files.pythonhosted.org/packages/fe/df/8c11dc4dfceda14e3003bb81a0d0edcaaf0796dd7b4f826ea3e532146bba/soundfile-0.13.1-py2.py3-none-win32.whl", hash = "sha256:c734564fab7c5ddf8e9be5bf70bab68042cd17e9c214c06e365e20d64f9a69d5", size = 899881, upload-time = "2025-01-25T09:16:56.663Z" }, + { url = "https://files.pythonhosted.org/packages/14/e9/6b761de83277f2f02ded7e7ea6f07828ec78e4b229b80e4ca55dd205b9dc/soundfile-0.13.1-py2.py3-none-win_amd64.whl", hash = "sha256:1e70a05a0626524a69e9f0f4dd2ec174b4e9567f4d8b6c11d38b5c289be36ee9", size = 1019162, upload-time = "2025-01-25T09:16:59.573Z" }, +] + +[[package]] +name = "sqlalchemy" +version = "2.1.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/08/bb/28e3106ee586e5b2f5ecf211eec1348055f0f926314b13fe23b9cffa9039/sqlalchemy-2.1.5.tar.gz", hash = "sha256:0df76cf1ca680ad745bd378a6299a058611a8a784eeaeb4ed78ad4a0b7ce2003", size = 10569593, upload-time = "2026-10-16T20:52:20.57Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/a5/286dc0a04b2f2052b15785784db16c39628d3d7424b25112a306bd0e1d43/sqlalchemy-2.1.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3eb1907fc67aacc160276e7f61c1f71a7a38c10e84ff87b74d90cae0abd137bb", size = 2471746, upload-time = "2026-10-16T22:45:12.171Z" }, + { url = "https://files.pythonhosted.org/packages/44/80/066b7dca8250d8a6135afe692b8a80bc5239c0a0344213ba847fc3f9a46b/sqlalchemy-2.1.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22eeeb297ced15cd7571aca242aede6a59141dcc3282c29c987fbc83f05c823b", size = 4673470, upload-time = "2026-10-16T22:34:28.997Z" }, + { url = "https://files.pythonhosted.org/packages/4d/33/8be720a412d595fa061a9ddcff6b5340ae09d3317ba6a32207523eb239f3/sqlalchemy-2.1.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6eb2fc3c1e8d2498d944b6ff64d32a63a5c900a14892c200626e701e69187113", size = 4726119, upload-time = "2026-10-16T22:40:54.421Z" }, + { url = "https://files.pythonhosted.org/packages/47/01/938538f2d7fa2e1ba62d07beaac3303c9ec0d21479e35320cbe5b0312ccc/sqlalchemy-2.1.5-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a534a39a9247a17843d9f6e34a0877d1a2af870b273e53e1c453b3a65f93c28e", size = 4374608, upload-time = "2026-10-16T22:52:47.037Z" }, + { url = "https://files.pythonhosted.org/packages/35/e4/b27d25f452994dc9acecb86f7984750c0f7891734fc1a50aee83483fd88e/sqlalchemy-2.1.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3cc3292040c980e9f1a54b14da76cf938a6a04a27e8acf6cb7709e9c3a40935b", size = 4596779, upload-time = "2026-10-16T22:34:30.811Z" }, + { url = "https://files.pythonhosted.org/packages/53/51/f2fae2a6bb734400aec41f3e625efcc03f1e43a26b852aa89206efce61a1/sqlalchemy-2.1.5-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:ce8d3de4e0489671fa023dea3f769360df02b2df6e482a44f8fa4421dd41c0ae", size = 4367657, upload-time = "2026-10-16T22:52:49.12Z" }, + { url = "https://files.pythonhosted.org/packages/0a/22/05957d18ac378d20ee048010916d3c1931442bcbd0c1c21b18e0e868ab6f/sqlalchemy-2.1.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:143cea634f03f9a8009fdeaeab46808031ab05bf0c50ec0aa25da51c29bdeeb8", size = 4673278, upload-time = "2026-10-16T22:40:56.847Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ea/266829855add33a99f1cb59d548e563e208aea514277d2f9650b454041dc/sqlalchemy-2.1.5-cp312-cp312-win32.whl", hash = "sha256:7133bd0ac969ba1a108508975e0c26229329cadaaa48844f0a038dafa610693b", size = 2381924, upload-time = "2026-10-16T22:33:41.207Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1b/3f59712d0a7e08bf3a075df43b0a3d89de051728d829d6836f546c533012/sqlalchemy-2.1.5-cp312-cp312-win_amd64.whl", hash = "sha256:ee7267d7ffed80c370dfdd7ad1c741d0227f0e8054b83d00715fb99307bd330c", size = 2434617, upload-time = "2026-10-16T22:33:42.917Z" }, + { url = "https://files.pythonhosted.org/packages/57/f6/31e94eb5403ca04d393805fe6df5470f48aabdbfb05437e93c2a7f8e3ebd/sqlalchemy-2.1.5-cp312-cp312-win_arm64.whl", hash = "sha256:b3732a60b01560c9efee3b9ea188dc12614b2642ffce4f8235c4fbf72dd40fe8", size = 2394015, upload-time = "2026-10-16T22:27:33.803Z" }, + { url = "https://files.pythonhosted.org/packages/de/e9/61176e4753f74ab5f6e72a56314ee654d25c31e6fc98c99060442998cccb/sqlalchemy-2.1.5-py3-none-any.whl", hash = "sha256:2f77b77b716f005b2dc3cc059d56df6a919bfb5b439e4149890a9df6c36be9e3", size = 2060214, upload-time = "2026-10-16T22:43:30.801Z" }, +] + +[[package]] +name = "starlette" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/0c/6efb252d091ecccd7d62048ae11f0ea35cd75a4fbaeea5e30f9c3bf91d10/starlette-1.8.0.tar.gz", hash = "sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522", size = 2730457, upload-time = "2026-10-13T07:54:39.53Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/b0/5742e4ac7af5eb58ec3470a537a49d7aa507e5539413e504b3a65ef50ba8/starlette-1.8.0-py3-none-any.whl", hash = "sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f", size = 79612, upload-time = "2026-10-13T07:54:38.019Z" }, +] + +[[package]] +name = "starlette-compress" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "brotli", marker = "platform_python_implementation == 'CPython'" }, + { name = "brotlicffi", marker = "platform_python_implementation != 'CPython'" }, + { name = "starlette" }, + { name = "zstandard" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/a4/bf7bb0dec4aa4541e7523a9d40cf10002d775449e111306959898a935d1c/starlette_compress-1.8.0.tar.gz", hash = "sha256:4dc0077468a2276b6dfd1b4f946fb61b5465a41c996c010486248e65af15b4b6", size = 24841, upload-time = "2026-07-18T00:05:08.216Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/74/9a/8eb13069f311042b0f44b5b3a5c59e50d265863b323757ab51a84564f65f/starlette_compress-1.8.0-py3-none-any.whl", hash = "sha256:3c991e21d31c7f845a004055db9ae3c7e79ed59cac34c8444e9e7e689456b623", size = 14072, upload-time = "2026-07-18T00:05:06.867Z" }, +] + +[[package]] +name = "textual" +version = "5.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py", extra = ["linkify", "plugins"] }, + { name = "platformdirs" }, + { name = "pygments" }, + { name = "rich" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ba/ce/f0f938d33d9bebbf8629e0020be00c560ddfa90a23ebe727c2e5aa3f30cf/textual-5.3.0.tar.gz", hash = "sha256:1b6128b339adef2e298cc23ab4777180443240ece5c232f29b22960efd658d4d", size = 1557651, upload-time = "2025-08-07T12:36:50.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/2f/f7c8a533bee50fbf5bb37ffc1621e7b2cdd8c9a6301fc51faa35fa50b09d/textual-5.3.0-py3-none-any.whl", hash = "sha256:02a6abc065514c4e21f94e79aaecea1f78a28a85d11d7bfc64abf3392d399890", size = 702671, upload-time = "2025-08-07T12:36:48.272Z" }, +] + +[[package]] +name = "tiktoken" +version = "0.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "regex" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/62/167a842aa0429d45f5e797354fd4343a96f6043d67d0513c675c7b8d36e6/tiktoken-0.14.0.tar.gz", hash = "sha256:231dec90efcdccf1b565a1416107736f1e09b1a08fe736ef9d6363e626d03874", size = 38898, upload-time = "2026-08-17T19:49:49.514Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8c/da/e273746b9d24a63c776bc60fba914351573ad9c575b52601eb5e60632564/tiktoken-0.14.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8e947aefe98ef74cce94923f90e48c98fe34eb1ec0a6bfdfadfc5a96359bfc36", size = 1094408, upload-time = "2026-08-17T19:48:49.269Z" }, + { url = "https://files.pythonhosted.org/packages/69/9f/fe6b1aca23331aa5271df5a4bd07bf68a7059254d47faee1b8272592a777/tiktoken-0.14.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d6cebe67765569df3dafac8474e4eccf5c19d24140492567a5e58a11445732a4", size = 1038499, upload-time = "2026-08-17T19:48:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/0b/35/e9f47647c9e163bd1de30fe1a491669b7248cfc67b7404c35c009a701e1a/tiktoken-0.14.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:7db45b98e94adf4173a5cd7422b150999a7ee11ff847783a14f6e1b80cc38cb6", size = 1186355, upload-time = "2026-08-17T19:48:51.93Z" }, + { url = "https://files.pythonhosted.org/packages/51/11/9976ad86980a00cdef05e730a0127a2578a1bc6d11644d8d47246de2eb26/tiktoken-0.14.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:7896eea257fe497a2b7134474d909156c6744ce8da35bce88011a960e008aa0d", size = 1204197, upload-time = "2026-08-17T19:48:53.18Z" }, + { url = "https://files.pythonhosted.org/packages/d4/9c/7035b0bcfaa68d1ee4803fc5be5214ad865669b05bd20e7105ae8a18afc6/tiktoken-0.14.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b950248272f1b303dc32986396e2dccfa10cf6d1e83ec8f0bba1776660305482", size = 1250635, upload-time = "2026-08-17T19:48:54.392Z" }, + { url = "https://files.pythonhosted.org/packages/bc/1d/69cabf18bed7f4366da076735816abce0d4db3fae491ae338a6612128777/tiktoken-0.14.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3de75343041a1c57333b1e707ac8a9769738241d7d6a55d39e12cf84548337c6", size = 1316085, upload-time = "2026-08-17T19:48:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/bd/bd/a2e884fb1402cba5be08836590320012b2d8ada0e2eef9911a64df4bcd2d/tiktoken-0.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:087538c080e5ff421abd3a0785ed63c5111d06af98e6cd0d374dbe5969147ca3", size = 941208, upload-time = "2026-08-17T19:48:56.938Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.23.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/2e/4ce5b9716f26e526eff6b0502ebed4ea8d7161f03b3c77617c9f25528e97/tokenizers-0.23.3-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9d2b5c97daf61688c2ad1803ca851800feaba50fb68d5821779e9ea5880d968c", size = 3148800, upload-time = "2026-10-09T10:00:51.457Z" }, + { url = "https://files.pythonhosted.org/packages/b2/72/01e49f032bb346e5aaf06c10c74fe8aeec847173adbadd66eb7c53054bf2/tokenizers-0.23.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:68649e97d5b43c44c031d8d848874a6eecae8f8fe40ea989aa777a5a83aca716", size = 3101381, upload-time = "2026-10-09T10:00:54.063Z" }, + { url = "https://files.pythonhosted.org/packages/15/fc/ae987741829b1cd547668c4c94be732ae3eefd1d74344e64c3d2ca714acd/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec82e80e65a862275b97c3d90b7a523df8d9519ee48aeb4e9625b2cc909274e0", size = 3519944, upload-time = "2026-10-09T10:00:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/1c/da/cc8f6c030afaf05fbddc608158fbb761dca46913cbeba6b112e59fc82e2a/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c64a0713180ff16829d4e7f39a658b77ea11443af4e1aa46523692943c9b1414", size = 3397695, upload-time = "2026-10-09T10:00:57.444Z" }, + { url = "https://files.pythonhosted.org/packages/ec/f1/256f78d1365fa2cd3ea6db716883d74667c8cbb6a21f15fa5b89a773cdc2/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ddedfd4b3b4be6be24ff6ca645c4a37fddfd305f6f3e354c54cf10b715c48215", size = 3753125, upload-time = "2026-10-09T10:01:00.165Z" }, + { url = "https://files.pythonhosted.org/packages/60/93/eee007ac2fcbf4ecfce7fbc354826cf3611f56bdb886f3e91b1f7dd06b8f/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2a89614730d7b80940a5d2ed9320e1ec8add5a745c6151d8d05071b7215505b6", size = 4018598, upload-time = "2026-10-09T10:01:02.05Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f9/0c96c4739461fce9d8d865b416728081bf6230022d7163bd6244f35f4b31/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e88646b8580c5ad7f4361477f1298e9cc01771a1ee9aecfe32c47b8ff614cc38", size = 3602442, upload-time = "2026-10-09T10:01:03.77Z" }, + { url = "https://files.pythonhosted.org/packages/3a/40/6706b82693715581457c6d5423eaa7faae576bb0526c5738a57085eb4449/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87", size = 3396193, upload-time = "2026-10-09T10:01:05.48Z" }, + { url = "https://files.pythonhosted.org/packages/fe/0c/85946de40e25b7364b8f1bcf56def129069acd5bb364b7c86a32919e1a23/tokenizers-0.23.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:bf501c40b72d2d5c8623620210430e9cac1ce47a46e45b34107b70a1557d46b0", size = 3553483, upload-time = "2026-10-09T10:01:07.387Z" }, + { url = "https://files.pythonhosted.org/packages/f1/6b/8d615d92cad1d511ca5ab188d1c7c167f0b3d295cc0d96207f9f82d486d8/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:114e2b55ed177179d59f4ab98200a4471e11e78f9e4b5a922d146740f96fcf52", size = 9972248, upload-time = "2026-10-09T10:01:09.437Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7d/a922e37ddd58d1b463bbc2ad08120c8f59c60b814cd353519a116b24f8ba/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:d3407fb7b9c4d75dd68850ffd7180bc0a5d2dbaf0762d888e612f31fec3f9c6b", size = 9802957, upload-time = "2026-10-09T10:01:11.869Z" }, + { url = "https://files.pythonhosted.org/packages/4b/06/5d3f506a86ae0699a0e4ea05c05978f9aee169ef2c1d844e68c971cf8194/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:84513ef0aeb8bf8f4ea11a2e8a7ac163ec5288aa115e649a59b470ac5c3107df", size = 10145487, upload-time = "2026-10-09T10:01:14.268Z" }, + { url = "https://files.pythonhosted.org/packages/26/e5/065625317690ea3548d834dad81f48ea1fd32e4964610e658e195d7fe28e/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3", size = 10266026, upload-time = "2026-10-09T10:16:33.054Z" }, + { url = "https://files.pythonhosted.org/packages/77/4e/babede85d0d19f5e3deeef0063e01848141329934d3d77c31b5cab5ac2b4/tokenizers-0.23.3-cp310-abi3-win32.whl", hash = "sha256:1ebf28794e7e4954e20a7f70fbea410b2d1f0418f7dbbca97ca384fcfef38c25", size = 2588086, upload-time = "2026-10-09T10:16:35.686Z" }, + { url = "https://files.pythonhosted.org/packages/d1/6c/24f074c9a0efb98e61b20aafe6b2641922d5db24e447d5d6daffd9e17555/tokenizers-0.23.3-cp310-abi3-win_amd64.whl", hash = "sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3", size = 2872101, upload-time = "2026-10-09T10:16:37.533Z" }, + { url = "https://files.pythonhosted.org/packages/53/77/a476b6f73a661c11d113a342d2326b91506cf2285f0995d1212a6bb2022d/tokenizers-0.23.3-cp310-abi3-win_arm64.whl", hash = "sha256:7e48734d2de9260d86f03ab056d2cfeeff3869f61dbd49aaa15a2793b5f3458b", size = 2742580, upload-time = "2026-10-09T10:16:39.244Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "5.20.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "safetensors" }, + { name = "tokenizers" }, + { name = "tqdm" }, + { name = "typer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/32/03/2e8d6da6a582a0fdbaa7af9c0dab72dac113e6e3ea3b98d6ed67248322cc/transformers-5.20.1.tar.gz", hash = "sha256:25b30879e4c243f00630c1079171ede6d4f6bf76e68f978acd47628a640bc8a0", size = 10224416, upload-time = "2026-10-16T13:02:04.181Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/ba/057af605774c3c7a9228ce61d88040749134ef320426403b31bb73755d43/transformers-5.20.1-py3-none-any.whl", hash = "sha256:5f51ce444193e5d0a751e3fa489ddbc2224ff12f6675a5cfefd4044b09757c19", size = 12844669, upload-time = "2026-10-16T13:02:00.488Z" }, +] + +[[package]] +name = "typer" +version = "0.27.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "rich" }, + { name = "shellingham" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/03/51/d33db42cc72ffd8c30777547b42d01f0cbf9d95a770457698d0174b3ed71/typer-0.27.3.tar.gz", hash = "sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901", size = 205303, upload-time = "2026-10-06T17:24:16.61Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/ea/2e31b67051e91a133189e9c000c222502ddc6969856416de0d095de4c0b0/typer-0.27.3-py3-none-any.whl", hash = "sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff", size = 123312, upload-time = "2026-10-06T17:24:15.054Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/68/f1b440335057bfce71b6e50a9d09445aa2ecbd08359a337976627b8409e7/tzdata-2026.5.tar.gz", hash = "sha256:8cc73c0a0bfca7dbfa59235d60b2eff82231dee33f53d206db1acd9173cfc0a7", size = 200404, upload-time = "2026-10-03T09:23:14.143Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +] + +[package.optional-dependencies] +standard = [ + { name = "httptools" }, + { name = "python-dotenv" }, + { name = "pyyaml" }, + { name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'" }, + { name = "watchfiles" }, + { name = "websockets" }, +] + +[[package]] +name = "uvloop" +version = "0.23.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fa/42/02c739ce85fb2ee8d99212c61417da8140c6b87e9d97c430bea520d76044/uvloop-0.23.0.tar.gz", hash = "sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27", size = 2559185, upload-time = "2026-10-01T03:17:04.4Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/98/04e766a6de99e6f7f955ecb7829e8d5a557de3427cb85be2236de54dda0c/uvloop-0.23.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3", size = 1393055, upload-time = "2026-10-01T03:15:42.526Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/499e7b863a848ede009539bce39806b66205da5f8779354228e785601144/uvloop-0.23.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63", size = 768909, upload-time = "2026-10-01T03:15:43.974Z" }, + { url = "https://files.pythonhosted.org/packages/3d/95/a880f8ce3b87ac5b307c354e8ee480be4658d24bf01f87921d57e3530b4a/uvloop-0.23.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda", size = 4419106, upload-time = "2026-10-01T03:15:45.551Z" }, + { url = "https://files.pythonhosted.org/packages/51/27/c1d2f9fa977f8f42ea294604166df10e0027e6dc6cd17f85ede386c9bf36/uvloop-0.23.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208", size = 4532597, upload-time = "2026-10-01T03:15:47.258Z" }, + { url = "https://files.pythonhosted.org/packages/42/dd/2cb6a2c8a30ca55c07a882dd4ae4ceae0fa7d8c15b25b3b7cb9a4b6cf4ca/uvloop-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac", size = 4230048, upload-time = "2026-10-01T03:15:49.119Z" }, + { url = "https://files.pythonhosted.org/packages/f4/52/29989cbaa4022dc4ef35c1dd60a4ab989e4c2065f341ed483ae71d2bd950/uvloop-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d", size = 4394152, upload-time = "2026-10-01T03:15:50.829Z" }, +] + +[[package]] +name = "watchfiles" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/68/e6aa0b77d217b31f8f486ec0cdfe5e00e6e38dc0be657e7d85819b9faf0a/watchfiles-1.3.0.tar.gz", hash = "sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207", size = 108119, upload-time = "2026-09-21T09:08:55.664Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/68/fa/c0b840d5d8bafe640925408ce11095948c8945bb61be1e67d0ab629b872a/watchfiles-1.3.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441", size = 399703, upload-time = "2026-09-21T09:08:13.518Z" }, + { url = "https://files.pythonhosted.org/packages/c7/8a/894799b485fe9473ad10422a0d9668e53fb78e3a2b5cc6061159572844ad/watchfiles-1.3.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c", size = 397647, upload-time = "2026-09-21T09:08:15.16Z" }, + { url = "https://files.pythonhosted.org/packages/5a/61/f277cd5ead05f5d37b98b41fbdd0c943ee0c04d49738f62e902cb291cf43/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5", size = 454994, upload-time = "2026-09-21T09:08:16.587Z" }, + { url = "https://files.pythonhosted.org/packages/46/66/ea4c01382975e53b1ac1b0a0ea1b353416b8127fb6e04f5c1c313119aab6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca", size = 460105, upload-time = "2026-09-21T09:08:17.961Z" }, + { url = "https://files.pythonhosted.org/packages/31/c3/1a501b597817096c9831c255f6270c124ce0e2faeb74124be24dcc93b86d/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30", size = 493761, upload-time = "2026-09-21T09:08:19.327Z" }, + { url = "https://files.pythonhosted.org/packages/5a/16/77352d05e152c7786a016e9f1decdb4507e8aa5bcf3343c72142a0413d14/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95", size = 577500, upload-time = "2026-09-21T09:08:20.723Z" }, + { url = "https://files.pythonhosted.org/packages/95/fe/81001c55b24466fe9911135e50269fd3a29f43e446627a92adfab54553b6/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29", size = 469209, upload-time = "2026-09-21T09:08:22.346Z" }, + { url = "https://files.pythonhosted.org/packages/8a/cf/e3ad894ed5909a7c44b0707e89bc25d19a3d78b3a7aec846119443b6ae56/watchfiles-1.3.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1", size = 458353, upload-time = "2026-09-21T09:08:23.7Z" }, + { url = "https://files.pythonhosted.org/packages/7f/f5/2f106829e6e2bc91ad74614730f6df484202b9a4d20d927dbf2f08d37d44/watchfiles-1.3.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935", size = 468707, upload-time = "2026-09-21T09:08:25.167Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/2741ab776b978669c1f3bba1e573f1a184f727ab8b4d3a6d9c61090800ed/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3", size = 632510, upload-time = "2026-09-21T09:08:26.532Z" }, + { url = "https://files.pythonhosted.org/packages/48/64/db4a4684275fe9b696ee5118c194705c1423b3d42181c3f8ee70194d5c73/watchfiles-1.3.0-cp310-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509", size = 661723, upload-time = "2026-09-21T09:08:28.004Z" }, + { url = "https://files.pythonhosted.org/packages/52/80/95ddb24f6a2f595c031c24432ab7b8aa7d6d1ada0c6d63a552166e06e8d1/watchfiles-1.3.0-cp310-abi3-win32.whl", hash = "sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661", size = 277761, upload-time = "2026-09-21T09:08:29.335Z" }, + { url = "https://files.pythonhosted.org/packages/48/a1/1c4a1b3c8030cd03206232612be8a6e8799093490c220b0fcb935d02b75a/watchfiles-1.3.0-cp310-abi3-win_amd64.whl", hash = "sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61", size = 290643, upload-time = "2026-09-21T09:08:30.45Z" }, + { url = "https://files.pythonhosted.org/packages/82/e0/d2db577c632d26d08078c4390dd870b8555c4e558df25d22270f0166c71f/watchfiles-1.3.0-cp310-abi3-win_arm64.whl", hash = "sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc", size = 285510, upload-time = "2026-09-21T09:08:31.561Z" }, +] + +[[package]] +name = "websockets" +version = "17.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/89/3f825ab71c242fffb62ea8fe638741c290f62f8d7aadf8125ff897747af3/websockets-17.2.tar.gz", hash = "sha256:36c2fb94c990cc2545143b12690e2de6c16300f9dbe5b4f33fa300cf57dc8792", size = 188355, upload-time = "2026-10-03T14:56:53.5Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/de/87854af9b38fe4738fd85f7f21c5b49558ae20aec898880894e435f33375/websockets-17.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:916ebdfd82e7fc68041d36b2b5f60361b9abce1e087454da15f8bd004839e090", size = 217757, upload-time = "2026-10-03T14:53:23.029Z" }, + { url = "https://files.pythonhosted.org/packages/3a/2e/1e80b5efa41544f626d56bd15ccb53dbfc56bf28bf80ab9cd6f82c4b1d20/websockets-17.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3621f3686397708b8eeabfd0a9d75267c1f29a7537d2fe31e65d099e71587fa4", size = 215439, upload-time = "2026-10-03T14:53:24.531Z" }, + { url = "https://files.pythonhosted.org/packages/3b/6e/82c78b595aee05be76a7ee78539323da1593c1848e4fef51c704c696568f/websockets-17.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a81e19710d48da88653473b6b9c366d47e99fe4f58e37ce415be47966748f31f", size = 215703, upload-time = "2026-10-03T14:53:26.226Z" }, + { url = "https://files.pythonhosted.org/packages/f8/c4/905ef6aa80423c03dba99e1e26fc0acf63a2a9a6a2d9e8c0e6a63caaf952/websockets-17.2-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f2731f9067976c8c4127212c0d2f2ada42d497d935e470419e029802365b12bb", size = 225023, upload-time = "2026-10-03T14:53:27.744Z" }, + { url = "https://files.pythonhosted.org/packages/03/c0/a6d8be9c43e4456fb9597fdf8b5e0ce1f0a5df41503acce6d869536e4e23/websockets-17.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6627b913b8586b1c06db9516b31dd0dfbc621de3bb9312616d92a7e44f268a5b", size = 225299, upload-time = "2026-10-03T14:53:29.171Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d4/976d34b5491258b0a86c2ce9b9aabb9fdd68919ffd7fe65999c14a502a98/websockets-17.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0198c4ec6a3406a2f7557c032967de426474c2c995c81076585e09d29a9f407b", size = 226540, upload-time = "2026-10-03T14:53:31.635Z" }, + { url = "https://files.pythonhosted.org/packages/83/2f/c4cfd42f53c697a8ed123fd82b8f85fcd13b6360d47f9f1d1d45d6ec6627/websockets-17.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:88c6a42c2632ff469e84155e44f6ed92cb15ccb047bf5fcb59225ae5a12fd33d", size = 229371, upload-time = "2026-10-03T14:53:33.061Z" }, + { url = "https://files.pythonhosted.org/packages/e7/55/9a221b29c6232ff9282eecb2fc102402cb9e42a3479264db0e5fc4fe6835/websockets-17.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:eb0023e6cdb4b8ece0b33875188dd16104ad8c335361d396a98394f99e30ff7a", size = 227173, upload-time = "2026-10-03T14:53:34.502Z" }, + { url = "https://files.pythonhosted.org/packages/8f/07/125e6d010c56c253d3d2b93cabaea0f96d33898151a16b49066a594acecf/websockets-17.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c1c09d5d4646eb96bda2cfb97493bcea21a0956a981de116e6b1f4a9de07f3fd", size = 225929, upload-time = "2026-10-03T14:53:36.071Z" }, + { url = "https://files.pythonhosted.org/packages/23/a8/aad3bd902aee84e1b261ad6ab83b405e4a564af43101b8ad1dc0293ff4f4/websockets-17.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0360c4dc13ac569cc245e0efa2f4d4b1e4733d24c47b8ab3f3747227b1356348", size = 223167, upload-time = "2026-10-03T14:53:37.528Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f4/ec8ab9be1a5310b4fea829f088c7aa2b7a58b61d34bce1b2a9338635ff12/websockets-17.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:76693a16dead737946b651375ee3109d7db7ad9569a1c55c60aaed3ef85cfcc6", size = 225974, upload-time = "2026-10-03T14:53:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/65/45/ba6503f8257d3f98b0f07ebaad0fd099c9023eae744fd5b775416743597e/websockets-17.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:77a42cc507993ec5471b5283f7eef869239173b6000031543e3938a86d1af0fd", size = 224581, upload-time = "2026-10-03T14:53:40.496Z" }, + { url = "https://files.pythonhosted.org/packages/d0/45/05cca59a876c6776727d96fc7ba59e0b6f9aa496afbf13e7e04ad0b63678/websockets-17.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:3bbc5543e39ee025d524077c5c15c2d67bc11c9f6676afe5b531839e24d701f6", size = 225347, upload-time = "2026-10-03T14:53:42.061Z" }, + { url = "https://files.pythonhosted.org/packages/1c/00/cf0e43292ae949b13f67535be84317102891d69fd1986ec2bf2ead42747b/websockets-17.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8da58558bfb0ca6ccac2419773521f1111e40654038b1afabdfc69c02cb82614", size = 226457, upload-time = "2026-10-03T14:53:43.575Z" }, + { url = "https://files.pythonhosted.org/packages/79/0d/9a5c61a18f0cc9876d94c70ccb3daf7614a9fee56abbb37c0e64e757fb96/websockets-17.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:01420cb1cb47433e8e7075d32cb8017ad3ffed0654bd1e48c0251b865920dec3", size = 224011, upload-time = "2026-10-03T14:53:45.077Z" }, + { url = "https://files.pythonhosted.org/packages/34/ed/991c1ab80ab2ce40e1c939fef6fa8f971c3ef3b21caf988a7a107e0ad27d/websockets-17.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:c49c9edd47d0e44d360299e2d8865e2950d2fcf1b4098782c9d7dcd070919e5a", size = 224990, upload-time = "2026-10-03T14:53:46.8Z" }, + { url = "https://files.pythonhosted.org/packages/e7/7a/363c835d17923e967fb66376188e67b9a261c85d826a0cd5e4dd3471221d/websockets-17.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:96f6c8d0fe21930d1f982bfce2382789d2e8d005d2ab63d21280660f95ef8fe1", size = 225265, upload-time = "2026-10-03T14:53:48.382Z" }, + { url = "https://files.pythonhosted.org/packages/c8/90/6c51f6d78636bd1cd6781fae8ea5ea7bf1d5b4059354f3c1f5f8de793338/websockets-17.2-cp312-cp312-win32.whl", hash = "sha256:b25659ab2d655d742701487d5591e3f98e8f8b329fc999e05e3d59691ab344a1", size = 218228, upload-time = "2026-10-03T14:53:49.867Z" }, + { url = "https://files.pythonhosted.org/packages/c6/2a/90008411c652dcfae34345a2169f4becd066a4ba71eebfa8dd801e0445e1/websockets-17.2-cp312-cp312-win_amd64.whl", hash = "sha256:faa763b677e96f1beccc6b4d7e8c079dfeed2f249f57a19debc321b519ee64ec", size = 218528, upload-time = "2026-10-03T14:53:51.486Z" }, + { url = "https://files.pythonhosted.org/packages/1f/a1/b8ad6c17f8e75ba2215422fffe0d7f0c4b690dcff1c47c0473db0d253d51/websockets-17.2-cp312-cp312-win_arm64.whl", hash = "sha256:63499fc49efe48bccc2fca40723bc7adb198866cbe159093dd979905316994b6", size = 218457, upload-time = "2026-10-03T14:53:52.938Z" }, + { url = "https://files.pythonhosted.org/packages/8a/58/835cd51934d6780fa586f275b5d9901eead6d81569b4343b3767cdbaae4c/websockets-17.2-py3-none-any.whl", hash = "sha256:6aa59f0ef92e796b2db6f5f26550c4713c0e4036899fadf02f55e2ed4db0b7ae", size = 211883, upload-time = "2026-10-03T14:56:51.898Z" }, +] + +[[package]] +name = "werkzeug" +version = "3.1.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz", hash = "sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060", size = 940188, upload-time = "2026-09-27T18:33:41.637Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a1/38/df03f564f43cec2684823f3cccae1a652ee7face1cbaa76fb223096e64d7/werkzeug-3.1.9-py3-none-any.whl", hash = "sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fab", size = 228700, upload-time = "2026-09-27T18:33:39.685Z" }, +] + +[[package]] +name = "xxhash" +version = "4.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/a5/1386f35da1475fcaeef42581deae73417c6d2a6a0b2d2e8914de18844dcd/xxhash-4.0.1.tar.gz", hash = "sha256:d55bf4ef10eb09b8b6866790e083d26d087d84caa3cc0946ba87c3ca7ecaf7b7", size = 101513, upload-time = "2026-08-17T08:24:08.557Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/26/6c/dc7cffeadd06336cd934947187cd38abb263103bbc552ca0f55fe4ff595a/xxhash-4.0.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1ee523f51718e41753f04f7102bb4dc55a18d2ea5cbaceef8ec7ca08571bd428", size = 38444, upload-time = "2026-08-17T08:21:54.332Z" }, + { url = "https://files.pythonhosted.org/packages/75/c9/cf736f6db8c3273af18925061572db0d4357818a9ce425f4b5fb0021918e/xxhash-4.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:515a822c73abbf6a0b7c70976d9662be342835c9d78b8dc7c023411f39c35dbc", size = 36195, upload-time = "2026-08-17T08:35:13.004Z" }, + { url = "https://files.pythonhosted.org/packages/da/a2/ca1929354b6851529d0148f7f335b5e2b0281f83bab3e19f0896dc579796/xxhash-4.0.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f5d031f35962e5483a613214e61f09fe24ab523062c3646d592dc16c4a217451", size = 253113, upload-time = "2026-08-17T08:20:52.152Z" }, + { url = "https://files.pythonhosted.org/packages/de/bb/542005206af59518bc8d78a210f1e0172217bc53beb32f64a5b632e72b6b/xxhash-4.0.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da0264844a09b538c894e5eff25313d941deb4dedec2131b98418a71a3c9944e", size = 276525, upload-time = "2026-08-17T08:21:01.886Z" }, + { url = "https://files.pythonhosted.org/packages/1b/df/607cff25dcb0f1d35c3b04493f6ad8471edb03fd4eacbdcc5ceddef1f3e9/xxhash-4.0.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1642907941ee4b75aacc3db688af52ea02ca2305ab22af7ee686ed726b332684", size = 297703, upload-time = "2026-08-17T08:21:57.958Z" }, + { url = "https://files.pythonhosted.org/packages/15/ba/9d2275eea0b9d9c6b02921be23f7588356c60df95c763b25f0e045894d43/xxhash-4.0.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4af350bc3f329970c0e3a59af84a8a30998bf8a9167eb50cd48e59baaa1d7bec", size = 280252, upload-time = "2026-08-17T08:20:47.299Z" }, + { url = "https://files.pythonhosted.org/packages/1d/aa/2299d9f6369e550aef2abb64945e39daa34412725aa46a20d99b74d76f67/xxhash-4.0.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8ba782ca3bf1e81492611152b9a0d5264971339e95e34d69de0ac2c926be496d", size = 511041, upload-time = "2026-08-17T08:20:36.771Z" }, + { url = "https://files.pythonhosted.org/packages/83/97/31bd8b8279e6935a0719f6910ced15e9d5a2cd554b253f6027ce1b5a1c2c/xxhash-4.0.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:237b8f63a2a0fcfb1ffc06e21dad23add44e6d354b2b014364a1d41e419a4dee", size = 261812, upload-time = "2026-08-17T08:22:00.469Z" }, + { url = "https://files.pythonhosted.org/packages/2d/c1/d180a2da23c105d8e0b02d54f9f5841013fc81c233010ec781e31f1aee4c/xxhash-4.0.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:81507a68ba84c55241fb61cce1469f473a5da4205fc8ef6f698e5948eea8dd88", size = 339878, upload-time = "2026-08-17T08:35:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/a8/3d/f584cd3172fe934f0f5a0a3917d0d7ce781f74d794fd43bb72be71c3ef6f/xxhash-4.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5f1ea31d61bcd2cd2f3ec4ca80a64187bbd7948f490b63cf0dcbc6e717b4c1e9", size = 272871, upload-time = "2026-08-17T08:20:56.067Z" }, + { url = "https://files.pythonhosted.org/packages/34/50/2c7956b2b551682e00b9aebce9ceb0a991a131d65f9850c09f5f9760be2e/xxhash-4.0.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:06713a5aaf1d0905c5579416c020c02e42b3ceb931e86c7d3b7fb85403dee3f3", size = 301440, upload-time = "2026-08-17T08:21:35.911Z" }, + { url = "https://files.pythonhosted.org/packages/eb/a2/0739f6482184a8026f4b022718f5f815d352059312e80696825433f0a8e7/xxhash-4.0.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e8cda075b10bb3917b002c74a04f9e02b7d13b5bf732571404d51c52b11c7329", size = 260157, upload-time = "2026-08-17T08:22:01.416Z" }, + { url = "https://files.pythonhosted.org/packages/a1/25/b31a7bcf1d7d116842812e54f9b944843b4236ea4fa85634e8259f342212/xxhash-4.0.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c10b9206753b64aa791b35b201485477525b26fdec5bf86e8364c388a03e2592", size = 278233, upload-time = "2026-08-17T08:21:15.674Z" }, + { url = "https://files.pythonhosted.org/packages/db/e8/5293bae090fc6119dbc5fcf5c4cc0e1536394b52d73b7904d033836c73db/xxhash-4.0.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f3e1a44af01b6692de0ec6caba5f0bf93ceb36896e02b7fc00952c6ea7ef39e1", size = 330270, upload-time = "2026-08-17T08:20:51.128Z" }, + { url = "https://files.pythonhosted.org/packages/72/9e/e2ab12d40921f3f34c9317637d65e011aeababf8288356ea8d527de2c1d0/xxhash-4.0.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:c6fc415b5568bd9accc7187f1729a99707330c0a67a8b9f93c1149ed573ed75d", size = 478555, upload-time = "2026-08-17T08:22:04.183Z" }, + { url = "https://files.pythonhosted.org/packages/6d/32/c6148d39a49efa95f39b4cf0d41ef35a487f3b30f6fb1fc8fe8d8eab577e/xxhash-4.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:96d8de55029d42251945531f6aa7590c32b48163c66a43bf29d8657d7446a377", size = 258174, upload-time = "2026-08-17T08:35:21.18Z" }, + { url = "https://files.pythonhosted.org/packages/8f/fb/0b04b68d6c5bc71c7a2c344f1287327b67e607f28fbcfd937697caca64b6/xxhash-4.0.1-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:0163b5d259de23ae9e07b7eabf435ce4704f6f205589a2b154e6af4be985ce1b", size = 20767, upload-time = "2026-08-17T08:21:00.806Z" }, + { url = "https://files.pythonhosted.org/packages/a6/be/476092aba34d1fcd313e1613a3bb3bc692f253d167b54bc90049043b5034/xxhash-4.0.1-cp312-cp312-win32.whl", hash = "sha256:1216f7ba5683f17a89eb7dcb4bc50a0b743dfe1902278d7b3d0786f538118433", size = 34669, upload-time = "2026-08-17T08:21:49.486Z" }, + { url = "https://files.pythonhosted.org/packages/aa/02/f9413d94fae43cec6d1a74c4f12156c6f4a7f5fd50e1d34defebdee3dec9/xxhash-4.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c2d525a3afabcd8e3549d85fc7e111fde6bc302d06a1893fe73adb79823415e", size = 37073, upload-time = "2026-08-17T08:22:04.886Z" }, + { url = "https://files.pythonhosted.org/packages/c1/83/6fe93c1b95acf962bc61a246df09dc2dcce895ccfc1080c9f48d0b652b92/xxhash-4.0.1-cp312-cp312-win_arm64.whl", hash = "sha256:86b2b12bec60c678ed8f5cca0258ad93a8928ebddb6ca7732f0875afe1451d1a", size = 33299, upload-time = "2026-08-17T08:35:12.708Z" }, + { url = "https://files.pythonhosted.org/packages/86/79/9127ff42a887a348dc4ce3211cf1a962836887adee6f57078132bfba78b4/xxhash-4.0.1-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:ff48915bf1871a1f19f74c11834c6329443d306cedc0c05fe7fe617810422a80", size = 31836, upload-time = "2026-08-17T08:36:28.261Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e6/f238693bfdd642adb59c99683964d46d9947fe721ff44d3bd850ae675407/xxhash-4.0.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:4a76345f5aceb4ec404918edf9c7f2b5507db864dc0d7455982009ac0890b57b", size = 34453, upload-time = "2026-08-17T08:23:49.795Z" }, + { url = "https://files.pythonhosted.org/packages/40/4b/796ace33cdfb75c91ba6d11615c3bd436355b9f3103e05865bbee9abce57/xxhash-4.0.1-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:31d86f9e81f3e84e00131ac7c54caf5119ae4ddd82c09c31cff597c813ce1ee2", size = 38488, upload-time = "2026-08-17T08:23:59.901Z" }, + { url = "https://files.pythonhosted.org/packages/ad/23/2d549e5d5d7759eaf9ac2d2d2ab81ff60f1bb2b52cdaae8e5ec5c6524354/xxhash-4.0.1-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:deca2a30d983d240b8375ec2ee0a4288e72042827fc61df2f7671f8467e4cb2f", size = 38206, upload-time = "2026-08-17T08:36:32.193Z" }, + { url = "https://files.pythonhosted.org/packages/79/98/1ee576b27f78e6107ee4ea8ac03e8a52888dff256e57d560f8282c195563/xxhash-4.0.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:7c343ee174d417a44d0c3355602c0cbbfa52a04d1bbbf1723378c7d2c8f60626", size = 37127, upload-time = "2026-08-17T08:23:42.705Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/b3/cd32ac66ae622b854c2df0ac52106dda220d361b65a64fde7d5b3684aa3f/yarl-1.25.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:94d7aa6debf92a1dd14cb5280b083a764169a13cfb23a452111160274ed989f4", size = 144798, upload-time = "2026-09-15T19:31:01.821Z" }, + { url = "https://files.pythonhosted.org/packages/61/fb/a2c52a8007c2051ba74662afb112ecf3d00346af4c25e33df9d80fd14fb8/yarl-1.25.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:83d4a37e4b95da4d8bda930d6d35b75b4cdadbacbb4980cae290ea3100b5d51d", size = 104583, upload-time = "2026-09-15T19:31:04.05Z" }, + { url = "https://files.pythonhosted.org/packages/be/dd/ee38aec8e09fdf957e50d4085453fbe202f56c6c3b4cf07b81cdb4f09ee9/yarl-1.25.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e029648f9c951db30e98a7d7ec90835db88ec4b32820efe2a9bdc2287e032eb6", size = 104325, upload-time = "2026-09-15T19:31:06.338Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b3/058dbfb1857b484c9cf9cc135659f50b85ce66e03c99e44dc2f7b6161f55/yarl-1.25.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4d781294bb815ecb5ea57ff6bbf8038e0a31a95fdf3e1788f66e0dc100d64b58", size = 115358, upload-time = "2026-09-15T19:31:08.593Z" }, + { url = "https://files.pythonhosted.org/packages/db/39/29693446cf0cf6b15a0e2f75a5d40f93c56819b05b0622196f45e95b5cc0/yarl-1.25.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e12c538e00e7c1b286a07061046b90e8124e6a9793efae2c70db6a4aad07faad", size = 107658, upload-time = "2026-09-15T19:31:10.802Z" }, + { url = "https://files.pythonhosted.org/packages/86/b3/3c4dd7e1af43b931fba95e0a722737f2ea94a6d199c802585282831d7abd/yarl-1.25.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e4de3ac4adbad3d0bc7c6f4360a7dbff5de2f15e3b723be3198074e17fd9c40", size = 122660, upload-time = "2026-09-15T19:31:12.84Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b5/1b60dbc3cfc9c5712b15148c206748f2bc93953ffdbe25ea75b63dfc89c9/yarl-1.25.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:419f392a1da624877975709e3864dfe833af6cc7671b39318086d456e288380c", size = 126506, upload-time = "2026-09-15T19:31:15.088Z" }, + { url = "https://files.pythonhosted.org/packages/bc/7b/ca212cbe170ac8b96e45317ecbcf9c3c3ecf0cdec98d5b088a9c4088929b/yarl-1.25.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6f117789d22dce188e5754e8bc65b7e6ebf8cb73963b9fa761f672a5883769d", size = 117050, upload-time = "2026-09-15T19:31:17.241Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c3/72b4938cdbe619ad71ac156182faef4908846b84dc3ca4dbb4c4e6f84014/yarl-1.25.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:80e47012e730da131c9f059c80936783f9659aae22dc31c03c0595590d11ed54", size = 114174, upload-time = "2026-09-15T19:31:19.294Z" }, + { url = "https://files.pythonhosted.org/packages/e8/43/268717870f9ba0cc9701a95181587f6dc8c5f387aab4aeecc83158f38a79/yarl-1.25.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e80f557716fd765439577131e526b8942ffc2c07bdbc5e39fa62f660ba1e963f", size = 114944, upload-time = "2026-09-15T19:31:21.414Z" }, + { url = "https://files.pythonhosted.org/packages/da/84/baa5bf504d51fe062c4bcaf62936da97fffb43285978d0b39984824231fd/yarl-1.25.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f61964f235a43738bfac50da46fc4254943a7eea3051aeb0b6fc7c992c29fadc", size = 108263, upload-time = "2026-09-15T19:31:23.388Z" }, + { url = "https://files.pythonhosted.org/packages/a4/28/779a2ed9e0152a601a27039bed9aead3f0b79797a67e2c44bfa444622dd8/yarl-1.25.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:e546fe1d4a93ebc2910f0d768baff19faa09843ab3f2036a67ed6e69fae4419d", size = 122184, upload-time = "2026-09-15T19:31:25.343Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1f/118e9e5b8f07694d63fd3222e801d7782270003f1a222aa798df3f8d5933/yarl-1.25.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cce0727fd5ac04d372fa9bbfde9febc2bcf209aadfcf0468e45dec72719895d1", size = 114001, upload-time = "2026-09-15T19:31:27.465Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ae/a4cf1cf372313734b17996d4007f9f73596e7a178b9485802e5494ecf484/yarl-1.25.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:af4ea5b37403ef4e30f3927eaed540db942bde01d8d3ff083527c0704d1c9c68", size = 120565, upload-time = "2026-09-15T19:31:29.47Z" }, + { url = "https://files.pythonhosted.org/packages/05/79/ad94f93ca731bc9e44d321833ab96b82a4f9f5f63cf773f81a4aeea5ecc1/yarl-1.25.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:68782fdb4027b8d1eee25ec35e9a6db05e863b899eb0310b3a33b6c3fef55707", size = 117060, upload-time = "2026-09-15T19:31:31.367Z" }, + { url = "https://files.pythonhosted.org/packages/bb/cc/51a7b4abf4ac593b8e7eb3794b28e5a35ae26eed8bc04787628d215af82f/yarl-1.25.1-cp312-cp312-win_amd64.whl", hash = "sha256:7d575b54cb3863ef9bc290ea4b009999d55dc237326131e4853cf33e888fee03", size = 102593, upload-time = "2026-09-15T19:31:33.329Z" }, + { url = "https://files.pythonhosted.org/packages/9d/21/0941a6b93a58b59a1ec75e5333bf06929b671309c43c0cd201c172d9c39f/yarl-1.25.1-cp312-cp312-win_arm64.whl", hash = "sha256:bc3ac7bf569f6b64dad04dd7808c7872dae8a97df657856eac05e9b7e3614a85", size = 97697, upload-time = "2026-09-15T19:31:35.855Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +] + +[[package]] +name = "zipp" +version = "4.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/23/655a1802fe8041302c959774ca7c80b53bc24737ff3ef45cb50ef11bd96c/zipp-4.1.1.tar.gz", hash = "sha256:7ebb7a44c021b29fd8dbd7cce6812d0d7b5b454521f93cc71af6ccd155aaa70b", size = 27649, upload-time = "2026-10-03T17:03:03.452Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/98/df615823cd9419131ce19fba00de53a663794369e198aade064a244b385d/zipp-4.1.1-py3-none-any.whl", hash = "sha256:8979f52d874162f485ff2981e3891f3a3317b7a3dd43ff1e1775b9304f307a9c", size = 10582, upload-time = "2026-10-03T17:03:02.506Z" }, +] + +[[package]] +name = "zstandard" +version = "0.25.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" }, + { url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" }, + { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, + { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, + { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, + { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, + { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, + { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, + { url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" }, + { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" }, + { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" }, +] diff --git a/tools/xtask/src/automation/agentx/agentic_config.rs b/tools/xtask/src/automation/agentx/agentic_config.rs new file mode 100644 index 0000000000..4b0850b066 --- /dev/null +++ b/tools/xtask/src/automation/agentx/agentic_config.rs @@ -0,0 +1,56 @@ +//! Explicit AgentX replay configuration shared by fixed-session profiles. +use super::{Prepared, trace_context}; +use crate::command::DynResult; +use serde_json::{Value, json}; + +pub(super) fn configuration( + input: &Prepared, + port: u16, + concurrency: u32, + sessions: usize, + namespace_label: &str, +) -> DynResult { + let cache = std::env::var_os("HF_HOME") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| input.root.join(".cache/huggingface")); + let tokenizer = cache + .join("hub") + .join(format!( + "models--{}", + input.model.tokenizer.replace('/', "--") + )) + .join("snapshots") + .join(&input.model.tokenizer_revision); + let tokenizer = input + .tools + .as_ref() + .map_or(tokenizer, |tools| tools.tokenizer.path.clone()); + let cohort = input + .dataset + .parent() + .ok_or("agentic cohort parent")? + .join("cohort.json"); + let cohort_digest = + crate::product::digest::file_sha256(&cohort).map_err(|failure| failure.error)?; + let marker_namespace = format!("{namespace_label}:{}:{cohort_digest}", input.model.key); + // An explicit config avoids AgentX scenario defaults reinstating an + // hour-long duration or consuming the selected turns in warmup. + Ok(json!({"schema_version":"2.0","random_seed":42,"benchmark":{ + "model":input.model.key, + "endpoint":{"url":format!("http://127.0.0.1:{port}/v1/chat/completions"), + "type":"chat","streaming":true,"timeout":1800, + "use_server_token_count":true,"session_header":"X-Session-ID","extra":{"ignore_eos":true}}, + "tokenizer":{"name":tokenizer,"revision":input.model.tokenizer_revision}, + "dataset":{"type":"file","path":input.dataset,"format":"weka_trace", + "sampling":"sequential","entries":sessions,"max_context_length":trace_context::LIMIT, + "ignore_trace_delays":false,"use_think_time_only":true, + "cache_bust":{"target":"first_turn_prefix","namespace":marker_namespace}}, + "phases":[{"name":"profiling","type":"concurrency","timing_mode":"agentic_replay", + "concurrency":concurrency,"sessions":sessions,"trajectory_start_min_ratio":0, + "trajectory_start_max_ratio":0,"burst_phase_starts":true}], + // Start the record processor before the one-shot dataset notification. + "runtime":{"record_processors":1}, + "artifacts":{"dir":input.output.join("upstream"),"summary":["json"], + "records":["jsonl"],"trace":true},"gpu_telemetry":{"enabled":false} + }})) +} diff --git a/tools/xtask/src/automation/agentx/cache_decisions.rs b/tools/xtask/src/automation/agentx/cache_decisions.rs new file mode 100644 index 0000000000..ad648eee2d --- /dev/null +++ b/tools/xtask/src/automation/agentx/cache_decisions.rs @@ -0,0 +1,411 @@ +//! Bounded, content-free projection of cache telemetry for AgentX diagnostics. +use crate::process::{ObservedLine, Stream, retained::MemberId}; +use serde::Serialize; +use serde_json::Value; +use std::collections::BTreeMap; + +const MAX_EVENTS: usize = 512; + +#[derive(Default, Serialize)] +pub(super) struct CacheDecisions { + schema_version: u8, + events: Vec, + omitted_events: u64, + exact_state_events: BTreeMap<&'static str, u64>, + exact_state_samples: Vec, + omitted_exact_state_samples: u64, +} + +#[derive(Serialize)] +struct ExactStateSample { + event: &'static str, + sequence: Option, + fields: BTreeMap<&'static str, u64>, +} + +#[derive(Serialize)] +struct CacheDecision { + kind: &'static str, + decision: &'static str, + source: Option<&'static str>, + at_unix_nanos: u64, + position: Option, + runtime_position: Option, +} + +impl CacheDecisions { + pub(super) fn new() -> Self { + Self { + schema_version: 4, + ..Self::default() + } + } + + pub(super) fn observe(&mut self, member: MemberId, line: ObservedLine<'_>) { + if member != MemberId::Seed { + return; + } + let exact_state = match line.stream { + Stream::Stdout => exact_state_jsonl_event(line.bytes), + Stream::Stderr => exact_state_event(line.bytes).map(|event| ExactStateSample { + event, + sequence: None, + fields: BTreeMap::new(), + }), + }; + if let Some(sample) = exact_state { + *self.exact_state_events.entry(sample.event).or_default() += 1; + if self.exact_state_samples.len() < MAX_EVENTS { + self.exact_state_samples.push(sample); + } else { + self.omitted_exact_state_samples = + self.omitted_exact_state_samples.saturating_add(1); + } + return; + } + if line.stream != Stream::Stderr { + return; + } + let Some(event) = parse(line.bytes) else { + return; + }; + if self.events.len() < MAX_EVENTS { + self.events.push(event); + } else { + self.omitted_events = self.omitted_events.saturating_add(1); + } + } +} + +fn exact_state_jsonl_event(line: &[u8]) -> Option { + if !std::str::from_utf8(line) + .ok()? + .contains("Skippy exact-state ") + { + return None; + } + let event: Value = serde_json::from_slice(line).ok()?; + if event.get("type")?.as_str()? != "info" { + return None; + } + let kind = exact_state_event(event.pointer("/data/message")?.as_str()?.as_bytes())?; + let fields = event + .pointer("/data/context") + .and_then(Value::as_str) + .map(exact_state_numeric_fields) + .unwrap_or_default(); + Some(ExactStateSample { + event: kind, + sequence: event.get("sequence").and_then(Value::as_u64), + fields, + }) +} + +fn exact_state_numeric_fields(context: &str) -> BTreeMap<&'static str, u64> { + context + .split_whitespace() + .filter_map(|field| { + let (key, value) = field.split_once('=')?; + let name = match key { + "position" => "position", + "logical_bytes" => "logical_bytes", + "physical_bytes" => "physical_bytes", + "limit_bytes" => "limit_bytes", + "max_entries" => "max_entries", + "kv_bytes" => "kv_bytes", + "recurrent_bytes" => "recurrent_bytes", + "pending_bytes" => "pending_bytes", + _ => return None, + }; + Some((name, value.parse().ok()?)) + }) + .collect() +} + +fn exact_state_event(line: &[u8]) -> Option<&'static str> { + match line.strip_prefix(b"Skippy exact-state ")? { + b"demotion_credit_full" => Some("demotion_credit_full"), + b"demotion_byte_full" => Some("demotion_byte_full"), + b"demotion_queue_full" => Some("demotion_queue_full"), + b"demotion_worker_stopped" => Some("demotion_worker_stopped"), + b"demotion_duplicate_or_stopped" => Some("demotion_duplicate_or_stopped"), + b"demotion_queued" => Some("demotion_queued"), + b"demotion_no_native_prefix" => Some("demotion_no_native_prefix"), + b"demotion_error" => Some("demotion_error"), + b"evicted_l1_count" => Some("evicted_l1_count"), + b"evicted_l1_soft" => Some("evicted_l1_soft"), + b"evicted_l1_hard" => Some("evicted_l1_hard"), + b"published_l1" => Some("published_l1"), + b"resident_branch_discarded" => Some("resident_branch_discarded"), + b"resident_capacity_displaced" => Some("resident_capacity_displaced"), + b"resident_restore_suffix_discarded" => Some("resident_restore_suffix_discarded"), + _ => None, + } +} + +fn parse(line: &[u8]) -> Option { + if !line.starts_with(b"{\"event\":") { + return None; + } + let event: Value = serde_json::from_slice(line).ok()?; + let kind = match event.get("event")?.as_str()? { + "stage.openai_kv_record_decision" => "record", + "stage.openai_kv_lookup_decision" => "lookup", + _ => return None, + }; + let attrs = event.get("attributes")?; + let decision = allowed_decision(attrs.get("skippy.kv.decision")?.as_str()?); + Some(CacheDecision { + kind, + decision, + source: attrs + .get("skippy.exact_cache.source") + .and_then(Value::as_str) + .and_then(allowed_source), + at_unix_nanos: event.get("start_time_unix_nanos")?.as_u64()?, + position: attrs + .get("skippy.exact_cache.recorded_tokens") + .or_else(|| attrs.get("skippy.exact_cache.restored_tokens")) + .or_else(|| attrs.get("skippy.kv.checkpoint_token_count")) + .and_then(Value::as_u64), + runtime_position: attrs + .get("skippy.kv.runtime_token_count") + .and_then(Value::as_u64), + }) +} + +fn allowed_source(value: &str) -> Option<&'static str> { + match value { + "resident_recurrent" => Some("resident_recurrent"), + "radix" => Some("radix"), + "l2" => Some("l2"), + "l3" => Some("l3"), + "l3-cachegen" => Some("l3-cachegen"), + _ => None, + } +} + +fn allowed_decision(value: &str) -> &'static str { + match value { + "post_decode_checkpoint_recorded" => "post_decode_checkpoint_recorded", + "post_decode_checkpoint_skipped" => "post_decode_checkpoint_skipped", + "post_decode_checkpoint_error" => "post_decode_checkpoint_error", + "post_decode_checkpoint_scheduler_error" => "post_decode_checkpoint_scheduler_error", + "prefill_checkpoint_recorded" => "prefill_checkpoint_recorded", + "prefill_checkpoint_skipped" => "prefill_checkpoint_skipped", + "prefill_checkpoint_error" => "prefill_checkpoint_error", + "prefill_checkpoint_scheduler_error" => "prefill_checkpoint_scheduler_error", + "shared_prefill_checkpoint_recorded" => "shared_prefill_checkpoint_recorded", + "shared_prefill_checkpoint_skipped" => "shared_prefill_checkpoint_skipped", + "shared_prefill_checkpoint_error" => "shared_prefill_checkpoint_error", + "shared_prefill_checkpoint_scheduler_error" => "shared_prefill_checkpoint_scheduler_error", + "chat_prefix_checkpoint_recorded" => "chat_prefix_checkpoint_recorded", + "chat_prefix_checkpoint_skipped" => "chat_prefix_checkpoint_skipped", + "chat_prefix_checkpoint_error" => "chat_prefix_checkpoint_error", + "chat_prefix_checkpoint_scheduler_error" => "chat_prefix_checkpoint_scheduler_error", + "exact_hit" => "exact_hit", + "resident_hit" => "resident_hit", + "chain_restore_hit" => "chain_restore_hit", + "miss" => "miss", + "resident_error" => "resident_error", + "exact_error" => "exact_error", + _ => "other", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn projects_numeric_cache_evidence_without_retaining_raw_content() { + let raw = br#"{"event":"stage.openai_kv_record_decision","attributes":{"skippy.kv.decision":"post_decode_checkpoint_recorded","skippy.exact_cache.recorded_tokens":110553,"authorization":"private-value","prompt":"token secret"},"start_time_unix_nanos":123}"#; + let mut decisions = CacheDecisions::new(); + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(projected.contains("110553")); + assert!(projected.contains("post_decode_checkpoint_recorded")); + assert!(!projected.contains("private-value")); + assert!(!projected.contains("token secret")); + assert!(!projected.contains("authorization")); + } + + #[test] + fn distinguishes_prefill_checkpoints_from_other_record_decisions() { + let mut decisions = CacheDecisions::new(); + for (decision, expected) in [ + ( + "shared_prefill_checkpoint_recorded", + "shared_prefill_checkpoint_recorded", + ), + ( + "chat_prefix_checkpoint_skipped", + "chat_prefix_checkpoint_skipped", + ), + ] { + let raw = format!( + r#"{{"event":"stage.openai_kv_record_decision","attributes":{{"skippy.kv.decision":"{decision}","prompt":"token secret"}},"start_time_unix_nanos":123}}"# + ); + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: raw.as_bytes(), + ending: crate::process::LineEnding::Lf, + }, + ); + assert_eq!(decisions.events.last().unwrap().decision, expected); + } + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(!projected.contains("token secret")); + } + + #[test] + fn projects_exact_hit_tier_and_restored_position_without_page_identity() { + let raw = br#"{"event":"stage.openai_kv_lookup_decision","attributes":{"skippy.kv.decision":"exact_hit","skippy.exact_cache.source":"resident_recurrent","skippy.exact_cache.restored_tokens":26938,"skippy.exact_cache.hit_page_id":"secret-page"},"start_time_unix_nanos":123}"#; + let mut decisions = CacheDecisions::new(); + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(projected.contains("\"source\":\"resident_recurrent\"")); + assert!(projected.contains("\"position\":26938")); + assert!(!projected.contains("secret-page")); + } + + #[test] + fn counts_exact_state_drops_without_retaining_context() { + let mut decisions = CacheDecisions::new(); + for line in [ + b"Skippy exact-state demotion_credit_full".as_slice(), + b" position=155509 secret=private-prompt".as_slice(), + b"Skippy exact-state demotion_credit_full".as_slice(), + b"Skippy exact-state demotion_queued".as_slice(), + ] { + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: line, + ending: crate::process::LineEnding::Lf, + }, + ); + } + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(projected.contains("\"demotion_credit_full\":2")); + assert!(projected.contains("\"demotion_queued\":1")); + assert!(!projected.contains("private-prompt")); + } + + #[test] + fn counts_standalone_jsonl_exact_state_events_without_retaining_context() { + let mut decisions = CacheDecisions::new(); + for bytes in [ + br#"{"data":{"context":"position=155509 logical_bytes=123 physical_bytes=456 limit_bytes=789 secret=private-prompt","message":"Skippy exact-state demotion_byte_full"},"schema_version":1,"sequence":17,"type":"info"}"#.as_slice(), + br#"{"data":{"message":"Skippy exact-state demotion_queued"},"type":"info"}"#.as_slice(), + br#"{"data":{"context":"position=44805","message":"Skippy exact-state resident_branch_discarded"},"type":"info"}"#.as_slice(), + br#"{"data":{"message":"Skippy exact-state demotion_credit_full"},"type":"native_log"}"#.as_slice(), + ] { + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stdout, + bytes, + ending: crate::process::LineEnding::Lf, + }, + ); + } + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(projected.contains("\"demotion_byte_full\":1")); + assert!(projected.contains("\"demotion_queued\":1")); + assert!(projected.contains("\"resident_branch_discarded\":1")); + assert_eq!(decisions.exact_state_samples[0].sequence, Some(17)); + assert_eq!(decisions.exact_state_samples[0].fields["position"], 155509); + assert_eq!( + decisions.exact_state_samples[0].fields["logical_bytes"], + 123 + ); + assert_eq!( + decisions.exact_state_samples[0].fields["physical_bytes"], + 456 + ); + assert_eq!(decisions.exact_state_samples[0].fields["limit_bytes"], 789); + assert!(!projected.contains("demotion_credit_full")); + assert!(!projected.contains("private-prompt")); + } + + #[test] + fn bounds_exact_state_samples_while_counting_every_event() { + let raw = br#"{"data":{"context":"position=42","message":"Skippy exact-state evicted_l1_soft"},"type":"info"}"#; + let mut decisions = CacheDecisions::new(); + for _ in 0..=MAX_EVENTS { + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stdout, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + } + assert_eq!(decisions.exact_state_samples.len(), MAX_EVENTS); + assert_eq!(decisions.omitted_exact_state_samples, 1); + assert_eq!(decisions.exact_state_events["evicted_l1_soft"], 513); + } + + #[test] + fn ignores_other_members_and_bounds_the_projection() { + let raw = br#"{"event":"stage.openai_kv_lookup_decision","attributes":{"skippy.kv.decision":"miss"},"start_time_unix_nanos":123}"#; + let mut decisions = CacheDecisions::new(); + decisions.observe( + MemberId::WorkerOne, + ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + assert!(decisions.events.is_empty()); + for _ in 0..=MAX_EVENTS { + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + } + assert_eq!(decisions.events.len(), MAX_EVENTS); + assert_eq!(decisions.omitted_events, 1); + } + + #[test] + fn unknown_decisions_cannot_copy_untrusted_text() { + let raw = br#"{"event":"stage.openai_kv_record_decision","attributes":{"skippy.kv.decision":"secret from untrusted source"},"start_time_unix_nanos":123}"#; + let mut decisions = CacheDecisions::new(); + decisions.observe( + MemberId::Seed, + ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + let projected = serde_json::to_string(&decisions).unwrap(); + assert!(projected.contains("\"decision\":\"other\"")); + assert!(!projected.contains("secret from untrusted source")); + } +} diff --git a/tools/xtask/src/automation/agentx/campaign.rs b/tools/xtask/src/automation/agentx/campaign.rs new file mode 100644 index 0000000000..1bbb2563a8 --- /dev/null +++ b/tools/xtask/src/automation/agentx/campaign.rs @@ -0,0 +1,234 @@ +//! Sweep ownership and partial-result publication, separate from child lifecycle. +use super::{Engine, Prepared, lifecycle, results, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; + +pub(super) fn run( + input: &Prepared, + engine: Engine, + only_concurrency: Option, +) -> DynResult<()> { + let concurrencies = selected_concurrencies(input.profile, only_concurrency)?; + super::hardware::capture(input)?; + let mut cells = Vec::new(); + let mut points = Vec::new(); + let mut notes = Vec::new(); + let engine = engine.label(); + for &concurrency in &concurrencies { + let mut cell: Prepared = serde_json::from_value(serde_json::to_value(input)?)?; + cell.output = input.output.join(format!("{engine}-c{concurrency}")); + std::fs::create_dir(&cell.output)?; + let cohort = super::trace_context::record(&cell, concurrency)?; + let outcome = lifecycle::execute(&cell, engine, concurrency) + .and_then(|()| results::read(&cell, engine, concurrency)); + match outcome { + Ok(summary) if complete(&summary) => { + points.push(results::point(&cell, concurrency)?); + notes.push(format!("{engine} c{concurrency}: complete")); + cells.push(summary); + } + Ok(mut summary) => { + summary["status"] = json!("incomplete"); + notes.push(format!( + "{engine} c{concurrency}: incomplete; excluded from serving points" + )); + cells.push(summary); + } + Err(error) => { + let mut status = failure_status(&cell.output); + let context_support = super::context_support::evidence(&cell.output); + if status == "failed" && context_support.is_some() { + status = "unsupported_context"; + } + notes.push(format!("{engine} c{concurrency}: {status}; see cell logs")); + cells.push(json!({"engine":engine,"concurrency":concurrency, + "status":status,"error":error.to_string(), + "cohort":cohort, + "context_support":context_support, + "memory":std::fs::read(cell.output.join("memory-summary.json")).ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()), + "memory_scope":"partial_attempt_not_comparable_to_completed_cells", + "capacity_policy":super::capacity::policy(engine, input.profile), + "configured_capacity":super::capacity::read_configured(&cell.output), + "native_capacity":super::capacity::read(&cell.output)})); + } + } + publish(input, engine, &cells, &points, ¬es)?; + // Never start another server if the previous process group was not reclaimed. + let evidence = cell.output.join("lifecycle.json"); + let lifecycle: Value = serde_json::from_slice(&std::fs::read(evidence)?)?; + if lifecycle["cleanup_complete"] != true { + return Err( + "cell cleanup incomplete; stopping sweep with prior results retained".into(), + ); + } + } + finish_sweep(concurrencies.len(), points.len()) +} + +fn selected_concurrencies(profile: super::Profile, only: Option) -> DynResult> { + match only { + Some(concurrency) if profile.concurrencies().contains(&concurrency) => { + Ok(vec![concurrency]) + } + Some(_) => Err("only-concurrency must be one of the selected profile's levels".into()), + None => Ok(profile.concurrencies().to_vec()), + } +} + +fn finish_sweep(expected: usize, completed: usize) -> DynResult<()> { + if completed != expected { + return Err(format!( + "AgentX sweep completed {completed}/{expected} cells; partial results retained" + ) + .into()); + } + Ok(()) +} + +fn complete(summary: &Value) -> bool { + summary["phase_outcome"]["cancelled"] == 0 && summary["phase_outcome"]["errors"] == 0 +} + +fn failure_status(output: &std::path::Path) -> &'static str { + let log = std::fs::read_to_string(output.join("server.stderr.log")) + .unwrap_or_default() + .to_ascii_lowercase(); + if [ + "out of memory", + "cuda_error_out_of_memory", + "cudamalloc failed", + ] + .iter() + .any(|needle| log.contains(needle)) + { + "out_of_memory" + } else if std::fs::read_to_string(output.join("lifecycle.json")) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .is_some_and(|record| { + matches!( + record["outcome"].as_str(), + Some("Deadline" | "ReadinessDeadline") + ) + }) + { + "timeout" + } else { + // A crash or readiness timeout is not evidence of a memory capacity limit. + "failed" + } +} + +fn publish( + input: &Prepared, + engine: &str, + cells: &[Value], + points: &[Value], + notes: &[String], +) -> DynResult<()> { + write( + &input.output.join("results.json"), + &json!({"profile":input.profile,"harness_version":input.profile.harness_version(),"model":input.model,"cells":cells}), + )?; + let Some(path) = std::env::var_os("JIANYANG_RESULT_PATH") else { + return Ok(()); + }; + use sha2::Digest; + let digest = if input.model.files.len() == 1 { + input.model.files[0].sha256.clone() + } else { + hex::encode(sha2::Sha256::digest(serde_json::to_vec( + &input.model.files, + )?)) + }; + // A wholly capacity-limited sweep has no fabricated zero-throughput points. + // Existing quality metrics let JY retain its explicit outcome counters. + write( + std::path::Path::new(&path), + &json!({"points":points,"notes":notes, + "quality":{"sweep":{"cells_finished":cells.len(),"cells_complete":points.len(), + "cells_unsupported_context":cells.iter().filter(|cell| cell["status"] == "unsupported_context").count(), + "cells_incomplete_or_failed":cells.len()-points.len()}}, + "provenance":{"stack_commit":std::env::var("JIANYANG_COMMIT")?, + "stack_name":engine,"model_package_ref":input.model.registry_ref(), + "model_package_sha256":digest}}), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn failed_and_incomplete_sweeps_fail_the_job() { + assert!(finish_sweep(3, 3).is_ok()); + for completed in 0..3 { + let error = finish_sweep(3, completed).unwrap_err().to_string(); + assert!(error.contains(&format!("{completed}/3"))); + assert!(error.contains("partial results retained")); + } + } + + #[test] + fn cancelled_requests_are_never_serving_points() { + assert!(complete( + &json!({"phase_outcome":{"cancelled":0,"errors":0}}) + )); + for value in [ + json!({}), + json!({"phase_outcome":{"cancelled":1,"errors":0}}), + json!({"phase_outcome":{"cancelled":0,"errors":1}}), + ] { + assert!(!complete(&value)); + } + } + #[test] + fn all_profiles_cover_every_requested_capacity() { + for profile in [ + super::super::Profile::Smoke, + super::super::Profile::Benchmark, + super::super::Profile::Comparison, + super::super::Profile::Contention, + ] { + let expected: &[u32] = if profile == super::super::Profile::Contention { + &[4, 8, 16] + } else { + &[1, 2, 4] + }; + assert_eq!(profile.concurrencies(), expected); + } + } + #[test] + fn diagnostic_concurrency_runs_one_cell_without_changing_default_sweep() { + assert_eq!( + selected_concurrencies(super::super::Profile::Comparison, None).unwrap(), + [1, 2, 4] + ); + assert_eq!( + selected_concurrencies(super::super::Profile::Comparison, Some(2)).unwrap(), + [2] + ); + assert!(selected_concurrencies(super::super::Profile::Comparison, Some(8)).is_err()); + assert_eq!( + selected_concurrencies(super::super::Profile::Contention, Some(16)).unwrap(), + [16] + ); + } + #[test] + fn memory_failure_requires_explicit_evidence() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(failure_status(dir.path()), "failed"); + std::fs::write( + dir.path().join("lifecycle.json"), + r#"{"outcome":"Deadline"}"#, + ) + .unwrap(); + assert_eq!(failure_status(dir.path()), "timeout"); + std::fs::write( + dir.path().join("server.stderr.log"), + "CUDA error: out of memory", + ) + .unwrap(); + assert_eq!(failure_status(dir.path()), "out_of_memory"); + } +} diff --git a/tools/xtask/src/automation/agentx/capacity.rs b/tools/xtask/src/automation/agentx/capacity.rs new file mode 100644 index 0000000000..3e31968b89 --- /dev/null +++ b/tools/xtask/src/automation/agentx/capacity.rs @@ -0,0 +1,217 @@ +//! Preserve native allocation evidence without equating offered load with slots. +use super::{Profile, trace_context}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::path::Path; + +pub(super) fn policy(engine: &str, profile: Profile) -> &'static str { + if engine == "skippy" { + "engine_default" + } else if matches!(profile, Profile::Comparison | Profile::Contention) { + "common_128k_per_slot_explicit_parallel" + } else { + "auto_context_explicit_parallel" + } +} + +pub(super) fn read(output: &Path) -> Value { + let mut observations = Vec::new(); + for stream in ["server.stdout.log", "server.stderr.log"] { + if let Ok(log) = std::fs::read_to_string(output.join(stream)) { + observations.extend( + log.lines() + .flat_map(|line| observations_in_line(stream, line)), + ); + } + } + json!({ + "status": if observations.is_empty() { "unavailable" } else { "observed" }, + "observations": observations, + }) +} + +/// The CLI reports the effective stage configuration before model load. Keep +/// this distinct from native allocation observations, which may be unavailable. +pub(super) fn read_configured(output: &Path) -> Value { + if let Some(config) = super::prepared_launch::configured(output) { + return config; + } + let observations = std::fs::read_to_string(output.join("server.stdout.log")) + .ok() + .map(|log| { + log.lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|event| event["type"] == "serving_capacity") + .filter_map(|event| { + let context_tokens_per_lane = + event["data"]["context_tokens_per_lane"].as_u64()?; + let lanes = event["data"]["lanes"].as_u64()?; + (context_tokens_per_lane > 0 && lanes > 0).then(|| { + json!({ + "source":"server.stdout.log:serving_capacity", + "context_tokens_per_lane":context_tokens_per_lane, + "lanes":lanes, + }) + }) + }) + .collect::>() + }) + .unwrap_or_default(); + json!({ + "status": if observations.is_empty() { "unavailable" } else { "observed" }, + "observations": observations, + }) +} + +pub(super) fn read_verified( + output: &Path, + engine: &str, + profile: Profile, + concurrency: u32, +) -> DynResult { + let evidence = read(output); + if engine == "llama" && matches!(profile, Profile::Comparison | Profile::Contention) { + let observations = evidence["observations"] + .as_array() + .ok_or("missing native context observations")?; + for (field, expected) in [ + ("n_slots", u64::from(concurrency)), + ("n_ctx_slot", trace_context::LIMIT), + ] { + let values: Vec<_> = observations + .iter() + .filter(|observation| observation["field"] == field) + .filter_map(|observation| observation["value"].as_u64()) + .collect(); + if values.is_empty() || values.iter().any(|&value| value != expected) { + return Err(format!( + "llama comparison {field} must be {expected}; observed {values:?}" + ) + .into()); + } + } + } + Ok(evidence) +} + +fn observations_in_line(stream: &str, line: &str) -> Vec { + // Retain each observation: warmup and model initialization can emit multiple + // context shapes, so selecting the last line would invent a final capacity. + // Server summaries can put several fields on one line. Keep the original + // field names: a per-slot limit is not an observed total KV allocation. + [ + "n_ctx_per_seq", + "n_ctx_seq", + "n_seq_max", + "n_ctx", + "n_slots", + "n_ctx_slot", + ] + .into_iter() + .filter_map(|field| { + let (_, suffix) = line.split_once(field)?; + let value = suffix.trim_start().strip_prefix('=')?; + let digits: String = value + .trim_start() + .chars() + .take_while(char::is_ascii_digit) + .collect(); + let value = digits.parse::().ok()?; + Some(json!({"source":stream,"field":field,"value":value})) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn comparison_capacity_policy_distinguishes_matched_context() { + assert_eq!( + policy("llama", Profile::Comparison), + "common_128k_per_slot_explicit_parallel" + ); + assert_eq!( + policy("llama", Profile::Smoke), + "auto_context_explicit_parallel" + ); + assert_eq!(policy("skippy", Profile::Comparison), "engine_default"); + } + + #[test] + fn configured_capacity_is_separate_from_native_evidence() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("server.stdout.log"), + concat!( + "{\"type\":\"serving_capacity\",\"data\":{\"context_tokens_per_lane\":131072,\"lanes\":4}}\n", + "{\"type\":\"status\",\"data\":{\"message\":\"ready\"}}\n", + ), + ) + .unwrap(); + let configured = read_configured(dir.path()); + assert_eq!(configured["status"], "observed"); + assert_eq!( + configured["observations"][0]["context_tokens_per_lane"], + 131072 + ); + assert_eq!(configured["observations"][0]["lanes"], 4); + assert_eq!(read(dir.path())["status"], "unavailable"); + } + + #[test] + fn comparison_requires_observed_matched_llama_slots() { + let dir = tempfile::tempdir().unwrap(); + assert!(read_verified(dir.path(), "llama", Profile::Comparison, 4).is_err()); + std::fs::write( + dir.path().join("server.stderr.log"), + "srv load_model: initializing, n_slots = 4, n_ctx_slot = 131072, kv_unified = 'false'", + ) + .unwrap(); + assert!(read_verified(dir.path(), "llama", Profile::Comparison, 4).is_ok()); + assert!(read_verified(dir.path(), "llama", Profile::Comparison, 2).is_err()); + std::fs::write( + dir.path().join("server.stderr.log"), + "srv load_model: initializing, n_slots = 4, n_ctx_slot = 262144, kv_unified = 'false'", + ) + .unwrap(); + assert!(read_verified(dir.path(), "llama", Profile::Comparison, 4).is_err()); + assert!(read_verified(dir.path(), "llama", Profile::Smoke, 4).is_ok()); + assert!(read_verified(dir.path(), "skippy", Profile::Comparison, 4).is_ok()); + } + + #[test] + fn retains_context_shapes_without_claiming_offered_load_is_capacity() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(read(dir.path())["status"], "unavailable"); + std::fs::write( + dir.path().join("server.stderr.log"), + "llama_context: n_ctx = 65536\nllama_context: n_ctx_per_seq = 16384\nllama_context: n_seq_max = 4\nllama_context: n_ctx_seq = 16384\n", + ) + .unwrap(); + let evidence = read(dir.path()); + assert_eq!(evidence["observations"][1]["field"], "n_ctx_per_seq"); + assert_eq!(evidence["observations"][1]["value"], 16384); + assert_eq!(evidence["observations"][3]["field"], "n_ctx_seq"); + assert_eq!(evidence["observations"][3]["value"], 16384); + assert_eq!(evidence["observations"].as_array().unwrap().len(), 4); + assert!(observations_in_line("stdout", "n_ctx_train = 262144").is_empty()); + } + + #[test] + fn retains_each_field_in_server_slot_summaries() { + let observations = observations_in_line( + "server.stderr.log", + "srv load_model: initializing, n_slots = 4, n_ctx_slot = 262144, kv_unified = 'false'", + ); + assert_eq!( + observations, + vec![ + json!({"source":"server.stderr.log","field":"n_slots","value":4}), + json!({"source":"server.stderr.log","field":"n_ctx_slot","value":262144}), + ] + ); + assert!(observations_in_line("stderr", "n_slots = auto, n_ctx_slot = -1").is_empty()); + } +} diff --git a/tools/xtask/src/automation/agentx/command.rs b/tools/xtask/src/automation/agentx/command.rs new file mode 100644 index 0000000000..cd7e7cb130 --- /dev/null +++ b/tools/xtask/src/automation/agentx/command.rs @@ -0,0 +1,88 @@ +use crate::{ + command::DynResult, + process::{self, ProcessSpec, Value}, +}; +use std::{ + path::{Path, PathBuf}, + time::Duration, +}; + +pub(super) fn executable(name: &str) -> DynResult { + if Path::new(name).is_absolute() { + return Ok(name.into()); + } + std::env::split_paths(&std::env::var_os("PATH").ok_or("PATH missing")?) + .map(|dir| dir.join(name)) + .find(|path| path.is_file()) + .ok_or_else(|| format!("missing executable: {name}").into()) +} +pub(super) fn spec(root: &Path, executable: &str, args: &[String]) -> DynResult { + let mut environment: std::collections::BTreeMap<_, _> = std::env::vars_os() + .filter(|(key, _)| { + matches!( + key.to_str(), + Some( + "PATH" + | "HOME" + | "TMPDIR" + | "CUDA_HOME" + | "CUDA_PATH" + | "SSL_CERT_FILE" + | "SSL_CERT_DIR" + | "HF_HOME" + | "HF_HUB_CACHE" + ) + ) + }) + .map(|(key, value)| (key, Value::Public(value))) + .collect(); + environment.insert("PYTHONDONTWRITEBYTECODE".into(), Value::Public("1".into())); + environment.insert("HF_HUB_OFFLINE".into(), Value::Public("1".into())); + Ok(ProcessSpec { + executable: self::executable(executable)?, + arguments: args.iter().map(|arg| Value::Public(arg.into())).collect(), + cwd: root.into(), + environment, + }) +} +pub(super) fn limits(seconds: u64) -> process::Limits { + process::Limits { + execution: Duration::from_secs(seconds), + graceful_shutdown: Duration::from_secs(15), + forced_shutdown: Duration::from_secs(5), + retained_bytes_per_stream: 65536, + readiness: process::Readiness::None, + completion: process::Completion::Exit, + } +} +pub(super) fn run(spec: &ProcessSpec, seconds: u64, log: &Path) -> DynResult<()> { + let interrupt = crate::automation::command_interrupt::Interrupt::install()?; + let result = process::supervise_raw_with_files( + spec, + &limits(seconds), + &interrupt.cancellation(), + process::OutputFiles { + stdout: Some(log.with_extension("stdout.log")), + stderr: Some(log.with_extension("stderr.log")), + }, + process::RawCaptureOptions { + stdout: None, + stderr: None, + }, + ); + let finish = interrupt.finish(); + let report = result?; + finish?; + if !report.process.success() { + return Err(format!( + "AgentX child failed: {}; see {}", + spec.executable.display(), + log.display() + ) + .into()); + } + Ok(()) +} +pub(super) fn strings(args: &[&str]) -> Vec { + args.iter().map(|arg| (*arg).into()).collect() +} diff --git a/tools/xtask/src/automation/agentx/comparison_cohort.rs b/tools/xtask/src/automation/agentx/comparison_cohort.rs new file mode 100644 index 0000000000..7d08fdddb3 --- /dev/null +++ b/tools/xtask/src/automation/agentx/comparison_cohort.rs @@ -0,0 +1,208 @@ +//! A fixed, complete local workload; independent of engine performance. +use super::{Prepared, inputs, trace_context, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + io::{BufRead, BufReader}, + path::Path, +}; + +// Pinned corpus: two <=64K, one 64–96K, one 96–128K peak-input trace. +// Within each band, smallest output totals among traces spanning <=600s. +// All requests, outputs, recorded delays and child topology remain unchanged. +pub(super) const IDS: [&str; 4] = [ + "12cfecf98c158ab54fb65980602421f00d69", + "1493faffdc8942e99daa22277f44871a40b8", + "9ec047754f4ddd94a59fcd0d85213d5f3b1b", + "bbdcb12440a7ab3496b9fac8b5f9824b1672", +]; + +pub(super) fn materialize(source: &Path, destination: &Path) -> DynResult<()> { + let mut selected = BTreeMap::new(); + for line in BufReader::new(std::fs::File::open(source)?).lines() { + let line = line?; + let trace: Value = serde_json::from_str(&line)?; + let id = trace["id"].as_str().ok_or("trace ID missing")?; + if IDS.contains(&id) && selected.insert(id.to_owned(), line).is_some() { + return Err("duplicate comparison trace".into()); + } + } + if selected.len() != IDS.len() { + return Err("fixed comparison cohort missing complete traces".into()); + } + let mut audit = Vec::new(); + let mut expected = BTreeMap::new(); + for (index, (id, line)) in selected.iter().enumerate() { + let trace: Value = serde_json::from_str(line)?; + let description = trace_context::describe(&trace, line.as_bytes())?; + if description["status"] != "eligible" { + return Err("fixed comparison trace exceeds common context budget".into()); + } + expected.extend(expected_turns(id, &trace)?); + audit.push(description); + std::fs::write(destination.join(format!("{index:04}.json")), line)?; + } + let parent = destination.parent().ok_or("comparison cohort parent")?; + write(&parent.join("expected-work.json"), &expected)?; + write( + &parent.join("cohort.json"), + &json!({ + "dataset_repo":inputs::DATA_REPO,"dataset_revision":inputs::DATA_REVISION, + "dataset_sha256":inputs::DATA_SHA,"trace_ids":IDS,"trace_context":audit, + "selection":"fixed_complete_context_stratified_v1", + "expected_requests":expected.len(),"expected_output_tokens":expected.values().sum::(), + "request_policy":"each_source_turn_exactly_once_no_dispatch_cutoff" + }), + ) +} + +pub(super) fn expected_turns(id: &str, trace: &Value) -> DynResult> { + let mut turns = BTreeMap::new(); + let requests = trace["requests"] + .as_array() + .ok_or("missing trace requests")?; + for (outer, request) in requests.iter().enumerate() { + if request["type"] == "subagent" { + let children = request["requests"] + .as_array() + .ok_or("missing child requests")?; + for (inner, child) in children.iter().enumerate() { + turns.insert( + turn_key(id, outer as u64, Some(inner as u64)), + output(child)?, + ); + } + } else { + turns.insert(turn_key(id, outer as u64, None), output(request)?); + } + } + Ok(turns) +} +fn output(request: &Value) -> DynResult { + if !matches!(request["type"].as_str(), Some("n" | "s")) { + return Err("unsupported comparison source request topology".into()); + } + Ok(request["out"] + .as_u64() + .ok_or("invalid requested output")? + .max(1)) +} +pub(super) fn turn_key(id: &str, outer: u64, inner: Option) -> String { + format!( + "{id}/{outer}/{}", + inner.map_or_else(|| "root".into(), |i| i.to_string()) + ) +} + +pub(super) fn configuration(input: &Prepared, port: u16, concurrency: u32) -> DynResult { + if ![1, 2, 4].contains(&concurrency) { + return Err("comparison supports c=1/2/4".into()); + } + super::agentic_config::configuration( + input, + port, + concurrency, + IDS.len(), + "mesh-agentx-comparison-v2", + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn comparison_finishes_sessions_without_a_duration_or_warmup_cutoff() { + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let dataset = dir.path().join("traces"); + std::fs::create_dir(&dataset).unwrap(); + std::fs::write(dir.path().join("cohort.json"), b"fixed source cohort").unwrap(); + let input = Prepared { + tools: None, + root: "/repo".into(), + output: "/results".into(), + weights: "/weights/model.gguf".into(), + dataset, + model: models[0].clone(), + profile: super::super::Profile::Comparison, + }; + let namespace = configuration(&input, 8080, 1).unwrap()["benchmark"]["dataset"] + ["cache_bust"]["namespace"] + .as_str() + .unwrap() + .to_owned(); + assert!(namespace.starts_with("mesh-agentx-comparison-v2:")); + for concurrency in [1, 2, 4] { + let config = configuration(&input, 8080, concurrency).unwrap(); + let benchmark = &config["benchmark"]; + assert_eq!(benchmark["dataset"]["cache_bust"]["namespace"], namespace); + assert!(benchmark["scenario"].is_null()); + assert_eq!( + benchmark["phases"], + json!([{ + "name":"profiling", "type":"concurrency", "timing_mode":"agentic_replay", + "concurrency":concurrency, "sessions":4, "trajectory_start_min_ratio":0, + "trajectory_start_max_ratio":0, "burst_phase_starts":true + }]) + ); + assert_eq!(benchmark["dataset"]["entries"], IDS.len()); + assert_eq!(benchmark["dataset"]["max_context_length"], 131072); + assert_eq!(benchmark["dataset"]["use_think_time_only"], true); + assert_eq!(benchmark["endpoint"]["extra"]["ignore_eos"], true); + assert_eq!(benchmark["endpoint"]["use_server_token_count"], true); + assert_eq!(benchmark["artifacts"]["records"], json!(["jsonl"])); + assert_eq!(benchmark["runtime"]["record_processors"], 1); + } + std::fs::write(dir.path().join("cohort.json"), b"different source cohort").unwrap(); + assert_ne!( + configuration(&input, 8080, 1).unwrap()["benchmark"]["dataset"]["cache_bust"]["namespace"], + namespace + ); + assert!(configuration(&input, 8080, 8).is_err()); + } + #[test] + fn expected_work_includes_children_and_zero_output_reservation() { + let trace = json!({"requests":[{"type":"n","out":3}, + {"type":"subagent","requests":[{"type":"s","out":0},{"type":"n","out":5}]}]}); + assert_eq!( + expected_turns("t", &trace).unwrap(), + BTreeMap::from([ + ("t/0/root".into(), 3), + ("t/1/0".into(), 1), + ("t/1/1".into(), 5) + ]) + ); + assert!( + expected_turns( + "t", + &json!({"requests":[{"type":"subagent","requests":[{"type":"subagent"}]}]}) + ) + .is_err() + ); + } + #[test] + fn materialization_retains_exact_rows_and_requires_every_selected_trace() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.jsonl"); + let dest = dir.path().join("traces"); + std::fs::create_dir(&dest).unwrap(); + let rows: Vec<_> = IDS + .iter() + .map(|id| json!({"id":id,"requests":[{"type":"n","in":120000,"out":2}]}).to_string()) + .collect(); + std::fs::write(&source, rows.join("\n")).unwrap(); + materialize(&source, &dest).unwrap(); + for (i, row) in rows.iter().enumerate() { + assert_eq!( + std::fs::read_to_string(dest.join(format!("{i:04}.json"))).unwrap(), + *row + ); + } + std::fs::write(&source, rows[..3].join("\n")).unwrap(); + assert!(materialize(&source, &dest).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/completed_work.rs b/tools/xtask/src/automation/agentx/completed_work.rs new file mode 100644 index 0000000000..79c1a3af79 --- /dev/null +++ b/tools/xtask/src/automation/agentx/completed_work.rs @@ -0,0 +1,141 @@ +//! Refuse fixed-work throughput if any source request is missing or repeated. +use super::{Prepared, comparison_cohort::turn_key, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + io::{BufRead, BufReader}, +}; + +pub(super) fn validate(input: &Prepared) -> DynResult { + let expected: BTreeMap = serde_json::from_slice(&std::fs::read( + input + .dataset + .parent() + .ok_or("cohort parent")? + .join("expected-work.json"), + )?)?; + let file = std::fs::File::open(input.output.join("upstream/profile_export.jsonl"))?; + let mut observed = BTreeMap::new(); + for line in BufReader::new(file).lines() { + let record: Value = serde_json::from_str(&line?)?; + if record["metadata"]["benchmark_phase"] == "profiling" { + add(&mut observed, &record)?; + } + } + check(&expected, &observed)?; + let result = json!({"status":"complete","requests":observed.len(), + "output_tokens":observed.values().sum::(), + "source_turn_output_sha256":hex::encode(Sha256::digest(serde_json::to_vec(&observed)?)), + "source_turns":observed}); + write(&input.output.join("completed-work.json"), &result)?; + Ok(result) +} +fn add(observed: &mut BTreeMap, record: &Value) -> DynResult<()> { + let m = &record["metadata"]; + if m["was_cancelled"] != false + || m["context_overflow_skip"] == true + || !record["error"].is_null() + { + return Err("fixed-work request failed, cancelled or overflowed".into()); + } + let id = m["source_trace_id"] + .as_str() + .ok_or("missing source trace ID")?; + let outer = m["source_outer_idx"] + .as_u64() + .ok_or("missing source turn index")?; + let inner = if m["source_inner_idx"].is_null() { + None + } else { + Some( + m["source_inner_idx"] + .as_u64() + .ok_or("invalid source child index")?, + ) + }; + let output = record["metrics"]["output_token_count"]["value"] + .as_f64() + .ok_or("missing output count")?; + if !output.is_finite() || output < 1.0 || output.fract() != 0.0 || output > (1_u64 << 53) as f64 + { + return Err("invalid actual output count".into()); + } + if observed + .insert(turn_key(id, outer, inner), output as u64) + .is_some() + { + return Err("fixed-work source turn repeated".into()); + } + Ok(()) +} +fn check(expected: &BTreeMap, observed: &BTreeMap) -> DynResult<()> { + if expected.is_empty() || expected != observed { + return Err(format!("fixed-work completion mismatch: expected {} source turns, observed {}; no comparable throughput",expected.len(),observed.len()).into()); + } + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn pinned_harness_records_cover_complete_roots_and_children() { + // Reduced actual 1.0.12.post1 export from a four-root mock replay. + let records = include_str!("../../../tests/fixtures/agentx/complete-trace-records.jsonl"); + let mut observed = BTreeMap::new(); + for line in records.lines() { + add(&mut observed, &serde_json::from_str(line).unwrap()).unwrap(); + } + let trace = json!({"requests":[{"type":"n","out":8}, + {"type":"subagent","requests":[{"type":"n","out":3},{"type":"n","out":4}]}, + {"type":"s","out":5}]}); + let expected = ["fixture-a", "fixture-1", "fixture-2", "fixture-3"] + .into_iter() + .flat_map(|id| super::super::comparison_cohort::expected_turns(id, &trace).unwrap()) + .collect(); + check(&expected, &observed).unwrap(); + assert_eq!(observed.len(), 16); + assert_eq!(observed.values().sum::(), 80); + } + #[test] + fn missing_extra_and_shortened_outputs_fail_closed() { + let expected = BTreeMap::from([("t/0/root".into(), 8), ("t/1/0".into(), 3)]); + assert!(check(&expected, &expected).is_ok()); + for observed in [ + BTreeMap::new(), + BTreeMap::from([("t/0/root".into(), 8)]), + BTreeMap::from([("t/0/root".into(), 8), ("t/1/0".into(), 2)]), + BTreeMap::from([ + ("t/0/root".into(), 8), + ("t/1/0".into(), 3), + ("t/2/root".into(), 1), + ]), + ] { + assert!(check(&expected, &observed).is_err()); + } + } + #[test] + fn duplicate_and_failed_source_turns_are_rejected() { + let record = json!({"metadata":{"source_trace_id":"t","source_outer_idx":1,"source_inner_idx":0, + "was_cancelled":false},"metrics":{"output_token_count":{"value":3.0}}}); + let mut observed = BTreeMap::new(); + add(&mut observed, &record).unwrap(); + assert_eq!(observed["t/1/0"], 3); + assert!(add(&mut observed, &record).is_err()); + let mut cancelled = record.clone(); + cancelled["metadata"]["was_cancelled"] = json!(true); + assert!(add(&mut BTreeMap::new(), &cancelled).is_err()); + for (key, value) in [ + ("context_overflow_skip", json!(true)), + ("was_cancelled", Value::Null), + ] { + let mut failed = record.clone(); + failed["metadata"][key] = value; + assert!(add(&mut BTreeMap::new(), &failed).is_err()); + } + let mut failed = record; + failed["error"] = json!({"message":"HTTP 429"}); + assert!(add(&mut BTreeMap::new(), &failed).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/container.rs b/tools/xtask/src/automation/agentx/container.rs new file mode 100644 index 0000000000..c9276bc0b8 --- /dev/null +++ b/tools/xtask/src/automation/agentx/container.rs @@ -0,0 +1,425 @@ +//! Own the Docker daemon's container as well as its attached client process. +use super::{Engine, Model, Profile, command, inputs, write}; +use crate::{command::DynResult, process}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +struct Launch { + root: PathBuf, + output: PathBuf, + artifacts: PathBuf, + hf_home: PathBuf, + commit: String, + name: String, + seconds: u64, +} + +pub(super) fn run(engine: Engine, model: &str, profile: Profile, output: PathBuf) -> DynResult<()> { + let launch = prepare(output, model)?; + let image = inspect(&launch)?; + let args = create_args(&launch, &image, engine, model, profile)?; + let spec = command::spec(&launch.root, "docker", &args)?; + if let Err(error) = command::run(&spec, 60, &launch.output.join("container-create")) { + // Creation can succeed at the daemon just as the attached client is cancelled. + let _ = remove(&launch); + return Err(error); + } + let interrupt = match crate::automation::command_interrupt::Interrupt::install() { + Ok(interrupt) => interrupt, + Err(error) => { + remove(&launch)?; + return Err(error.into()); + } + }; + let result = attached(&launch, &interrupt.cancellation()); + // A stopped container remains inspectable until explicitly removed. Cleanup + // gets an independent cancellation token so SIGTERM cannot skip daemon cleanup. + let cleanup = remove(&launch); + let finished = interrupt.finish(); + write( + &launch.artifacts.join("container-lifecycle.json"), + &json!({"container":launch.name,"image":image,"source_commit":launch.commit, + "benchmark_success":result.is_ok(),"removed":cleanup.is_ok()}), + )?; + let result_path = std::env::var_os("JIANYANG_RESULT_PATH").ok_or("JY result path missing")?; + let published = retain_result( + &launch.artifacts.join("container-result.json"), + Path::new(&result_path), + result, + ); + cleanup?; + finished?; + published +} + +fn retain_result(source: &Path, destination: &Path, outcome: DynResult<()>) -> DynResult<()> { + // Failed sweeps still publish valid earlier cells and explicit failure counts. + // A failure before the first cell may have no result at all; retain that error. + match std::fs::copy(source, destination) { + Ok(_) => outcome, + Err(error) if error.kind() == std::io::ErrorKind::NotFound && outcome.is_err() => outcome, + Err(error) => Err(error.into()), + } +} + +fn prepare(output: PathBuf, model_key: &str) -> DynResult { + if std::env::consts::OS != "linux" || std::env::consts::ARCH != "aarch64" { + return Err("AgentX Docker jobs must execute on the Linux ARM64 Spark".into()); + } + let commit = std::env::var("JIANYANG_COMMIT")?; + let run = std::env::var("JIANYANG_RUN_ID")?; + validate_identity(&commit, &run)?; + if !output.is_absolute() { + return Err("container output must be absolute".into()); + } + std::fs::create_dir(&output)?; + let artifacts = PathBuf::from( + std::env::var_os("JIANYANG_ARTIFACT_DIR").ok_or("JY artifact directory missing")?, + ) + .canonicalize()?; + let model = inputs::select_model(&std::env::current_dir()?, model_key)?; + let requested = std::env::var_os("HF_HOME").map(PathBuf::from); + let fallbacks = [ + PathBuf::from("/mnt/lab/huggingface"), + PathBuf::from("/mnt/model-store/hf"), + ]; + let hf_home = resolve_hf_home(requested.as_deref(), &fallbacks, &model)?; + write( + &artifacts.join("hf-home-selection.json"), + &json!({"requested":requested,"selected":hf_home,"model":model.key}), + )?; + let seconds = remaining(std::env::var("JIANYANG_DEADLINE_EPOCH")?.parse()?)?; + Ok(Launch { + root: std::env::current_dir()?, + output, + artifacts, + hf_home, + commit, + name: format!("agentx-{run}"), + seconds, + }) +} + +fn resolve_hf_home( + requested: Option<&Path>, + fallbacks: &[PathBuf], + model: &Model, +) -> DynResult { + let snapshot = format!("models--{}", model.repo.replace('/', "--")); + requested + .into_iter() + .chain(fallbacks.iter().map(PathBuf::as_path)) + .find(|home| { + home.is_absolute() + && home.is_dir() + && !model.files.is_empty() + && model.files.iter().all(|file| { + home.join("hub") + .join(&snapshot) + .join("snapshots") + .join(&model.revision) + .join(&file.name) + .is_file() + }) + }) + .map(Path::to_path_buf) + .ok_or_else(|| { + format!( + "pinned model weights are absent from host HF_HOME for {}", + model.key + ) + .into() + }) +} + +fn validate_identity(commit: &str, run: &str) -> DynResult<()> { + if commit.len() != 40 + || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) + || run.is_empty() + || run.len() > 100 + || !run + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + { + return Err("invalid JY source/run identity".into()); + } + Ok(()) +} + +fn remaining(deadline: u64) -> DynResult { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_secs(); + deadline + .checked_sub(now + 60) + .filter(|seconds| *seconds > 0) + .ok_or_else(|| "JY deadline has no time left for benchmark and cleanup".into()) +} + +fn inspect(launch: &Launch) -> DynResult { + let spec = command::spec( + &launch.root, + "docker", + &command::strings(&[ + "image", + "inspect", + &format!("mesh-agentx:{}", launch.commit), + ]), + )?; + let log = launch.output.join("image-inspect"); + command::run(&spec, 30, &log)?; + let bytes = std::fs::read(log.with_extension("stdout.log"))?; + let images: Value = serde_json::from_slice(&bytes)?; + let image = &images[0]; + if image["Architecture"] != "arm64" + || image["Config"]["Labels"]["org.opencontainers.image.revision"] != launch.commit + { + return Err("container architecture/source label does not match JY job".into()); + } + let id = image["Id"].as_str().ok_or("image ID missing")?; + if !id.starts_with("sha256:") || id.len() != 71 { + return Err("invalid immutable image ID".into()); + } + std::fs::write(launch.artifacts.join("container-image.json"), bytes)?; + Ok(id.into()) +} + +fn mount(source: &Path, destination: &str) -> DynResult { + let source = source.to_str().ok_or("non-Unicode mount path")?; + if source.contains([',', '\n', '\r']) { + return Err("unsupported Docker mount path".into()); + } + Ok(format!("type=bind,source={source},target={destination}")) +} + +fn create_args( + launch: &Launch, + image: &str, + engine: Engine, + model: &str, + profile: Profile, +) -> DynResult> { + let mut args = command::strings(&[ + "create", + "--name", + &launch.name, + "--gpus", + "all", + "--init", + "--label", + &format!("jianyang.run={}", launch.name), + "--mount", + &mount(&launch.output, "/output")?, + "--mount", + &mount(&launch.artifacts, "/artifacts")?, + "--mount", + &format!( + "{},readonly", + mount( + &launch.hf_home, + launch.hf_home.to_str().ok_or("HF_HOME path")?, + )? + ), + "--env", + &format!("HF_HOME={}", launch.hf_home.display()), + "--env", + "JIANYANG_ARTIFACT_DIR=/artifacts", + "--env", + "JIANYANG_RESULT_PATH=/artifacts/container-result.json", + "--env", + &format!("JIANYANG_COMMIT={}", launch.commit), + "--env", + &format!("AGENTX_CONTAINER_IMAGE={image}"), + ]); + #[cfg(unix)] + { + // SAFETY: getuid/getgid only read the current process's numeric identity. + let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; + args.extend(command::strings(&["--user", &format!("{uid}:{gid}")])); + } + args.extend(command::strings(&[ + image, + &launch.seconds.to_string(), + "/workspace/target/debug/xtask", + "automation", + "agentx", + "run", + "--engine", + engine.label(), + "--model", + model, + "--profile", + profile.label(), + "--output", + "/output/campaign", + ])); + Ok(args) +} + +fn attached(launch: &Launch, cancellation: &process::Cancellation) -> DynResult<()> { + let spec = command::spec( + &launch.root, + "docker", + &command::strings(&["start", "--attach", &launch.name]), + )?; + let report = process::supervise_inherited_closed_stdin( + &spec, + &docker_limits(launch.seconds + 30), + cancellation, + )?; + if report.outcome != process::Outcome::Exited + || !report.cleanup.complete + || report.failure.is_some() + || !report.status.is_some_and(|status| status.success()) + { + return Err("AgentX container failed, timed out, or was cancelled".into()); + } + Ok(()) +} + +fn remove(launch: &Launch) -> DynResult<()> { + let spec = command::spec( + &launch.root, + "docker", + &command::strings(&["container", "rm", "--force", &launch.name]), + )?; + let report = process::supervise_inherited_closed_stdin( + &spec, + &docker_limits(3), + &process::Cancellation::default(), + )?; + if !report.cleanup.complete || !report.status.is_some_and(|status| status.success()) { + return Err("Docker container removal failed".into()); + } + Ok(()) +} + +fn docker_limits(seconds: u64) -> process::Limits { + // JY escalates SIGTERM to SIGKILL after ten seconds. Leave time to remove + // the daemon-owned container after terminating an unresponsive Docker client. + let mut limits = command::limits(seconds); + limits.graceful_shutdown = std::time::Duration::from_secs(1); + limits.forced_shutdown = std::time::Duration::from_secs(1); + limits +} + +#[cfg(test)] +mod tests { + use super::super::FilePin; + use super::*; + + fn test_model(files: &[&str]) -> Model { + Model { + key: "test-model".into(), + family: "dense".into(), + repo: "org/model".into(), + revision: "pinned-revision".into(), + tokenizer: "org/model".into(), + tokenizer_revision: "pinned-revision".into(), + files: files + .iter() + .map(|name| FilePin { + name: (*name).into(), + sha256: "0".repeat(64), + }) + .collect(), + } + } + + fn cache_file(home: &Path, name: &str) { + let path = home + .join("hub/models--org--model/snapshots/pinned-revision") + .join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, b"weight").unwrap(); + } + + #[test] + fn selects_cache_containing_every_pinned_model_file() { + let dir = tempfile::tempdir().unwrap(); + let requested = dir.path().join("empty"); + let fallback = dir.path().join("cached"); + std::fs::create_dir_all(&requested).unwrap(); + let model = test_model(&["BF16/part-1.gguf", "BF16/part-2.gguf"]); + cache_file(&requested, "BF16/part-1.gguf"); + cache_file(&fallback, "BF16/part-1.gguf"); + cache_file(&fallback, "BF16/part-2.gguf"); + assert_eq!( + resolve_hf_home(Some(&requested), std::slice::from_ref(&fallback), &model).unwrap(), + fallback + ); + cache_file(&requested, "BF16/part-2.gguf"); + assert_eq!( + resolve_hf_home(Some(&requested), &[fallback], &model).unwrap(), + requested + ); + } + + #[test] + fn missing_cache_fails_before_container_launch() { + let dir = tempfile::tempdir().unwrap(); + assert!( + resolve_hf_home( + None, + &[dir.path().to_path_buf()], + &test_model(&["model.gguf"]) + ) + .is_err() + ); + } + #[test] + fn failed_container_retains_partial_results_without_becoming_successful() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("container-result.json"); + let destination = dir.path().join("result.json"); + let partial = r#"{"points":[{"concurrency":1}],"quality":{"sweep":{"cells_incomplete_or_failed":1}}}"#; + std::fs::write(&source, partial).unwrap(); + let result = retain_result(&source, &destination, Err("cell failed".into())); + assert_eq!(result.unwrap_err().to_string(), "cell failed"); + assert_eq!(std::fs::read_to_string(&destination).unwrap(), partial); + assert!(retain_result(&source, &destination, Ok(())).is_ok()); + } + + #[test] + fn missing_results_are_only_allowed_after_failure() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("missing.json"); + let destination = dir.path().join("result.json"); + assert!(retain_result(&source, &destination, Ok(())).is_err()); + let result = retain_result(&source, &destination, Err("startup failed".into())); + assert_eq!(result.unwrap_err().to_string(), "startup failed"); + assert!(!destination.exists()); + } + + #[test] + fn selected_engine_reaches_container_with_same_host_cache_mount() { + let launch = Launch { + root: "/repo".into(), + output: "/runs/one".into(), + artifacts: "/artifacts/one".into(), + hf_home: "/mnt/lab/huggingface".into(), + commit: "a".repeat(40), + name: "agentx-run_one".into(), + seconds: 600, + }; + for engine in [Engine::Llama, Engine::Skippy] { + let args = + create_args(&launch, "sha256:test", engine, "model", Profile::Smoke).unwrap(); + assert!( + args.windows(2) + .any(|pair| pair == ["--engine", engine.label()]) + ); + assert!(args.windows(2).any(|pair| pair == ["--gpus", "all"])); + assert!(args.iter().any(|arg| arg + == "type=bind,source=/mnt/lab/huggingface,target=/mnt/lab/huggingface,readonly")); + } + } + #[test] + fn rejects_ambiguous_identity_and_mounts() { + assert!(validate_identity(&"a".repeat(40), "run_abc").is_ok()); + assert!(validate_identity("main", "run_abc").is_err()); + assert!(validate_identity(&"a".repeat(40), "../other").is_err()); + assert!(mount(Path::new("/cache,readonly"), "/cache").is_err()); + assert!(remaining(0).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/contention_cohort.rs b/tools/xtask/src/automation/agentx/contention_cohort.rs new file mode 100644 index 0000000000..3437a848ec --- /dev/null +++ b/tools/xtask/src/automation/agentx/contention_cohort.rs @@ -0,0 +1,269 @@ +//! Bounded two-turn sessions for concurrency diagnosis. +use super::{Prepared, comparison_cohort, inputs, trace_context, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::{BufRead, BufReader}, + path::Path, +}; + +pub(super) const SESSIONS: usize = 16; +const OUTPUT_TOKENS_PER_TURN: u64 = 128; +const INPUT_TOKENS_PER_TURN_CAP: u64 = 8192; +const MAX_SECOND_TURN_DELAY_SECS: f64 = 60.0; + +struct Candidate { + id: String, + source_requested_output_tokens: u64, + source_requested_turns: usize, + profile_requested_output_tokens: u64, + line: String, + source_context: Value, + profile_context: Value, +} + +pub(super) fn materialize(source: &Path, destination: &Path) -> DynResult<()> { + let mut seen = BTreeSet::new(); + let mut eligible = Vec::new(); + for line in BufReader::new(std::fs::File::open(source)?).lines() { + let line = line?; + let trace: Value = serde_json::from_str(&line)?; + let id = trace["id"].as_str().ok_or("trace ID missing")?.to_owned(); + if !seen.insert(id.clone()) { + return Err("duplicate contention trace".into()); + } + let source_context = trace_context::describe(&trace, line.as_bytes())?; + if source_context["status"] != "eligible" { + continue; + } + let Some(profile) = two_turn_profile(&trace)? else { + continue; + }; + let turns = comparison_cohort::expected_turns(&id, &trace)?; + let profile_turns = comparison_cohort::expected_turns(&id, &profile)?; + let profile_line = serde_json::to_string(&profile)?; + let profile_context = trace_context::describe(&profile, profile_line.as_bytes())?; + eligible.push(Candidate { + id, + source_requested_output_tokens: turns.values().sum(), + source_requested_turns: turns.len(), + profile_requested_output_tokens: profile_turns.values().sum(), + line: profile_line, + source_context, + profile_context, + }); + } + eligible.sort_by(|a, b| { + a.source_requested_output_tokens + .cmp(&b.source_requested_output_tokens) + .then_with(|| a.id.cmp(&b.id)) + }); + if eligible.len() < SESSIONS { + return Err("fewer than 16 two-turn context-compatible AgentX traces".into()); + } + let selected: Vec<_> = eligible.into_iter().take(SESSIONS).collect(); + let parent = destination.parent().ok_or("contention cohort parent")?; + let audit: Vec<_> = selected + .iter() + .map(|candidate| candidate.profile_context.clone()) + .collect(); + let mut expected = BTreeMap::new(); + for (index, candidate) in selected.iter().enumerate() { + std::fs::write( + destination.join(format!("{index:04}.json")), + &candidate.line, + )?; + let trace: Value = serde_json::from_str(&candidate.line)?; + expected.extend(comparison_cohort::expected_turns(&candidate.id, &trace)?); + } + write(&parent.join("expected-work.json"), &expected)?; + write( + &parent.join("cohort.json"), + &json!({ + "dataset_repo":inputs::DATA_REPO,"dataset_revision":inputs::DATA_REVISION, + "dataset_sha256":inputs::DATA_SHA, + "trace_ids":selected.iter().map(|candidate| &candidate.id).collect::>(), + "trace_context":audit, + "source_trace_context":selected.iter().map(|candidate| &candidate.source_context).collect::>(), + "selection":"16_lowest_source_output_two_root_turns_input8k_output128_v2", + "source_requested_turns":selected.iter().map(|candidate| candidate.source_requested_turns).sum::(), + "source_requested_output_tokens":selected.iter().map(|candidate| candidate.source_requested_output_tokens).sum::(), + "profile_requested_turns":SESSIONS * 2, + "profile_requested_output_tokens":selected.iter().map(|candidate| candidate.profile_requested_output_tokens).sum::(), + "output_tokens_per_turn_cap":OUTPUT_TOKENS_PER_TURN, + "input_tokens_per_turn_cap":INPUT_TOKENS_PER_TURN_CAP, + "max_second_turn_delay_seconds":MAX_SECOND_TURN_DELAY_SECS, + "request_policy":"fixed_16_two_turn_sessions_not_full_agentx_qualification", + }), + ) +} + +pub(super) fn configuration(input: &Prepared, port: u16, concurrency: u32) -> DynResult { + super::agentic_config::configuration( + input, + port, + concurrency, + SESSIONS, + "mesh-agentx-contention-v2", + ) +} + +fn two_turn_profile(trace: &Value) -> DynResult> { + let requests = trace["requests"] + .as_array() + .ok_or("missing trace requests")?; + let [first, second, ..] = requests.as_slice() else { + return Ok(None); + }; + if ![first, second] + .iter() + .all(|turn| matches!(turn["type"].as_str(), Some("n" | "s"))) + { + return Ok(None); + } + let (Some(first_at), Some(second_at)) = (first["t"].as_f64(), second["t"].as_f64()) else { + return Ok(None); + }; + if !(0.0..=MAX_SECOND_TURN_DELAY_SECS).contains(&(second_at - first_at)) { + return Ok(None); + } + let block_size = trace["block_size"] + .as_u64() + .ok_or("invalid trace block size")?; + if block_size == 0 { + return Err("zero trace block size".into()); + } + let mut selected = Vec::with_capacity(2); + for turn in [first, second] { + let output = turn["out"].as_u64().ok_or("invalid requested output")?; + let input = turn["in"].as_u64().ok_or("invalid requested input")?; + let capped_input = input.min(INPUT_TOKENS_PER_TURN_CAP); + let mut capped = turn.clone(); + capped["out"] = json!(output.clamp(1, OUTPUT_TOKENS_PER_TURN)); + capped["in"] = json!(capped_input); + if let Some(hashes) = turn["hash_ids"].as_array() { + let blocks = capped_input.div_ceil(block_size) as usize; + capped["hash_ids"] = json!(hashes.iter().take(blocks).collect::>()); + } + selected.push(capped); + } + let mut profile = trace.clone(); + profile["requests"] = json!(selected); + Ok(Some(profile)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selects_the_same_bounded_two_turn_traces_independent_of_source_order() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.jsonl"); + let rows: Vec<_> = (0..20) + .map(|index| { + json!({"id":format!("trace-{index:02}"),"block_size":64, + "requests":[{"type":"n","t":0,"in":100,"out":20-index}, + {"type":"s","t":1,"in":10000,"out":256,"hash_ids":(0..157).collect::>()}, + {"type":"n","t":2,"in":300,"out":512}]}) + .to_string() + }) + .collect(); + std::fs::write(&source, rows.join("\n")).unwrap(); + let first = dir.path().join("first/traces"); + std::fs::create_dir_all(&first).unwrap(); + materialize(&source, &first).unwrap(); + let first_cohort: Value = serde_json::from_slice( + &std::fs::read(first.parent().unwrap().join("cohort.json")).unwrap(), + ) + .unwrap(); + assert_eq!( + first_cohort["trace_ids"].as_array().unwrap().len(), + SESSIONS + ); + assert_eq!(first_cohort["trace_ids"][0], "trace-19"); + assert_eq!( + first_cohort["source_requested_output_tokens"], + 136 + 16 * 768 + ); + assert_eq!( + first_cohort["profile_requested_output_tokens"], + 136 + 16 * 128 + ); + assert_eq!(first_cohort["profile_requested_turns"], 32); + let expected: BTreeMap = serde_json::from_slice( + &std::fs::read(first.parent().unwrap().join("expected-work.json")).unwrap(), + ) + .unwrap(); + assert_eq!(expected.len(), 32); + assert_eq!(expected.values().sum::(), 136 + 16 * 128); + let first_trace: Value = + serde_json::from_slice(&std::fs::read(first.join("0000.json")).unwrap()).unwrap(); + assert_eq!(first_trace["requests"].as_array().unwrap().len(), 2); + assert_eq!(first_trace["requests"][1]["out"], 128); + assert_eq!(first_trace["requests"][1]["in"], 8192); + assert_eq!( + first_trace["requests"][1]["hash_ids"] + .as_array() + .unwrap() + .len(), + 128 + ); + std::fs::write( + &source, + rows.into_iter().rev().collect::>().join("\n"), + ) + .unwrap(); + let second = dir.path().join("second/traces"); + std::fs::create_dir_all(&second).unwrap(); + materialize(&source, &second).unwrap(); + let second_cohort: Value = serde_json::from_slice( + &std::fs::read(second.parent().unwrap().join("cohort.json")).unwrap(), + ) + .unwrap(); + assert_eq!(first_cohort, second_cohort); + } + + #[test] + fn excludes_delayed_or_branching_first_followups() { + let ordinary = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, + {"type":"s","t":2,"in":200,"out":1}]}); + assert!(two_turn_profile(&ordinary).unwrap().is_some()); + let delayed = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, + {"type":"s","t":61,"in":200,"out":1}]}); + assert!(two_turn_profile(&delayed).unwrap().is_none()); + let branched = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, + {"type":"subagent","requests":[]}]}); + assert!(two_turn_profile(&branched).unwrap().is_none()); + } + + #[test] + fn config_runs_all_sessions_without_scenario_warmup_or_duration() { + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let dataset = dir.path().join("traces"); + std::fs::create_dir(&dataset).unwrap(); + std::fs::write(dir.path().join("cohort.json"), b"bounded source cohort").unwrap(); + let input = Prepared { + tools: None, + root: "/repo".into(), + output: "/results".into(), + weights: "/weights/model.gguf".into(), + dataset, + model: models[1].clone(), + profile: super::super::Profile::Contention, + }; + let config = configuration(&input, 8080, 16).unwrap(); + let benchmark = &config["benchmark"]; + assert_eq!(benchmark["dataset"]["entries"], SESSIONS); + assert_eq!(benchmark["phases"][0]["sessions"], SESSIONS); + assert_eq!(benchmark["phases"][0]["concurrency"], 16); + assert!(benchmark["phases"][0]["duration"].is_null()); + assert!(benchmark["phases"][0]["warmup_requests_per_lane"].is_null()); + assert!(benchmark["scenario"].is_null()); + } +} diff --git a/tools/xtask/src/automation/agentx/context_support.rs b/tools/xtask/src/automation/agentx/context_support.rs new file mode 100644 index 0000000000..12cdbd098e --- /dev/null +++ b/tools/xtask/src/automation/agentx/context_support.rs @@ -0,0 +1,125 @@ +//! Keep context-limited workloads visible without publishing unequal-work metrics. +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::path::Path; + +pub(super) fn evidence(output: &Path) -> Option { + read(output).ok() +} + +fn read(output: &Path) -> DynResult { + let lifecycle: Value = serde_json::from_slice(&std::fs::read(output.join("lifecycle.json"))?)?; + if lifecycle["clean"] != true || lifecycle["cleanup_complete"] != true { + return Err("context support requires clean process completion".into()); + } + let export_path = output.join("upstream/profile_export_aiperf.json"); + let export: Value = serde_json::from_slice(&std::fs::read(&export_path)?)?; + let overflows = request_count(&export, "context_overflow_count")?; + if export["was_cancelled"] != false + || export["metadata"]["submission_valid"] != false + || optional_errors(&export)? != 0 + { + return Err("export contains other failures or invalid provenance".into()); + } + let phase = super::phase_outcome::context_limited( + &std::fs::read_to_string(output.join("upstream/logs/aiperf.log"))?, + request_count(&export, "request_count")?, + overflows, + )?; + Ok(json!({ + "reason":"recorded requests exceed the engine's context capacity; traces were not truncated", + "context_overflow_requests":overflows, + "phase_outcome":phase, + "export_sha256":crate::product::digest::file_sha256(&export_path).map_err(|e|e.error)?, + "export_path":"upstream/profile_export_aiperf.json", + "trace_diagnostics_path":"upstream/logs/aiperf.log" + })) +} + +fn optional_errors(export: &Value) -> DynResult { + if export["error_request_count"].is_null() { + Ok(0) + } else { + request_count(export, "error_request_count") + } +} + +fn request_count(export: &Value, name: &str) -> DynResult { + let value = export[name]["avg"] + .as_f64() + .ok_or("missing request count")?; + if export[name]["unit"] != "requests" + || !value.is_finite() + || value < 0.0 + || value.fract() != 0.0 + || value > (1_u64 << 53) as f64 + { + return Err("invalid request count".into()); + } + Ok(value as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture(output: &Path, export: &Value, log: &str) { + std::fs::create_dir_all(output.join("upstream/logs")).unwrap(); + std::fs::write( + output.join("lifecycle.json"), + r#"{"clean":true,"cleanup_complete":true}"#, + ) + .unwrap(); + std::fs::write( + output.join("upstream/profile_export_aiperf.json"), + export.to_string(), + ) + .unwrap(); + std::fs::write(output.join("upstream/logs/aiperf.log"), log).unwrap(); + } + + #[test] + fn identifies_context_only_rejection_without_publishing_throughput() { + let dir = tempfile::tempdir().unwrap(); + let export = json!({"was_cancelled":false,"metadata":{"submission_valid":false}, + "context_overflow_count":{"unit":"requests","avg":1.0}, + "request_count":{"unit":"requests","avg":4.0}}); + let log = "Phase profiling (profiling) complete | completed=5, cancelled=0, errors=1 | elapsed=151.96s"; + fixture(dir.path(), &export, log); + let record = evidence(dir.path()).unwrap(); + assert_eq!(record["context_overflow_requests"], 1); + assert!(record.get("output_tok_s").is_none()); + for (field, value) in [ + ("was_cancelled", json!(true)), + ("error_request_count", json!({"unit":"requests","avg":1})), + ("error_request_count", json!({"unit":"requests","avg":-1})), + ("context_overflow_count", json!({"unit":"requests","avg":0})), + ( + "context_overflow_count", + json!({"unit":"requests","avg":1.5}), + ), + ("context_overflow_count", Value::Null), + ] { + let mut invalid = export.clone(); + invalid[field] = value; + fixture(dir.path(), &invalid, log); + assert!(evidence(dir.path()).is_none(), "{field}"); + } + for invalid in [ + log.replace("cancelled=0", "cancelled=1"), + log.replace("errors=1", "errors=2"), + log.replace("completed=5", "completed=4"), + String::new(), + ] { + fixture(dir.path(), &export, &invalid); + assert!(evidence(dir.path()).is_none()); + } + fixture(dir.path(), &export, log); + std::fs::write( + dir.path().join("lifecycle.json"), + r#"{"clean":false,"cleanup_complete":true}"#, + ) + .unwrap(); + assert!(evidence(dir.path()).is_none()); + } +} diff --git a/tools/xtask/src/automation/agentx/final_sweep.rs b/tools/xtask/src/automation/agentx/final_sweep.rs new file mode 100644 index 0000000000..3eedb23c42 --- /dev/null +++ b/tools/xtask/src/automation/agentx/final_sweep.rs @@ -0,0 +1,219 @@ +//! One complete model/backend campaign: six balanced engine sweeps, no worker rebuilds. +use super::{ + Engine, Model, Prepared, Profile, campaign, comparison_cohort, inputs, + prepared_tools::{self, Backend, File, Tools}, + results, write, +}; +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +pub(super) const ORDER: [&str; 6] = ["llama", "skippy", "skippy", "llama", "llama", "skippy"]; +pub(super) const COHORT_SHA: &str = + "1d4b4c739312ca34a871dbfe85c6e50d533496b2e72782bfdf57b18d515a6c46"; +pub(super) const USAGE: &str = "automation agentx {pin|comparison|mlflow-export|mlflow-publish} --input ABS_JSON --output ABS_FRESH_PATH"; + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Request { + pub schema_version: u32, + pub campaign: String, + pub workspace: PathBuf, + pub model_key: String, + pub model: PathBuf, + pub corpus: File, + pub tools: Tools, +} +impl Request { + fn validate(&self) -> DynResult { + if self.schema_version != 1 + || self.campaign.is_empty() + || self.campaign.len() > 128 + || !self + .campaign + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + { + return Err("invalid final AgentX campaign identity".into()); + } + prepared_tools::absolute(&self.workspace)?; + prepared_tools::absolute(&self.model)?; + if !self.workspace.join("Justfile").is_file() { + return Err("owning workspace missing".into()); + } + self.corpus.verify()?; + if self.corpus.sha256 != inputs::DATA_SHA { + return Err("final comparison corpus pin differs".into()); + } + let catalog = std::fs::read( + self.workspace + .join("skippy/evals/kv-validation/models.json"), + )?; + if inputs::digest(&catalog) + != "6a2b724cf32208186d80ac614e21a168bfc08ca72e55afdabc3dc39b338c9206" + { + return Err("final comparison requires the exact historical four-model catalog".into()); + } + let model = inputs::select_model(&self.workspace, &self.model_key)?; + inputs::verify(&self.model, &model.files[0].sha256)?; + self.tools.verify(&self.workspace)?; + Ok(model) + } +} +pub(super) fn command(args: &[String]) -> DynResult<()> { + let [verb, input_flag, input, output_flag, output] = args else { + return Err(USAGE.into()); + }; + if input_flag != "--input" || output_flag != "--output" { + return Err("invalid final AgentX arguments".into()); + } + let input = Path::new(input); + let output = Path::new(output); + prepared_tools::absolute(input)?; + prepared_tools::absolute(output)?; + let bytes = crate::automation::receipt_files::bounded(input, 1024 * 1024)?; + if verb == "mlflow-export" { + return super::mlflow_export::run(serde_json::from_slice(&bytes)?, output); + } + if verb == "mlflow-publish" { + return super::mlflow_publish::run(serde_json::from_slice(&bytes)?, output); + } + if verb == "pin" { + let mut request: Request = serde_json::from_slice(&bytes)?; + request.corpus.sha256 = + crate::product::digest::file_sha256(&request.corpus.path).map_err(|e| e.error)?; + request.tools.pin()?; + request.validate()?; + return crate::automation::receipt_files::fresh( + output, + &serde_json::to_vec_pretty(&request)?, + ); + } + if verb == "comparison" { + return run(serde_json::from_slice(&bytes)?, output); + } + Err(format!("unknown AgentX command: {verb}").into()) +} +fn run(request: Request, output: &Path) -> DynResult<()> { + std::fs::create_dir(output)?; + write(&output.join("request.json"), &request)?; + let mut arms = Vec::new(); + let mut result = execute(&request, output, &mut arms); + let status = if result.is_ok() { "passed" } else { "failed" }; + let mut report = json!({"schema_version":1,"campaign":request.campaign,"model_key":request.model_key,"request":request, + "backend":request.tools.backend,"status":status,"arms":arms,"error":result.as_ref().err().map(ToString::to_string), + "repeat_order":ORDER,"concurrencies":[1,2,4],"scope":if request.tools.backend==Backend::Cpu{"cpu_diagnostic_not_gpu_performance"}else{"fixed_complete_AgentX_comparison"}, + "jy_job_id":std::env::var("JIANYANG_JOB_ID").ok(),"jy_run_id":std::env::var("JIANYANG_RUN_ID").ok(), + "source_attribution":{"product":request.tools.product_source_commit,"native":request.tools.native_source_commit, + "standard_upstream":request.tools.standard_upstream,"automation_binary_sha256":crate::product::digest::file_sha256(&std::env::current_exe()?).map_err(|e|e.error)?}, + "mlflow":{"experiment_id":"6","experiment_name":"agentx-skippy-vs-llama","publication":"not_published; export/audit separately"}}); + write(&output.join("result.json"), &report)?; + if let Err(error) = results::archive(output) { + report["status"] = json!("failed"); + report["error"] = json!(format!( + "evidence archive failed: {error}; execution error: {:?}", + result.as_ref().err().map(ToString::to_string) + )); + write(&output.join("result.json"), &report)?; + result = Err(error); + } + if let Some(path) = std::env::var_os("JIANYANG_RESULT_PATH") { + write(Path::new(&path), &report)?; + } + result +} +fn execute(request: &Request, output: &Path, arms: &mut Vec) -> DynResult<()> { + admit_host(request.tools.backend, output)?; + let model = request.validate()?; + super::prepared_launch::doctor(&request.tools, &request.workspace, output)?; + write(&output.join("prepared-identities.json"), request)?; + let traces = output.join("traces"); + std::fs::create_dir(&traces)?; + comparison_cohort::materialize(&request.corpus.path, &traces)?; + let expected: Value = serde_json::from_slice(&std::fs::read(output.join("cohort.json"))?)?; + if expected["expected_requests"] != 69 || expected["expected_output_tokens"] != 18713 { + return Err("comparison source work must remain69requests/18713outputs".into()); + } + for (index, engine) in ORDER.into_iter().enumerate() { + let arm = output.join(format!("{}-{engine}", index + 1)); + std::fs::create_dir(&arm)?; + let prepared = Prepared { + tools: Some(request.tools.clone()), + root: request.workspace.clone(), + output: arm.clone(), + model: model.clone(), + weights: request.model.clone(), + dataset: traces.clone(), + profile: Profile::Comparison, + }; + let outcome = campaign::run( + &prepared, + if engine == "llama" { + Engine::Llama + } else { + Engine::Skippy + }, + None, + ); + let cells: Value = serde_json::from_slice(&std::fs::read(arm.join("results.json"))?)?; + arms.push(json!({"index":index+1,"engine":engine,"cells":cells["cells"],"status":if outcome.is_ok(){"passed"}else{"failed"}})); + write( + &output.join("progress.json"), + &json!({"arms":arms,"expected_arms":6}), + )?; + outcome?; + } + validate_work(arms)?; + request.validate()?; + Ok(()) +} +fn admit_host(backend: Backend, output: &Path) -> DynResult<()> { + let spec = super::command::spec(output, "hostname", &["-s".into()])?; + super::command::run(&spec, 10, &output.join("hostname"))?; + let host = std::fs::read_to_string(output.join("hostname.stdout.log"))?; + if ["spark-db08", "spark-9f06", "spark-000280", "spark-000499"].contains(&host.trim()) { + return Err("excluded benchmark host".into()); + } + if (backend == Backend::Metal && std::env::consts::OS != "macos") + || (backend == Backend::Cuda && std::env::consts::OS != "linux") + { + return Err("prepared backend does not match host OS".into()); + } + Ok(()) +} +pub(super) fn validate_work(arms: &[Value]) -> DynResult<()> { + if arms.len() != 6 { + return Err("incomplete ABBAAB campaign".into()); + } + let mut work = None; + for (arm, engine) in arms.iter().zip(ORDER) { + if arm["engine"] != engine || arm["status"] != "passed" { + return Err("ABBAAB engine order/outcome differs".into()); + } + let cells = arm["cells"].as_array().ok_or("campaign cells missing")?; + if cells.len() != 3 { + return Err("comparison requires allc1/c2/c4 cells".into()); + } + for (cell, concurrency) in cells.iter().zip([1, 2, 4]) { + let hash = cell["completed_work"]["source_turn_output_sha256"] + .as_str() + .ok_or("completed-work hash missing")?; + if cell["offered_sessions"] != concurrency + || cell["completed_work"]["requests"] != 69 + || cell["output_tok_s"] + .as_f64() + .is_none_or(|v| !v.is_finite() || v <= 0.0) + || cell["completed_work"]["output_tokens"] != 18713 + || cell["cohort"]["selected_cohort_sha256"] != COHORT_SHA + || cell["phase_outcome"]["errors"] != 0 + || cell["phase_outcome"]["cancelled"] != 0 + || work.is_some_and(|previous| previous != hash) + { + return Err("fixed-work/cohort/concurrency mismatch".into()); + } + work = Some(hash); + } + } + Ok(()) +} diff --git a/tools/xtask/src/automation/agentx/final_sweep_tests.rs b/tools/xtask/src/automation/agentx/final_sweep_tests.rs new file mode 100644 index 0000000000..0968d886f5 --- /dev/null +++ b/tools/xtask/src/automation/agentx/final_sweep_tests.rs @@ -0,0 +1,122 @@ +use super::{ + final_sweep::{self, COHORT_SHA, ORDER}, + prepared_launch, + prepared_tools::{Tools, Tree}, +}; +use serde_json::{Value, json}; + +pub(super) fn arms() -> Vec { + ORDER.into_iter().enumerate().map(|(index,engine)|json!({"index":index+1,"engine":engine,"status":"passed", + "cells":([1,2,4].map(|c|json!({"offered_sessions":c,"output_tok_s":20.0, + "cohort":{"selected_cohort_sha256":COHORT_SHA},"phase_outcome":{"errors":0,"cancelled":0}, + "completed_work":{"requests":69,"output_tokens":18713,"source_turn_output_sha256":"a".repeat(64)}})))})).collect() +} +#[test] +fn complete_balanced_work_rejects_partial_reordered_cancelled_or_changed_cells() { + let complete = arms(); + final_sweep::validate_work(&complete).unwrap(); + assert!(final_sweep::validate_work(&complete[..5]).is_err()); + for (pointer, value) in [ + ("/engine", json!("skippy")), + ("/cells/0/offered_sessions", json!(4)), + ("/cells/0/completed_work/output_tokens", json!(18712)), + ("/cells/0/cohort/selected_cohort_sha256", json!("changed")), + ( + "/cells/0/completed_work/source_turn_output_sha256", + json!("b".repeat(64)), + ), + ("/cells/0/phase_outcome/cancelled", json!(1)), + ("/cells/0/output_tok_s", json!(-1)), + ] { + let mut changed = complete.clone(); + *changed[0].pointer_mut(pointer).unwrap() = value; + assert!(final_sweep::validate_work(&changed).is_err(), "{pointer}"); + } +} +fn tools() -> Tools { + serde_json::from_str(include_str!( + "../../../../../skippy/evals/agentx/tools.example.json" + )) + .unwrap() +} +#[test] +fn product_auto_capacity_is_preserved_and_diagnostic_override_is_verified() { + let mut tools = tools(); + let mut args = vec!["serve".into(), "--n-gpu-layers".into(), "99".into()]; + prepared_launch::arguments(&mut args, "skippy", &tools); + assert!(!args.iter().any(|v| v == "--generation-concurrency")); + let config = json!({"stage":{"lane_count":4,"ctx_size":131072,"n_batch":2048,"n_ubatch":512, + "cache_type_k":"f16","cache_type_v":"f16","flash_attn_type":"enabled","kv_cache":{"l2_max_bytes":8589934592u64}}, + "frontend":{"prefill_chunk_size":64,"prefill_chunk_policy":"fixed","generation_concurrency":4}, + "options":{"kv-cache-disk":"off"},"constraints":{"unified_kv":"required"},"execution":{"threads":20,"threads_batch":20}}); + prepared_launch::validate_config(&config, &tools).unwrap(); + tools.diagnostic_generation_lanes = Some(1); + assert!(prepared_launch::validate_config(&config, &tools).is_err()); + tools.diagnostic_generation_lanes = None; + let mut wrong = config; + wrong["stage"]["kv_cache"]["l2_max_bytes"] = json!(1073741824); + assert!(prepared_launch::validate_config(&wrong, &tools).is_err()); +} +#[test] +fn prepared_tree_identity_detects_mutation_and_refuses_directory_links() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("code"), b"first").unwrap(); + let tree = Tree { + path: dir.path().into(), + sha256: crate::product::digest::tree_sha256(dir.path()) + .map_err(|e| e.error) + .unwrap(), + }; + tree.verify().unwrap(); + std::fs::write(dir.path().join("code"), b"changed").unwrap(); + assert!(tree.verify().is_err()); + #[cfg(unix)] + { + let target = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(target.path(), dir.path().join("editable")).unwrap(); + assert!(tree.verify().is_err()); + } +} + +#[test] +fn manifest_cannot_pair_wrong_source_backend_or_upstream_with_pinned_tools() { + let tools = tools(); + let manifest = json!({"runtime":{"backend":{"kind":"cuda"},"skippy_abi":"0.1.76"}, + "build":{"llama_patched_sha":tools.native_source_commit,"llama_patch_digest":tools.native_patch_digest,"llama_upstream_sha":tools.standard_upstream}}); + tools.validate_manifest(&manifest).unwrap(); + for pointer in [ + "/build/llama_patched_sha", + "/build/llama_patch_digest", + "/build/llama_upstream_sha", + "/runtime/backend/kind", + "/runtime/skippy_abi", + ] { + let mut wrong = manifest.clone(); + *wrong.pointer_mut(pointer).unwrap() = json!("different"); + assert!(tools.validate_manifest(&wrong).is_err(), "{pointer}"); + } +} + +#[cfg(unix)] +#[test] +fn ordinary_venv_alias_is_pinned_without_permitting_external_editable_packages() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("lib")).unwrap(); + std::fs::create_dir(dir.path().join("other")).unwrap(); + std::fs::write(dir.path().join("lib/package"), b"package").unwrap(); + let alias = dir.path().join("lib64"); + std::os::unix::fs::symlink("lib", &alias).unwrap(); + let mut tree = Tree { + path: dir.path().into(), + sha256: String::new(), + }; + tree.sha256 = tree.observe().unwrap(); + tree.verify().unwrap(); + std::fs::remove_file(&alias).unwrap(); + std::os::unix::fs::symlink("other", &alias).unwrap(); + assert!(tree.verify().is_err()); + std::fs::remove_file(&alias).unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(outside.path(), &alias).unwrap(); + assert!(tree.observe().is_err()); +} diff --git a/tools/xtask/src/automation/agentx/hardware.rs b/tools/xtask/src/automation/agentx/hardware.rs new file mode 100644 index 0000000000..0e89bd5634 --- /dev/null +++ b/tools/xtask/src/automation/agentx/hardware.rs @@ -0,0 +1,205 @@ +//! Record and admit the accelerator used by the native AgentX runner. +use super::{Prepared, command, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; + +pub(super) fn admit_execution() -> DynResult<()> { + validate_execution( + std::env::consts::OS, + std::env::consts::ARCH, + std::path::Path::new("/.dockerenv").exists(), + std::env::var("AGENTX_CONTAINER_IMAGE").ok().as_deref(), + std::env::var("JIANYANG_RUN_ID").ok().as_deref(), + std::env::var("JIANYANG_COMMIT").ok().as_deref(), + ) +} + +fn validate_execution( + os: &str, + arch: &str, + in_container: bool, + image: Option<&str>, + run: Option<&str>, + commit: Option<&str>, +) -> DynResult<()> { + match (os, arch) { + ("linux", "aarch64") + if in_container + && image.is_some_and(|value| { + value.strip_prefix("sha256:").is_some_and(|digest| { + digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + }) => Ok(()), + ("macos", "aarch64") + if run.is_some_and(|value| value.starts_with("run_") && value.len() > 4) + && commit.is_some_and(|value| { + value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) => Ok(()), + _ => Err("AgentX requires the JY GPU container on Spark or a pinned native JY job on Apple Silicon".into()), + } +} + +pub(super) fn capture(input: &Prepared) -> DynResult<()> { + if input + .tools + .as_ref() + .is_some_and(|tools| tools.backend == super::prepared_tools::Backend::Cpu) + { + return write( + &input.output.join("hardware.json"), + &json!({"os":std::env::consts::OS,"arch":std::env::consts::ARCH,"backend":"cpu","scope":"explicit_cpu_diagnostic"}), + ); + } + let os = std::env::consts::OS; + let arch = std::env::consts::ARCH; + let (executable, args) = probe(os, arch)?; + let spec = command::spec(&input.root, executable, &command::strings(args))?; + let log = input.output.join("hardware"); + command::run(&spec, 60, &log)?; + let output = std::fs::read_to_string(log.with_extension("stdout.log"))?; + let backend = validate(os, &output)?; + write( + &input.output.join("hardware.json"), + &json!({"os":os,"arch":arch,"backend":backend}), + ) +} + +fn probe(os: &str, arch: &str) -> DynResult<(&'static str, &'static [&'static str])> { + match (os, arch) { + ("linux", "aarch64") => Ok(( + "nvidia-smi", + &[ + "--query-gpu=name,memory.total,memory.used,memory.free", + "--format=csv,noheader", + ], + )), + ("macos", "aarch64") => Ok(( + "/usr/sbin/system_profiler", + &["SPDisplaysDataType", "-json"], + )), + _ => Err("AgentX requires a Linux aarch64 DGX Spark or an Apple Silicon Mac".into()), + } +} + +fn validate(os: &str, output: &str) -> DynResult<&'static str> { + if os == "linux" && output.contains("GB10") { + return Ok("cuda"); + } + if os == "macos" { + let report: Value = serde_json::from_str(output)?; + let supported = report["SPDisplaysDataType"] + .as_array() + .is_some_and(|gpus| gpus.iter().any(apple_metal)); + if supported { + return Ok("metal"); + } + } + Err("AgentX requires an NVIDIA GB10 or an Apple GPU with Metal support".into()) +} + +fn apple_metal(gpu: &Value) -> bool { + gpu["spdisplays_vendor"] == "sppci_vendor_Apple" + && ["spdisplays_mtlgpufamilysupport", "spdisplays_metal"] + .iter() + .any(|field| { + gpu[field].as_str().is_some_and(|value| { + value == "spdisplays_supported" + || value + .strip_prefix("spdisplays_metal") + .and_then(|version| version.parse::().ok()) + .is_some_and(|version| version > 0) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn execution_requires_platform_appropriate_provenance() { + let image = format!("sha256:{}", "a".repeat(64)); + let commit = "b".repeat(40); + assert!(validate_execution("linux", "aarch64", true, Some(&image), None, None).is_ok()); + assert!( + validate_execution( + "linux", + "aarch64", + false, + Some(&image), + Some("run_test"), + Some(&commit) + ) + .is_err() + ); + assert!( + validate_execution("linux", "aarch64", true, Some("sha256:invalid"), None, None) + .is_err() + ); + assert!( + validate_execution( + "macos", + "aarch64", + false, + None, + Some("run_test"), + Some(&commit) + ) + .is_ok() + ); + for (run, revision) in [ + (None, Some(commit.as_str())), + (Some("run_test"), None), + (Some("run_"), Some(commit.as_str())), + (Some("run_test"), Some("main")), + ] { + assert!(validate_execution("macos", "aarch64", false, None, run, revision).is_err()); + } + assert!( + validate_execution( + "windows", + "aarch64", + true, + Some(&image), + Some("run_test"), + Some(&commit) + ) + .is_err() + ); + } + + #[test] + fn admits_recorded_apple_metal_and_spark_reports() { + for field in ["spdisplays_mtlgpufamilysupport", "spdisplays_metal"] { + let report = json!({"SPDisplaysDataType":[{ + "spdisplays_vendor":"sppci_vendor_Apple",field:"spdisplays_metal4"}]}); + assert_eq!(validate("macos", &report.to_string()).unwrap(), "metal"); + } + assert_eq!(validate("linux", "NVIDIA GB10, [N/A]").unwrap(), "cuda"); + assert!(probe("macos", "aarch64").is_ok()); + assert!(probe("linux", "aarch64").is_ok()); + } + + #[test] + fn rejects_unsupported_devices_and_missing_accelerator_evidence() { + for (os, report) in [ + ("macos", "{}"), + ( + "macos", + r#"{"SPDisplaysDataType":[{"spdisplays_vendor":"sppci_vendor_Apple"}]}"#, + ), + ("linux", "NVIDIA A100"), + ( + "macos", + r#"{"SPDisplaysDataType":[{"spdisplays_vendor":"sppci_vendor_Apple","spdisplays_metal":"spdisplays_metal_unsupported"}]}"#, + ), + ( + "macos", + r#"{"SPDisplaysDataType":[{"spdisplays_vendor":"Intel","spdisplays_metal":"spdisplays_metal4"}]}"#, + ), + ] { + assert!(validate(os, report).is_err()); + } + assert!(probe("linux", "x86_64").is_err()); + assert!(probe("windows", "aarch64").is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/inputs.rs b/tools/xtask/src/automation/agentx/inputs.rs new file mode 100644 index 0000000000..c7efd1a7a7 --- /dev/null +++ b/tools/xtask/src/automation/agentx/inputs.rs @@ -0,0 +1,255 @@ +use super::{Model, Prepared, Profile, command, write}; +use crate::command::DynResult; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +pub(super) const DATA_REPO: &str = "semianalysisai/cc-traces-weka-062126-256k"; +pub(super) const DATA_REVISION: &str = "8fecd2fc56694469f758f0afbbb6335ad3043740"; +pub(super) const DATA_SHA: &str = + "e39cd2ff3eba21d4a3664be51da743ac3d2149a1933898cafc7bfeac8147eeef"; + +pub(super) fn digest(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(bytes)) +} + +pub(super) fn prepare( + root: PathBuf, + output: PathBuf, + key: &str, + profile: Profile, +) -> DynResult { + let model = select_model(&root, key)?; + let mut weights = None; + for (index, file) in model.files.iter().enumerate() { + let path = download( + &root, + &model.repo, + &model.revision, + &file.name, + false, + &output, + &format!("download-weight-{index}"), + )?; + // Preparation verifies each pin once before any serving cell starts. + verify(&path, &file.sha256)?; + weights.get_or_insert(path); + } + download( + &root, + &model.tokenizer, + &model.tokenizer_revision, + "", + false, + &output, + "download-tokenizer", + )?; + let dataset = download( + &root, + DATA_REPO, + DATA_REVISION, + "traces.jsonl", + true, + &output, + "download-dataset", + )?; + verify(&dataset, DATA_SHA)?; + let traces = output.join("traces"); + materialize(&dataset, &traces, profile)?; + let prepared = Prepared { + tools: None, + root, + output, + weights: weights.ok_or("empty model files")?, + dataset: traces, + model, + profile, + }; + write(&prepared.output.join("inputs.json"), &prepared)?; + Ok(prepared) +} + +pub(super) fn select_model(root: &Path, key: &str) -> DynResult { + let models: Vec = serde_json::from_slice(&std::fs::read( + root.join("skippy/evals/kv-validation/models.json"), + )?)?; + models + .into_iter() + .find(|model| model.key == key || model.registry_ref() == key) + .ok_or_else(|| "unknown AgentX model".into()) +} +fn download( + root: &Path, + repo: &str, + revision: &str, + file: &str, + dataset: bool, + output: &Path, + log_name: &str, +) -> DynResult { + let hf = root.join("skippy/evals/agentx/.venv/bin/hf"); + // Standard HF cache resolution reuses the host's blobs/snapshots and writes + // only missing pins into that same mounted HF_HOME. Never use --local-dir. + let mut args = command::strings(&["download", repo, "--revision", revision, "--quiet"]); + if dataset { + args.extend(command::strings(&["--repo-type", "dataset"])); + } + if !file.is_empty() { + args.push(file.into()); + } else { + args.extend(command::strings(&[ + "--include", + "tokenizer*", + "--include", + "vocab.json", + "--include", + "merges.txt", + "--include", + "config.json", + "--include", + "chat_template*", + ])); + } + let log = output.join(log_name); + let mut spec = command::spec(root, hf.to_str().ok_or("hf path")?, &args)?; + spec.environment.insert( + "HF_HUB_OFFLINE".into(), + crate::process::Value::Public("1".into()), + ); + command::run(&spec, 60, &log)?; + cached_path(&std::fs::read_to_string(log.with_extension("stdout.log"))?) +} + +fn cached_path(stdout: &str) -> DynResult { + let text = stdout.trim(); + let path = PathBuf::from(text); + if text.contains(['\n', '\r']) || !path.is_absolute() || !path.exists() { + return Err("HF download did not return one existing absolute cache path".into()); + } + // Retain the snapshot path rather than canonicalizing to blobs: split GGUF + // loaders and shard verification resolve sibling files in the snapshot. + Ok(path) +} +pub(super) fn verify(path: &Path, expected: &str) -> DynResult<()> { + let actual = crate::product::digest::file_sha256(path).map_err(|failure| failure.error)?; + if actual != expected { + return Err(format!("SHA-256 mismatch for {}", path.display()).into()); + } + Ok(()) +} +fn materialize(source: &Path, destination: &Path, profile: Profile) -> DynResult<()> { + std::fs::create_dir(destination)?; + if profile == Profile::Comparison { + return super::comparison_cohort::materialize(source, destination); + } + if profile == Profile::Contention { + return super::contention_cohort::materialize(source, destination); + } + let limit = if profile == Profile::Smoke { 128 } else { 393 }; + let mut ids = Vec::new(); + let mut trace_context = Vec::new(); + for (index, line) in BufReader::new(std::fs::File::open(source)?) + .lines() + .take(limit) + .enumerate() + { + let line = line?; + let trace: serde_json::Value = serde_json::from_str(&line)?; + ids.push(trace["id"].as_str().ok_or("trace ID missing")?.to_owned()); + trace_context.push(super::trace_context::describe(&trace, line.as_bytes())?); + std::fs::write(destination.join(format!("{index:04}.json")), line)?; + } + if ids.len() != limit { + return Err("AgentX corpus has fewer traces than requested".into()); + } + write( + &destination + .parent() + .ok_or("trace parent")? + .join("cohort.json"), + &serde_json::json!({"dataset_repo":DATA_REPO,"dataset_revision":DATA_REVISION,"dataset_sha256":DATA_SHA,"trace_ids":ids,"trace_context":trace_context}), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn smoke_preserves_complete_rows_and_selects_exact_prefix() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("corpus.jsonl"); + let rows: Vec<_> = (0..129).map(|index| format!(r#"{{"id":"trace-{index}","requests":[{{"type":"subagent","id":"child","requests":[{{"type":"s","in":120000,"out":20000}}]}},{{"type":"n","in":10,"out":100000}}]}}"#)).collect(); + std::fs::write(&source, rows.join("\n")).unwrap(); + let target = temp.path().join("selected"); + materialize(&source, &target, Profile::Smoke).unwrap(); + assert_eq!(std::fs::read_dir(&target).unwrap().count(), 128); + for (index, row) in rows.iter().take(128).enumerate() { + assert_eq!( + std::fs::read_to_string(target.join(format!("{index:04}.json"))).unwrap(), + *row + ); + } + let cohort: serde_json::Value = + serde_json::from_slice(&std::fs::read(temp.path().join("cohort.json")).unwrap()) + .unwrap(); + assert_eq!(cohort["trace_ids"].as_array().unwrap().len(), 128); + assert_eq!(cohort["trace_context"][0]["status"], "unsupported_context"); + } + #[test] + fn corrupted_download_fails_before_use() { + let temp = tempfile::NamedTempFile::new().unwrap(); + assert!(verify(temp.path(), DATA_SHA).is_err()); + } + #[cfg(unix)] + #[test] + fn consecutive_input_commands_retain_independent_outputs() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let bin = root.path().join("skippy/evals/agentx/.venv/bin"); + std::fs::create_dir_all(&bin).unwrap(); + let fixture = root.path().join("cached.gguf"); + std::fs::write(&fixture, b"cached weights").unwrap(); + let hf = bin.join("hf"); + std::fs::write( + &hf, + format!("#!/bin/sh\nprintf '%s\\n' '{}'\n", fixture.display()), + ) + .unwrap(); + std::fs::set_permissions(&hf, std::fs::Permissions::from_mode(0o755)).unwrap(); + for name in [ + "download-weight-0", + "download-tokenizer", + "download-dataset", + ] { + assert_eq!( + download( + root.path(), + "org/model", + "pin", + "file", + false, + root.path(), + name + ) + .unwrap(), + fixture + ); + assert!(root.path().join(format!("{name}.stdout.log")).is_file()); + } + } + #[cfg(unix)] + #[test] + fn hf_cache_resolution_preserves_snapshot_symlinks_and_rejects_ambiguous_output() { + let cache = tempfile::tempdir().unwrap(); + let blob = cache.path().join("blob"); + std::fs::write(&blob, b"weights").unwrap(); + let snapshot = cache.path().join("snapshot.gguf"); + std::os::unix::fs::symlink(&blob, &snapshot).unwrap(); + assert_eq!( + cached_path(&format!("{}\n", snapshot.display())).unwrap(), + snapshot + ); + assert!(cached_path(&format!("{}\n{}", blob.display(), snapshot.display())).is_err()); + assert!(cached_path("relative/model.gguf").is_err()); + assert!(cached_path(cache.path().join("missing").to_str().unwrap()).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/lifecycle.rs b/tools/xtask/src/automation/agentx/lifecycle.rs new file mode 100644 index 0000000000..09716c2ca9 --- /dev/null +++ b/tools/xtask/src/automation/agentx/lifecycle.rs @@ -0,0 +1,865 @@ +use super::{ + Prepared, Profile, cache_decisions::CacheDecisions, command, inputs, native_kv_span, + scheduler_profile::SchedulerProfile, trace_context, write, +}; +use crate::{ + command::DynResult, + process::{ + self, + retained::{Action, Context, Coordinator, ExpectedExit, Launch, MemberId, MemberState}, + }, +}; +use serde_json::json; +use std::{path::PathBuf, time::Duration}; + +pub(super) const STARTUP_TIMEOUT_SECS: u64 = 900; +const LLAMA_CACHE_RAM_MIB_ENV: &str = "AGENTX_LLAMA_CACHE_RAM_MIB"; +const LLAMA_KV_UNIFIED_ENV: &str = "AGENTX_LLAMA_KV_UNIFIED"; +const SKIPPY_KV_UNIFIED_ENV: &str = "AGENTX_SKIPPY_KV_UNIFIED"; +const SKIPPY_MICROBATCH_TOKENS_ENV: &str = "AGENTX_SKIPPY_MICROBATCH_TOKENS"; +const SKIPPY_GENERATION_CONCURRENCY_ENV: &str = "AGENTX_SKIPPY_GENERATION_CONCURRENCY"; +const BASELINE_MICROBATCH_TOKENS: usize = 512; +const BATCH_TOKENS: usize = 2_048; + +fn llama_comparison_context(concurrency: u32) -> DynResult { + trace_context::LIMIT + .checked_mul(u64::from(concurrency)) + .and_then(|tokens| u32::try_from(tokens).ok()) + .ok_or_else(|| "llama comparison context exceeds supported size".into()) +} + +fn parse_llama_cache_ram_mib(value: &str) -> DynResult { + match value.parse::() { + Ok(mib) if mib > 0 => Ok(mib), + _ => Err(format!("{LLAMA_CACHE_RAM_MIB_ENV} must be a positive MiB count").into()), + } +} + +fn llama_cache_ram_mib() -> DynResult> { + match std::env::var(LLAMA_CACHE_RAM_MIB_ENV) { + Ok(value) => parse_llama_cache_ram_mib(&value).map(Some), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(error) => Err(format!("{LLAMA_CACHE_RAM_MIB_ENV}: {error}").into()), + } +} + +fn llama_kv_layout_arguments( + value: Option<&str>, + matched_slot_context: bool, +) -> DynResult> { + match value { + None => Ok(Vec::new()), + Some("1" | "true") => { + let mut arguments = vec!["--kv-unified".into()]; + if matched_slot_context { + arguments.extend([ + "--kv-unified-per-slot".into(), + trace_context::LIMIT.to_string(), + ]); + } + Ok(arguments) + } + Some("0" | "false") => Ok(vec!["--no-kv-unified".into()]), + Some(_) => Err(format!("{LLAMA_KV_UNIFIED_ENV} must be 0, 1, false, or true").into()), + } +} + +fn llama_kv_layout_override(matched_slot_context: bool) -> DynResult> { + match std::env::var(LLAMA_KV_UNIFIED_ENV) { + Ok(value) => llama_kv_layout_arguments(Some(&value), matched_slot_context), + Err(std::env::VarError::NotPresent) => { + llama_kv_layout_arguments(None, matched_slot_context) + } + Err(error) => Err(format!("{LLAMA_KV_UNIFIED_ENV}: {error}").into()), + } +} + +fn skippy_kv_layout_arguments(value: Option<&str>) -> DynResult> { + match value { + None => Ok(Vec::new()), + Some("1" | "true") => Ok(vec!["--kv-cache-unified=true".into()]), + Some("0" | "false") => Ok(vec!["--kv-cache-unified=false".into()]), + Some(_) => Err(format!("{SKIPPY_KV_UNIFIED_ENV} must be 0, 1, false, or true").into()), + } +} + +fn skippy_kv_layout_override() -> DynResult> { + match std::env::var(SKIPPY_KV_UNIFIED_ENV) { + Ok(value) => skippy_kv_layout_arguments(Some(&value)), + Err(std::env::VarError::NotPresent) => skippy_kv_layout_arguments(None), + Err(error) => Err(format!("{SKIPPY_KV_UNIFIED_ENV}: {error}").into()), + } +} + +fn llama_comparison_arguments( + concurrency: u32, + cache_ram_mib: Option, +) -> DynResult> { + let mut args = vec![ + "--ctx-size".into(), + llama_comparison_context(concurrency)?.to_string(), + ]; + if let Some(mib) = cache_ram_mib { + args.extend(["--cache-ram".into(), mib.to_string()]); + } + Ok(args) +} + +fn positive_override(name: &str, value: &str) -> DynResult { + match value.parse::() { + Ok(count) if count > 0 => Ok(count), + _ => Err(format!("{name} must be a positive integer").into()), + } +} + +fn positive_env_override(name: &str) -> DynResult> { + match std::env::var(name) { + Ok(value) => positive_override(name, &value).map(Some), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(error) => Err(format!("{name}: {error}").into()), + } +} + +fn parse_microbatch_tokens(value: &str) -> DynResult { + let tokens = positive_override(SKIPPY_MICROBATCH_TOKENS_ENV, value)?; + if tokens > BATCH_TOKENS { + return Err( + format!("{SKIPPY_MICROBATCH_TOKENS_ENV} must not exceed {BATCH_TOKENS}").into(), + ); + } + Ok(tokens) +} + +fn skippy_microbatch_tokens() -> DynResult { + match std::env::var(SKIPPY_MICROBATCH_TOKENS_ENV) { + Ok(value) => parse_microbatch_tokens(&value), + Err(std::env::VarError::NotPresent) => Ok(BASELINE_MICROBATCH_TOKENS), + Err(error) => Err(format!("{SKIPPY_MICROBATCH_TOKENS_ENV}: {error}").into()), + } +} + +fn skippy_diagnostic_arguments(generation_concurrency: Option) -> Vec { + let mut arguments = Vec::new(); + if let Some(permits) = generation_concurrency { + arguments.extend(["--generation-concurrency".into(), permits.to_string()]); + } + arguments +} + +fn skippy_overrides() -> DynResult> { + let mut arguments = + skippy_diagnostic_arguments(positive_env_override(SKIPPY_GENERATION_CONCURRENCY_ENV)?); + arguments.extend(skippy_kv_layout_override()?); + Ok(arguments) +} + +fn launch_microbatch_tokens(arguments: &[String], engine: &str) -> DynResult { + let flag = if engine == "skippy" { + "--microbatch-size" + } else { + "--ubatch-size" + }; + let pair = arguments + .windows(2) + .find(|pair| pair[0] == flag) + .ok_or("missing server microbatch argument")?; + pair[1] + .parse::() + .map_err(|error| format!("invalid {flag} argument: {error}").into()) +} + +fn agentx_limits(seconds: u64) -> process::Limits { + let mut limits = command::limits(seconds); + // A model with a large KV allocation can need more than the generic 15 s + // grace period to unload after the worker has completed its trace. + limits.graceful_shutdown = Duration::from_secs(90); + limits +} + +fn server( + input: &Prepared, + engine: &str, + port: u16, + concurrency: u32, +) -> DynResult { + // Skippy plans its own capacity. Preserve llama's explicit parallel setting: + // its auto-parallel mode also changes the baseline's unified-KV policy. + // For the fixed-work comparison, match the per-slot context ceiling to the + // common trace budget; llama otherwise allocates the model's full native + // context for every slot and pays for capacity the workload cannot use. + let weights = input.weights.to_str().ok_or("weight path")?; + let microbatch_tokens = if input.tools.is_some() { + BASELINE_MICROBATCH_TOKENS + } else if engine == "skippy" { + skippy_microbatch_tokens()? + } else { + BASELINE_MICROBATCH_TOKENS + }; + let (mut binary, mut args) = if engine == "llama" { + ( + input.root.join(".deps/agentx-llama-build/bin/llama-server"), + command::strings(&[ + "--model", + weights, + "--alias", + &input.model.key, + "--host", + "127.0.0.1", + "--port", + &port.to_string(), + "--parallel", + &concurrency.to_string(), + "--batch-size", + "2048", + "--ubatch-size", + "512", + "--n-gpu-layers", + "99", + "--cache-type-k", + "f16", + "--cache-type-v", + "f16", + "--flash-attn", + "on", + "--jinja", + "--chat-template-kwargs", + r#"{"enable_thinking":false}"#, + ]), + ) + } else { + ( + input.root.join("target/release/skippy"), + command::strings(&[ + "serve", + "--model-path", + weights, + "--model-id", + &input.model.key, + "--bind-addr", + &format!("127.0.0.1:{port}"), + "--startup-timeout-secs", + &STARTUP_TIMEOUT_SECS.to_string(), + "--batch-size", + "2048", + "--microbatch-size", + µbatch_tokens.to_string(), + "--generation-queue-capacity", + "256", + "--generation-admission-timeout-secs", + "1800", + "--n-gpu-layers", + "-1", + "--kv-cache-type-k", + "f16", + "--kv-cache-type-v", + "f16", + "--flash-attention", + "enabled", + "--speculative-strategy", + "disabled", + "--prefix-cache", + "on", + "--prefix-cache-ram", + "8GiB", + "--kv-cache-disk", + "off", + "--chat-template-kwargs", + r#"{"enable_thinking":false}"#, + ]), + ) + }; + if engine == "llama" && matches!(input.profile, Profile::Comparison | Profile::Contention) { + args.extend(llama_comparison_arguments( + concurrency, + if input.tools.is_some() { + Some(8192) + } else { + llama_cache_ram_mib()? + }, + )?); + } else if engine == "skippy" { + if let Some(tools) = input.tools.as_ref() { + args.extend(skippy_diagnostic_arguments( + tools.diagnostic_generation_lanes.map(|v| v as usize), + )); + } else { + args.extend(skippy_overrides()?); + } + } + if engine == "llama" { + args.extend(if input.tools.is_some() { + vec!["--no-kv-unified".into()] + } else { + llama_kv_layout_override(matches!( + input.profile, + Profile::Comparison | Profile::Contention + ))? + }); + } + if let Some(tools) = input.tools.as_ref() { + binary = if engine == "llama" { + tools.llama.path.clone() + } else { + tools.skippy.path.clone() + }; + super::prepared_launch::arguments(&mut args, engine, tools); + } + let mut spec = command::spec(&input.root, binary.to_str().ok_or("server path")?, &args)?; + if engine == "skippy" { + spec.arguments.extend([ + process::Value::Public("--runtime-bundle".into()), + process::Value::Public( + input + .tools + .as_ref() + .map_or_else( + || input.root.join("dist/native-runtimes"), + |tools| tools.runtime.path.clone(), + ) + .into_os_string(), + ), + ]); + if input.tools.is_none() + && (input.profile == Profile::Contention + || std::env::var("AGENTX_SKIPPY_DEBUG_TELEMETRY").as_deref() == Ok("1")) + { + spec.arguments.extend([ + process::Value::Public("--telemetry-level".into()), + process::Value::Public("debug".into()), + ]); + spec.environment.insert( + "SKIPPY_TELEMETRY_STDERR".into(), + process::Value::Public("1".into()), + ); + } + if input.tools.is_none() + && std::env::var("SKIPPY_EXACT_STATE_DIAGNOSTICS").as_deref() == Ok("1") + { + enable_exact_state_diagnostics(&mut spec); + } + if input.tools.is_none() + && std::env::var("AGENTX_SKIPPY_KV_SPAN_DEBUG").as_deref() == Ok("1") + { + enable_native_kv_span_debug(&mut spec); + } + if input.tools.is_none() + && std::env::var("AGENTX_SKIPPY_KV_EXTENT_PROFILE").as_deref() == Ok("1") + { + spec.environment.insert( + "LLAMA_KV_EXTENT_PROFILE".into(), + process::Value::Public("1".into()), + ); + } + } + spec.environment.insert( + "MESH_AGENT_SESSION_HEADER".into(), + process::Value::Public("X-Session-ID".into()), + ); + spec.environment.insert( + "MESH_OPENAI_BACKEND_TIMEOUT_SECS".into(), + process::Value::Public("1800".into()), + ); + Ok(spec) +} + +fn enable_exact_state_diagnostics(spec: &mut process::ProcessSpec) { + spec.environment.insert( + "SKIPPY_EXACT_STATE_DIAGNOSTICS".into(), + process::Value::Public("1".into()), + ); +} + +fn enable_native_kv_span_debug(spec: &mut process::ProcessSpec) { + spec.arguments + .push(process::Value::Public("--debug".into())); + spec.environment.insert( + "LLAMA_KV_CACHE_DEBUG".into(), + process::Value::Public("1".into()), + ); + spec.environment.insert( + "GGML_LLAMA_LOG_LEVEL".into(), + process::Value::Public("4".into()), + ); +} +pub(super) fn execute(input: &Prepared, engine: &str, concurrency: u32) -> DynResult<()> { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + write(&input.output.join("worker.json"), input)?; + let server = server(input, engine, port, concurrency)?; + if engine == "skippy" && input.tools.is_some() { + super::prepared_launch::effective_config(input, &server)?; + } + write( + &input.output.join("launch.json"), + &launch_identity(input, &server, engine, concurrency)?, + )?; + let worker = command::spec( + &input.root, + std::env::current_exe()?.to_str().ok_or("xtask path")?, + &command::strings(&[ + "automation", + "agentx", + "worker", + "--input", + input + .output + .join("worker.json") + .to_str() + .ok_or("worker path")?, + "--port", + &port.to_string(), + "--concurrency", + &concurrency.to_string(), + ]), + )?; + let seconds = if let Some(tools) = input.tools.as_ref() { + tools.cell_seconds + } else if matches!(input.profile, Profile::Smoke | Profile::Contention) { + 4800 + } else { + 10200 + }; + let memory = super::memory::Monitor::start(&input.output)?; + let debug_scheduler = input.tools.is_none() + && (input.profile == Profile::Contention + || std::env::var("AGENTX_SKIPPY_DEBUG_TELEMETRY").as_deref() == Ok("1")); + let mut owner = Owner { + memory_pid: std::sync::Arc::clone(&memory.pid), + cache_decisions: (engine == "skippy" && debug_scheduler).then(CacheDecisions::new), + scheduler_profile: (engine == "skippy" && debug_scheduler).then(SchedulerProfile::new), + native_kv_span: (input.tools.is_none() + && engine == "skippy" + && std::env::var("AGENTX_SKIPPY_KV_SPAN_DEBUG").as_deref() == Ok("1")) + .then(native_kv_span::NativeKvSpan::default), + native_kv_span_output: input.output.clone(), + server: Some(launch(input, server, MemberId::Seed, "server", seconds)), + worker: Some(launch( + input, + worker, + MemberId::WorkerOne, + "worker", + seconds, + )), + stop: false, + policy: ExpectedExit::new(&[0], Duration::from_secs(seconds))?, + }; + drop(listener); + let report = super::super::retained_session::run(&mut owner, &agentx_limits(seconds)); + if let Some(decisions) = owner.cache_decisions.as_ref() { + write(&input.output.join("cache-decisions.json"), decisions)?; + } + if let Some(profile) = owner.scheduler_profile.as_ref() { + write(&input.output.join("scheduler-profile.json"), profile)?; + } + let report = report?; + write( + &input.output.join("memory-summary.json"), + &serde_json::to_value(memory.finish()?)?, + )?; + let clean = report.recovery_success() + && report.members.len() == 2 + && report.members.iter().all(|member| { + member.process.cleanup.complete + && !member.process.cleanup.forced + && member.process.failure.is_none() + }) + && report.members.iter().any(|member| { + member.member == MemberId::WorkerOne + && member + .process + .status + .as_ref() + .and_then(std::process::ExitStatus::code) + == Some(0) + }); + write( + &input.output.join("lifecycle.json"), + &json!({ + "clean":clean, + "cleanup_complete":report.members.iter().all(|m| m.process.cleanup.complete), + "outcome":format!("{:?}",report.outcome), + "failure":report.failure.as_ref().map(ToString::to_string), + "members":report.members.iter().map(|member| json!({ + "member":format!("{:?}",member.member), + "disposition":member.disposition.label(), + "status":member.process.status.and_then(|status| status.code()), + "cleanup_complete":member.process.cleanup.complete, + "cleanup_forced":member.process.cleanup.forced, + "graceful_signal_failed":member.process.cleanup.graceful_signal_failed, + "cleanup_failure":member.process.cleanup.failure.as_ref().map(ToString::to_string), + "process_failure":member.process.failure.as_ref().map(ToString::to_string), + })).collect::>(), + }), + )?; + if !clean { + return Err(format!("{engine} c{concurrency} failed; partial artifacts retained").into()); + } + Ok(()) +} +fn launch_identity( + input: &Prepared, + server: &process::ProcessSpec, + engine: &str, + concurrency: u32, +) -> DynResult { + let matched_llama_context = if engine == "llama" + && matches!(input.profile, Profile::Comparison | Profile::Contention) + { + Some(llama_comparison_context(concurrency)?) + } else { + None + }; + let runtime = if let Some(tools) = input.tools.as_ref() { + if engine == "skippy" { + tools.runtime.path.clone() + } else { + tools.standard_runtime.path.clone() + } + } else if engine == "skippy" { + input.root.join("dist/native-runtimes") + } else { + input.root.join(".deps/agentx-llama-build/bin") + }; + let arguments: Vec<_> = server + .arguments + .iter() + .map(|value| match value { + process::Value::Public(value) => value.to_string_lossy().into_owned(), + process::Value::Secret(_) => "".into(), + }) + .collect(); + let microbatch_tokens = launch_microbatch_tokens(&arguments, engine)?; + let llama_unified_kv = engine == "llama" && arguments.iter().any(|arg| arg == "--kv-unified"); + let skippy_kv_unified = if engine == "skippy" { + arguments.iter().find_map(|arg| match arg.as_str() { + "--kv-cache-unified=true" => Some(true), + "--kv-cache-unified=false" => Some(false), + _ => None, + }) + } else { + None + }; + let requested_generation_concurrency = arguments + .windows(2) + .find(|pair| pair[0] == "--generation-concurrency") + .and_then(|pair| pair[1].parse::().ok()); + Ok(json!({ + "engine":engine,"command":arguments, + "container_image":std::env::var("AGENTX_CONTAINER_IMAGE").ok(), + "execution_mode":if cfg!(target_os = "macos") { "native_metal" } else { "gpu_container" }, + "stack_commit":input.tools.as_ref().map(|tools|tools.product_source_commit.clone()).or_else(||std::env::var("JIANYANG_COMMIT").ok()), + "binary_sha256":crate::product::digest::file_sha256(&server.executable).map_err(|error|error.error)?, + "runtime_tree_sha256":crate::product::digest::tree_sha256(&runtime).map_err(|error|error.error)?, + "harness_lock_sha256":crate::product::digest::file_sha256(&input.root.join("skippy/evals/agentx/uv.lock")).map_err(|error|error.error)?, + "capacity_policy":if llama_unified_kv { "diagnostic_unified_kv_common_128k_trace_limit" } else if skippy_kv_unified == Some(false) { "auto_capacity_explicit_separate_kv" } else { super::capacity::policy(engine, input.profile) }, + "context_tokens":matched_llama_context.map(|_| trace_context::LIMIT), + "total_context_tokens":matched_llama_context, + "kv_unified_per_slot_context_tokens":if llama_unified_kv && matched_llama_context.is_some() { Some(trace_context::LIMIT) } else { None }, + "llama_kv_unified":if engine == "llama" { Some(llama_unified_kv) } else { None }, + "skippy_kv_unified":skippy_kv_unified, + "generation_slots":null,"offered_sessions":concurrency, + "requested_generation_concurrency":requested_generation_concurrency, + "generation_concurrency_policy":if engine == "llama" { "explicit_parallel" } + else if requested_generation_concurrency.is_some() { "explicit_override" } + else { "automatic" }, + "native_kv_span_debug":input.tools.is_none() && engine == "skippy" && std::env::var("AGENTX_SKIPPY_KV_SPAN_DEBUG").as_deref() == Ok("1"), + "native_kv_extent_profile":input.tools.is_none() && engine == "skippy" && std::env::var("AGENTX_SKIPPY_KV_EXTENT_PROFILE").as_deref() == Ok("1"), + "batch_tokens":BATCH_TOKENS,"microbatch_tokens":microbatch_tokens, + "speculation":false,"dataset_sha256":inputs::DATA_SHA, + "llama_upstream":std::fs::read_to_string(input.root.join("skippy/llama_cpp/upstream.txt"))?.trim() + })) +} +fn launch( + input: &Prepared, + spec: process::ProcessSpec, + member: MemberId, + label: &str, + seconds: u64, +) -> Launch { + Launch { + member, + spec, + files: process::OutputFiles { + stdout: Some(input.output.join(format!("{label}.stdout.log"))), + stderr: Some(input.output.join(format!("{label}.stderr.log"))), + }, + readiness_deadline: Duration::from_secs(seconds), + } +} +struct Owner { + memory_pid: std::sync::Arc, + cache_decisions: Option, + scheduler_profile: Option, + native_kv_span: Option, + native_kv_span_output: PathBuf, + server: Option, + worker: Option, + stop: bool, + policy: ExpectedExit, +} + +impl Coordinator for Owner { + type Rejection = String; + fn line( + &mut self, + member: MemberId, + line: process::ObservedLine<'_>, + ) -> process::ProbeDecision { + if let Some(profile) = self.scheduler_profile.as_mut() { + profile.observe(member, &line); + } + if let Some(span) = self.native_kv_span.as_mut() { + span.observe(member, &line); + } + if let Some(decisions) = self.cache_decisions.as_mut() { + decisions.observe(member, line); + } + process::ProbeDecision::Pending + } + fn tick(&mut self, context: Context<'_>) -> Action { + if let Some(server) = context + .members + .iter() + .find(|member| member.member == MemberId::Seed) + { + self.memory_pid + .store(server.pid, std::sync::atomic::Ordering::Relaxed); + } + if self.stop { + return Action::Complete; + } + if let Some(server) = self.server.take() { + return Action::Start(server); + } + if context.members.iter().any(|member| { + member.member == MemberId::Seed && matches!(member.state, MemberState::Starting) + }) { + return Action::Admit(MemberId::Seed); + } + if let Some(worker) = self.worker.take() { + return Action::StartExpected { + launch: worker, + policy: self.policy.clone(), + }; + } + if context.members.iter().any(|member| { + member.member == MemberId::WorkerOne + && matches!(member.state, MemberState::ExpectedExit { .. }) + }) { + if let Some(span) = self.native_kv_span.as_ref() + && let Err(error) = span.save(&self.native_kv_span_output) + { + return Action::Reject(format!("capture native KV span: {error}")); + } + self.stop = true; + return Action::Stop(MemberId::Seed); + } + Action::Pending + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn skippy_diagnostic_overrides_are_explicit_and_positive() { + assert!(skippy_diagnostic_arguments(None).is_empty()); + assert_eq!( + skippy_diagnostic_arguments(Some(2)), + ["--generation-concurrency", "2"] + ); + for name in [ + SKIPPY_MICROBATCH_TOKENS_ENV, + SKIPPY_GENERATION_CONCURRENCY_ENV, + ] { + assert_eq!(positive_override(name, "1").unwrap(), 1); + for value in ["", "0", "-1", "oops"] { + assert!(positive_override(name, value).is_err(), "{name}={value}"); + } + } + assert_eq!(parse_microbatch_tokens("256").unwrap(), 256); + assert_eq!(parse_microbatch_tokens("2048").unwrap(), 2048); + assert!(parse_microbatch_tokens("2049").is_err()); + } + #[test] + fn exact_state_diagnostics_reach_the_server_process() { + let mut spec = command::spec(&std::env::temp_dir(), "sh", &[]).unwrap(); + enable_exact_state_diagnostics(&mut spec); + assert!(matches!( + spec.environment + .get(std::ffi::OsStr::new("SKIPPY_EXACT_STATE_DIAGNOSTICS")), + Some(process::Value::Public(value)) if value == "1" + )); + } + + #[test] + fn kv_span_diagnostic_enables_native_cell_span_logging() { + let mut spec = command::spec(&std::env::temp_dir(), "sh", &[]).unwrap(); + enable_native_kv_span_debug(&mut spec); + assert!(spec.arguments.iter().any(|argument| matches!(argument, + process::Value::Public(value) if value == "--debug"))); + for (key, expected) in [("LLAMA_KV_CACHE_DEBUG", "1"), ("GGML_LLAMA_LOG_LEVEL", "4")] { + assert!( + matches!(spec.environment.get(std::ffi::OsStr::new(key)), Some(process::Value::Public(value)) if value == expected) + ); + } + } + #[test] + fn paired_engines_pin_identical_batch_capacity() { + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let input = Prepared { + tools: None, + root: "/repo".into(), + output: "/output".into(), + weights: "/cache/model.gguf".into(), + dataset: "/traces".into(), + model: models[1].clone(), + profile: Profile::Smoke, + }; + for (engine, microbatch) in [("llama", "--ubatch-size"), ("skippy", "--microbatch-size")] { + let spec = server(&input, engine, 8080, 2).unwrap(); + let arguments: Vec<_> = spec + .arguments + .iter() + .map(|value| match value { + process::Value::Public(value) => value.to_string_lossy().into_owned(), + process::Value::Secret(_) => panic!("unexpected secret in server arguments"), + }) + .collect(); + for pair in [["--batch-size", "2048"], [microbatch, "512"]] { + assert!( + arguments.windows(2).any(|args| args == pair), + "{engine}: {pair:?}" + ); + } + assert_eq!(launch_microbatch_tokens(&arguments, engine).unwrap(), 512); + for flag in ["--generation-concurrency", "--ctx-size"] { + assert!(!arguments.iter().any(|arg| arg == flag), "{engine}: {flag}"); + } + if engine == "llama" { + assert!(arguments.windows(2).any(|args| args == ["--parallel", "2"])); + } else { + assert!(!arguments.iter().any(|arg| arg == "--parallel")); + assert!(arguments.windows(2).any(|args| { + args == ["--startup-timeout-secs", &STARTUP_TIMEOUT_SECS.to_string()] + })); + } + } + } + + #[test] + fn diagnostic_profiles_match_llama_slot_context_to_common_trace_budget() { + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let mut input = Prepared { + tools: None, + root: "/repo".into(), + output: "/output".into(), + weights: "/cache/model.gguf".into(), + dataset: "/traces".into(), + model: models[0].clone(), + profile: Profile::Comparison, + }; + for (profile, concurrencies) in [ + (Profile::Comparison, &[1, 2, 4][..]), + (Profile::Contention, &[4, 8, 16][..]), + ] { + input.profile = profile; + for &concurrency in concurrencies { + let llama = server(&input, "llama", 8080, concurrency).unwrap(); + let arguments: Vec<_> = llama + .arguments + .iter() + .map(|value| match value { + process::Value::Public(value) => value.to_string_lossy().into_owned(), + process::Value::Secret(_) => { + panic!("unexpected secret in server arguments") + } + }) + .collect(); + let expected_context = (trace_context::LIMIT * u64::from(concurrency)).to_string(); + assert!( + arguments + .windows(2) + .any(|args| args == ["--ctx-size", &expected_context]) + ); + assert!( + arguments + .windows(2) + .any(|args| args == ["--parallel", &concurrency.to_string()]) + ); + let skippy = server(&input, "skippy", 8080, concurrency).unwrap(); + assert!(!skippy.arguments.iter().any(|value| matches!(value, + process::Value::Public(argument) if argument == "--ctx-size"))); + } + } + } + + #[test] + fn llama_cache_budget_control_is_explicit_and_rejects_invalid_values() { + assert_eq!(parse_llama_cache_ram_mib("65536").unwrap(), 65536); + for value in ["", "0", "-1", "8GiB", "4294967296"] { + assert!(parse_llama_cache_ram_mib(value).is_err(), "{value}"); + } + assert_eq!( + llama_comparison_arguments(2, Some(65536)).unwrap(), + ["--ctx-size", "262144", "--cache-ram", "65536"] + ); + assert_eq!( + llama_comparison_arguments(2, None).unwrap(), + ["--ctx-size", "262144"] + ); + } + + #[test] + fn llama_kv_layout_control_is_explicit_and_rejects_invalid_values() { + assert!(llama_kv_layout_arguments(None, true).unwrap().is_empty()); + for value in ["1", "true"] { + assert_eq!( + llama_kv_layout_arguments(Some(value), true).unwrap(), + ["--kv-unified", "--kv-unified-per-slot", "131072"] + ); + assert_eq!( + llama_kv_layout_arguments(Some(value), false).unwrap(), + ["--kv-unified"] + ); + } + for value in ["0", "false"] { + assert_eq!( + llama_kv_layout_arguments(Some(value), true).unwrap(), + ["--no-kv-unified"] + ); + } + for value in ["", "on", "off", "2"] { + assert!( + llama_kv_layout_arguments(Some(value), true).is_err(), + "{value}" + ); + } + } + + #[test] + fn skippy_kv_layout_control_is_explicit_and_rejects_invalid_values() { + assert!(skippy_kv_layout_arguments(None).unwrap().is_empty()); + for value in ["1", "true"] { + assert_eq!( + skippy_kv_layout_arguments(Some(value)).unwrap(), + ["--kv-cache-unified=true"] + ); + } + for value in ["0", "false"] { + assert_eq!( + skippy_kv_layout_arguments(Some(value)).unwrap(), + ["--kv-cache-unified=false"] + ); + } + for value in ["", "on", "off", "2"] { + assert!(skippy_kv_layout_arguments(Some(value)).is_err(), "{value}"); + } + } +} diff --git a/tools/xtask/src/automation/agentx/memory.rs b/tools/xtask/src/automation/agentx/memory.rs new file mode 100644 index 0000000000..6f289aea27 --- /dev/null +++ b/tools/xtask/src/automation/agentx/memory.rs @@ -0,0 +1,264 @@ +//! Local benchmark memory observations. RSS, cgroup bytes and CUDA's +//! per-process device-memory accounting are not physical GPU residency on +//! unified-memory systems; unavailable counters stay absent. +use crate::command::DynResult; +use serde::Serialize; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{ + Arc, + atomic::{AtomicU32, Ordering}, + mpsc, +}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +#[cfg(target_os = "macos")] +mod macos; + +#[derive(Default, Serialize)] +struct Sample { + elapsed_ms: u128, + process_rss_bytes: Option, + process_rss_high_water_bytes: Option, + process_anonymous_rss_bytes: Option, + process_physical_footprint_bytes: Option, + cuda_process_accounted_memory_bytes: Option, + container_memory_bytes: Option, + host_available_bytes: Option, +} + +#[derive(Default, Serialize)] +pub(super) struct Summary { + samples: usize, + sampled_peak_process_rss_bytes: Option, + sampled_peak_process_physical_footprint_bytes: Option, + process_rss_high_water_bytes: Option, + sampled_peak_cuda_process_accounted_memory_bytes: Option, + sampled_peak_container_memory_bytes: Option, + minimum_host_available_bytes: Option, +} + +pub(super) struct Monitor { + pub(super) pid: Arc, + stop: mpsc::Sender<()>, + worker: Option>>, +} + +impl Monitor { + pub(super) fn start(output: &Path) -> DynResult { + let file = File::create(output.join("memory.jsonl"))?; + let pid = Arc::new(AtomicU32::new(0)); + let worker_pid = Arc::clone(&pid); + let (stop, stopped) = mpsc::channel(); + let worker = thread::Builder::new() + .name("agentx-memory".into()) + .spawn(move || { + sample_loop(file, &worker_pid, &stopped).map_err(|error| error.to_string()) + })?; + Ok(Self { + pid, + stop, + worker: Some(worker), + }) + } + + pub(super) fn finish(mut self) -> DynResult { + let _ = self.stop.send(()); + self.worker + .take() + .ok_or("missing memory worker")? + .join() + .map_err(|_| "memory worker panicked")? + .map_err(Into::into) + } +} + +impl Drop for Monitor { + fn drop(&mut self) { + let _ = self.stop.send(()); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +#[cfg(any(not(target_os = "macos"), test))] +fn kib_field(text: &str, name: &str) -> Option { + let line = text.lines().find_map(|line| line.strip_prefix(name))?; + let mut fields = line.split_whitespace(); + let value = fields.next()?.parse::().ok()?; + (fields.next()? == "kB").then_some(value)?.checked_mul(1024) +} + +fn cgroup_memory_path() -> Option { + // Docker's cgroup namespace normally mounts this container at the root. + let root = PathBuf::from("/sys/fs/cgroup/memory.current"); + if root.is_file() { + return Some(root); + } + let groups = std::fs::read_to_string("/proc/self/cgroup").ok()?; + let relative = groups.lines().find_map(|line| line.strip_prefix("0::"))?; + Some( + Path::new("/sys/fs/cgroup") + .join(relative.trim_start_matches('/')) + .join("memory.current"), + ) +} + +fn read_sample(pid: u32, elapsed_ms: u128, cgroup: Option<&Path>) -> Sample { + #[cfg(target_os = "macos")] + { + let _ = cgroup; + macos::sample(pid, elapsed_ms) + } + #[cfg(not(target_os = "macos"))] + read_proc_sample(pid, elapsed_ms, cgroup) +} + +#[cfg(not(target_os = "macos"))] +fn read_proc_sample(pid: u32, elapsed_ms: u128, cgroup: Option<&Path>) -> Sample { + let status = if pid == 0 { + String::new() + } else { + std::fs::read_to_string(format!("/proc/{pid}/status")).unwrap_or_default() + }; + let host = std::fs::read_to_string("/proc/meminfo").unwrap_or_default(); + Sample { + elapsed_ms, + process_rss_bytes: kib_field(&status, "VmRSS:"), + process_rss_high_water_bytes: kib_field(&status, "VmHWM:"), + process_anonymous_rss_bytes: kib_field(&status, "RssAnon:"), + process_physical_footprint_bytes: None, + cuda_process_accounted_memory_bytes: None, + container_memory_bytes: cgroup + .and_then(|path| std::fs::read_to_string(path).ok()) + .and_then(|value| value.trim().parse().ok()), + host_available_bytes: kib_field(&host, "MemAvailable:"), + } +} + +#[cfg(any(target_os = "linux", test))] +fn parse_cuda_process_memory(output: &str, pid: u32) -> Option { + let mut total = None; + for line in output.lines() { + let Some((listed_pid, mib)) = line.split_once(',') else { + continue; + }; + if listed_pid.trim().parse::().ok() != Some(pid) { + continue; + } + let bytes = mib.trim().parse::().ok()?.checked_mul(1024 * 1024)?; + total = Some(total.unwrap_or(0_u64).checked_add(bytes)?); + } + total +} + +#[cfg(target_os = "linux")] +fn cuda_process_memory(pid: u32) -> Option { + let output = std::process::Command::new("timeout") + .args([ + "-k", + "1s", + "4s", + "nvidia-smi", + "--query-compute-apps=pid,used_memory", + "--format=csv,noheader,nounits", + ]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + parse_cuda_process_memory(std::str::from_utf8(&output.stdout).ok()?, pid) +} + +fn sample_loop(file: File, pid: &AtomicU32, stop: &mpsc::Receiver<()>) -> DynResult { + let mut writer = BufWriter::new(file); + let mut summary = Summary::default(); + let started = Instant::now(); + let cgroup = cgroup_memory_path(); + #[cfg(target_os = "linux")] + let mut next_cuda_probe = Instant::now(); + loop { + let current_pid = pid.load(Ordering::Relaxed); + let sample = read_sample( + current_pid, + started.elapsed().as_millis(), + cgroup.as_deref(), + ); + #[cfg(target_os = "linux")] + let sample = Sample { + cuda_process_accounted_memory_bytes: if current_pid != 0 + && Instant::now() >= next_cuda_probe + { + next_cuda_probe = Instant::now() + Duration::from_secs(30); + cuda_process_memory(current_pid) + } else { + None + }, + ..sample + }; + summary.samples += 1; + summary.sampled_peak_process_rss_bytes = summary + .sampled_peak_process_rss_bytes + .max(sample.process_rss_bytes); + summary.sampled_peak_process_physical_footprint_bytes = summary + .sampled_peak_process_physical_footprint_bytes + .max(sample.process_physical_footprint_bytes); + summary.process_rss_high_water_bytes = summary + .process_rss_high_water_bytes + .max(sample.process_rss_high_water_bytes); + summary.sampled_peak_cuda_process_accounted_memory_bytes = summary + .sampled_peak_cuda_process_accounted_memory_bytes + .max(sample.cuda_process_accounted_memory_bytes); + summary.sampled_peak_container_memory_bytes = summary + .sampled_peak_container_memory_bytes + .max(sample.container_memory_bytes); + if let Some(available) = sample.host_available_bytes { + summary.minimum_host_available_bytes = Some( + summary + .minimum_host_available_bytes + .map_or(available, |previous| previous.min(available)), + ); + } + serde_json::to_writer(&mut writer, &sample)?; + writer.write_all(b"\n")?; + writer.flush()?; + match stop.recv_timeout(Duration::from_secs(1)) { + Err(mpsc::RecvTimeoutError::Timeout) => {} + Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + Ok(summary) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn proc_memory_requires_units_and_never_converts_missing_to_zero() { + let status = "VmRSS:\t123 kB\nVmHWM:\t456 kB\nRssAnon:\t7 kB\n"; + assert_eq!(kib_field(status, "VmRSS:"), Some(123 * 1024)); + assert_eq!(kib_field(status, "VmHWM:"), Some(456 * 1024)); + assert_eq!(kib_field(status, "MemAvailable:"), None); + assert_eq!(kib_field("VmRSS: 12 MB", "VmRSS:"), None); + assert_eq!(kib_field("VmRSS: 18446744073709551615 kB", "VmRSS:"), None); + } + + #[test] + fn cuda_process_memory_matches_container_pid_and_preserves_missing_values() { + let output = "122, 5544\n817739, 5544\n122, 100\n"; + assert_eq!( + parse_cuda_process_memory(output, 122), + Some((5544 + 100) * 1024 * 1024) + ); + assert_eq!(parse_cuda_process_memory(output, 1), None); + assert_eq!(parse_cuda_process_memory("122, N/A\n", 122), None); + assert_eq!( + parse_cuda_process_memory("122, 18446744073709551615\n", 122), + None + ); + } +} diff --git a/tools/xtask/src/automation/agentx/memory/macos.rs b/tools/xtask/src/automation/agentx/memory/macos.rs new file mode 100644 index 0000000000..7b8791fcb5 --- /dev/null +++ b/tools/xtask/src/automation/agentx/memory/macos.rs @@ -0,0 +1,56 @@ +//! Process memory from Darwin's libproc; neither field is GPU residency. +use super::Sample; +use std::mem::MaybeUninit; + +pub(super) fn sample(pid: u32, elapsed_ms: u128) -> Sample { + let usage = usage(pid); + Sample { + elapsed_ms, + process_rss_bytes: usage.as_ref().map(|value| value.ri_resident_size), + process_physical_footprint_bytes: usage.as_ref().map(|value| value.ri_phys_footprint), + // rusage_info_v2 exposes instantaneous values, not an RSS high-water mark. + ..Sample::default() + } +} + +fn usage(pid: u32) -> Option { + let pid = i32::try_from(pid).ok().filter(|pid| *pid > 0)?; + let mut usage = MaybeUninit::::uninit(); + // SAFETY: the buffer has the layout/size selected by RUSAGE_INFO_V2. libproc + // initializes it on success; failures never read the uninitialized buffer. + let status = + unsafe { libc::proc_pid_rusage(pid, libc::RUSAGE_INFO_V2, usage.as_mut_ptr().cast()) }; + if status != 0 { + return None; + } + // SAFETY: the successful call above initialized the complete v2 structure. + Some(unsafe { usage.assume_init() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn observes_live_process_memory_without_claiming_high_water_or_gpu_residency() { + let sample = sample(std::process::id(), 123); + assert!(sample.process_rss_bytes.is_some_and(|bytes| bytes > 0)); + assert!( + sample + .process_physical_footprint_bytes + .is_some_and(|bytes| bytes > 0) + ); + assert_eq!(sample.elapsed_ms, 123); + assert_eq!(sample.process_rss_high_water_bytes, None); + assert_eq!(sample.container_memory_bytes, None); + } + + #[test] + fn unavailable_process_is_missing_not_zero() { + for pid in [0, u32::MAX, i32::MAX as u32] { + let sample = sample(pid, 0); + assert_eq!(sample.process_rss_bytes, None); + assert_eq!(sample.process_physical_footprint_bytes, None); + } + } +} diff --git a/tools/xtask/src/automation/agentx/mlflow_export.rs b/tools/xtask/src/automation/agentx/mlflow_export.rs new file mode 100644 index 0000000000..6b82987899 --- /dev/null +++ b/tools/xtask/src/automation/agentx/mlflow_export.rs @@ -0,0 +1,308 @@ +//! Publication plans for the existing AgentX experiment; never create an experiment. +use super::{final_sweep, prepared_tools::File}; +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{collections::BTreeMap, path::Path}; + +pub(super) const EXPERIMENT: &str = "6"; +pub(super) const EXPERIMENT_NAME: &str = "agentx-skippy-vs-llama"; +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Input { + pub report: File, + pub archive: File, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Plan { + pub schema_version: u32, + pub experiment_id: String, + pub expected_experiment_name: String, + pub campaign_root: CampaignRoot, + pub run_key: String, + pub name: String, + pub tags: BTreeMap, + pub children: Vec, + pub report: File, + pub archive: File, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct CampaignRoot { + pub run_key: String, + pub name: String, + pub tags: BTreeMap, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Child { + pub run_key: String, + pub name: String, + pub tags: BTreeMap, + pub metrics: BTreeMap, +} +pub(super) fn run(input: Input, output: &Path) -> DynResult<()> { + input.report.verify()?; + input.archive.verify()?; + let report: Value = serde_json::from_slice(&crate::automation::receipt_files::bounded( + &input.report.path, + 4 * 1024 * 1024, + )?)?; + let plan = build(&report, input)?; + crate::automation::receipt_files::fresh(output, &serde_json::to_vec_pretty(&plan)?) +} +fn build(report: &Value, input: Input) -> DynResult { + if report["status"] != "passed" || report["scope"] != "fixed_complete_AgentX_comparison" { + return Err("MLflow performance publication requires a complete non-CPU campaign".into()); + } + let arms = report["arms"].as_array().ok_or("arms missing")?; + final_sweep::validate_work(arms)?; + let campaign = report["campaign"].as_str().ok_or("campaign missing")?; + let model = report["model_key"].as_str().ok_or("model key missing")?; + let backend = report["backend"].as_str().ok_or("backend missing")?; + let source = report["source_attribution"]["product"] + .as_str() + .ok_or("source missing")?; + let mut tags = BTreeMap::from([ + ("ax.campaign".into(), campaign.into()), + ("ax.model_key".into(), model.into()), + ("ax.backend".into(), backend.into()), + ("ax.source_commit".into(), source.into()), + ("ax.audit_state".into(), "verified_work_accounting".into()), + ("ax.report_sha256".into(), input.report.sha256.clone()), + ("ax.archive_sha256".into(), input.archive.sha256.clone()), + ]); + let catalog: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + ))?; + let selected = catalog + .iter() + .find(|row| row.key == model) + .ok_or("unknown publication model")?; + tags.insert("ax.model_ref".into(), selected.registry_ref()); + tags.insert("ax.model_sha256".into(), selected.files[0].sha256.clone()); + tags.insert("ax.category".into(), selected.family.clone()); + tags.insert("ax.stage".into(), "final-comparison".into()); + for (key, pointer) in [ + ( + "ax.native_source_commit", + "/request/tools/native_source_commit", + ), + ( + "ax.native_patch_digest", + "/request/tools/native_patch_digest", + ), + ("ax.runtime_sha256", "/request/tools/runtime/sha256"), + ("ax.skippy_sha256", "/request/tools/skippy/sha256"), + ("ax.llama_sha256", "/request/tools/llama/sha256"), + ( + "ax.standard_runtime_sha256", + "/request/tools/standard_runtime/sha256", + ), + ("ax.client_sha256", "/request/tools/client/sha256"), + ( + "ax.client_environment_sha256", + "/request/tools/client_environment/sha256", + ), + ("ax.corpus_sha256", "/request/corpus/sha256"), + ( + "ax.automation_sha256", + "/source_attribution/automation_binary_sha256", + ), + ] { + tags.insert( + key.into(), + report + .pointer(pointer) + .and_then(Value::as_str) + .ok_or("publication provenance missing")? + .into(), + ); + } + tags.insert("ax.cohort_sha256".into(), final_sweep::COHORT_SHA.into()); + tags.insert( + "ax.work_sha256".into(), + arms[0]["cells"][0]["completed_work"]["source_turn_output_sha256"] + .as_str() + .ok_or("work identity missing")? + .into(), + ); + for (field, key) in [("jy_job_id", "ax.job_id"), ("jy_run_id", "ax.run_id")] { + if let Some(value) = report[field].as_str() { + tags.insert(key.into(), value.into()); + } + } + let key = format!("{campaign}:{source}:{backend}:{model}"); + let mut children = Vec::new(); + for (index, arm) in arms.iter().enumerate() { + let engine = arm["engine"].as_str().ok_or("engine missing")?; + let mut metrics = BTreeMap::new(); + for cell in arm["cells"].as_array().ok_or("cells missing")? { + let concurrency = cell["offered_sessions"] + .as_u64() + .ok_or("concurrency missing")?; + let prefix = format!("c{concurrency}"); + for (name, pointer) in [ + ("output_tok_s", "/output_tok_s"), + ("ttft_p50_ms", "/ttft/p50"), + ("ttft_p95_ms", "/ttft/p95"), + ("itl_p50_ms", "/itl/p50"), + ("cache_read_tokens_avg", "/cache_read_tokens/avg"), + ( + "peak_process_rss_bytes", + "/memory/sampled_peak_process_rss_bytes", + ), + ( + "peak_process_footprint_bytes", + "/memory/sampled_peak_process_physical_footprint_bytes", + ), + ( + "peak_cuda_process_accounted_bytes", + "/memory/sampled_peak_cuda_process_accounted_memory_bytes", + ), + ] { + if let Some(value) = cell.pointer(pointer).and_then(Value::as_f64) { + if !value.is_finite() || value < 0.0 { + return Err("nonfinite/negative publication metric".into()); + } + metrics.insert(format!("{prefix}.{name}"), value); + } + } + metrics.insert(format!("{prefix}.requests"), 69.0); + metrics.insert(format!("{prefix}.output_tokens"), 18713.0); + } + let mut child_tags = tags.clone(); + child_tags.insert("ax.engine".into(), engine.into()); + child_tags.insert("ax.arm".into(), (index + 1).to_string()); + children.push(Child { + run_key: format!("{key}:arm{}", index + 1), + name: format!("{backend} {model} arm{} {engine}", index + 1), + tags: child_tags, + metrics, + }); + } + Ok(Plan { + schema_version: 1, + experiment_id: EXPERIMENT.into(), + expected_experiment_name: EXPERIMENT_NAME.into(), + campaign_root: CampaignRoot { + run_key: format!("{campaign}:{source}:root"), + name: campaign.into(), + tags: BTreeMap::from([ + ("ax.campaign".into(), campaign.into()), + ("ax.source_commit".into(), source.into()), + ("ax.stage".into(), "four-model-two-backend-campaign".into()), + ( + "ax.completion_policy".into(), + "pending_external_eight_group_audit".into(), + ), + ]), + }, + run_key: format!("{key}:parent"), + name: format!("{campaign} {backend} {model}"), + tags, + children, + report: input.report, + archive: input.archive, + }) +} +pub(super) fn validate_experiment(value: &Value) -> DynResult<()> { + let experiment = &value["experiment"]; + if experiment["experiment_id"] != EXPERIMENT + || experiment["name"] != EXPERIMENT_NAME + || experiment["lifecycle_stage"] != "active" + { + return Err( + "existing AgentX experiment6/name/active state required; creation is forbidden".into(), + ); + } + Ok(()) +} +pub(super) fn validate_plan(plan: &Plan) -> DynResult<()> { + if plan.schema_version != 1 + || plan.experiment_id != EXPERIMENT + || plan.expected_experiment_name != EXPERIMENT_NAME + { + return Err("publication plan cannot select another experiment".into()); + } + plan.report.verify()?; + plan.archive.verify()?; + let report: Value = serde_json::from_slice(&crate::automation::receipt_files::bounded( + &plan.report.path, + 4 * 1024 * 1024, + )?)?; + let expected = build( + &report, + Input { + report: plan.report.clone(), + archive: plan.archive.clone(), + }, + )?; + if serde_json::to_value(expected)? != serde_json::to_value(plan)? { + return Err("MLflow plan differs from verified report".into()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn existing_experiment_must_not_be_missing_deleted_or_replaced() { + validate_experiment(&json!({"experiment":{"experiment_id":"6","name":EXPERIMENT_NAME,"lifecycle_stage":"active"}})).unwrap(); + for value in [ + json!({}), + json!({"experiment":{"experiment_id":"7","name":EXPERIMENT_NAME,"lifecycle_stage":"active"}}), + json!({"experiment":{"experiment_id":"6","name":"replacement","lifecycle_stage":"active"}}), + json!({"experiment":{"experiment_id":"6","name":EXPERIMENT_NAME,"lifecycle_stage":"deleted"}}), + ] { + assert!(validate_experiment(&value).is_err()); + } + } + #[test] + fn publication_keeps_shared_campaign_and_complete_work_provenance() { + let tools: Value = serde_json::from_str(include_str!( + "../../../../../skippy/evals/agentx/tools.example.json" + )) + .unwrap(); + let mut report = json!({"status":"passed","scope":"fixed_complete_AgentX_comparison", + "campaign":"agentx-final-fixture","backend":"cuda","model_key":"qwen3.5-4b-q4-k-m", + "source_attribution":{"product":"382c6c62a5e6b7dc9b624f7e64041e39913759d5","automation_binary_sha256":"automation"}, + "request":{"tools":tools,"corpus":{"sha256":"corpus"}},"arms":super::super::final_sweep_tests::arms()}); + report["arms"][0]["cells"][0]["cache_read_tokens"] = json!({"avg":12.5}); + let input = || Input { + report: File { + path: "/report.json".into(), + sha256: "report".into(), + }, + archive: File { + path: "/archive.tar.gz".into(), + sha256: "archive".into(), + }, + }; + let plan = build(&report, input()).unwrap(); + assert_eq!(plan.experiment_id, "6"); + assert_eq!( + plan.campaign_root.run_key, + "agentx-final-fixture:382c6c62a5e6b7dc9b624f7e64041e39913759d5:root" + ); + assert_eq!(plan.children.len(), 6); + assert_eq!(plan.children[0].metrics["c1.cache_read_tokens_avg"], 12.5); + for tag in [ + "ax.native_source_commit", + "ax.native_patch_digest", + "ax.runtime_sha256", + "ax.client_environment_sha256", + "ax.cohort_sha256", + "ax.work_sha256", + ] { + assert!(plan.tags.contains_key(tag), "{tag}"); + } + report["request"]["tools"]["runtime"]["sha256"] = Value::Null; + assert!(build(&report, input()).is_err()); + report["scope"] = json!("cpu_diagnostic_not_gpu_performance"); + assert!(build(&report, input()).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/mlflow_publish.rs b/tools/xtask/src/automation/agentx/mlflow_publish.rs new file mode 100644 index 0000000000..4980d86b18 --- /dev/null +++ b/tools/xtask/src/automation/agentx/mlflow_publish.rs @@ -0,0 +1,294 @@ +//! Explicit publication into existing experiment6, preserving historical runs. +use super::{ + command, inputs, + mlflow_export::{self, Plan}, + prepared_tools::File, + write, +}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + io::Write, + path::{Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; + +struct Client { + base: url::Url, + auth: tempfile::NamedTempFile, + output: PathBuf, + sequence: u32, +} +impl Client { + fn new(output: &Path) -> DynResult { + let base = url::Url::parse(&std::env::var("MLFLOW_TRACKING_URI")?)?; + if base.scheme() != "https" + || !base.username().is_empty() + || base.password().is_some() + || base.query().is_some() + || base.fragment().is_some() + { + return Err("MLflow requires clean HTTPS tracking URI".into()); + } + let user = std::env::var("MLFLOW_TRACKING_USERNAME")?; + let password = std::env::var("MLFLOW_TRACKING_PASSWORD")?; + if [&user, &password] + .into_iter() + .any(|v| v.contains(['\r', '\n', '\0']) || v.len() > 8192) + { + return Err("invalid MLflow credential shape".into()); + } + let escape = |value: &str| value.replace('\\', "\\\\").replace('"', "\\\""); + let mut auth = tempfile::NamedTempFile::new()?; + writeln!(auth, "user = \"{}:{}\"", escape(&user), escape(&password))?; + auth.flush()?; + Ok(Self { + base, + auth, + output: output.into(), + sequence: 0, + }) + } + fn request( + &mut self, + route: &str, + method: &str, + body: Option<&Value>, + file: Option<&File>, + ) -> DynResult { + self.sequence += 1; + let label = format!("mlflow-{:03}", self.sequence); + let endpoint = self.base.join(route)?; + let mut args = vec![ + "--disable".into(), + "--silent".into(), + "--show-error".into(), + "--fail-with-body".into(), + "--proto".into(), + "=https".into(), + "--max-time".into(), + "120".into(), + "--max-filesize".into(), + "4194304".into(), + "--config".into(), + self.auth.path().to_string_lossy().into_owned(), + "--request".into(), + method.into(), + endpoint.to_string(), + ]; + if let Some(body) = body { + let path = self.output.join(format!("{label}.request.json")); + write(&path, body)?; + args.extend([ + "--header".into(), + "Content-Type: application/json".into(), + "--data-binary".into(), + format!("@{}", path.display()), + ]); + } + if let Some(file) = file { + file.verify()?; + args.extend([ + "--upload-file".into(), + file.path.to_string_lossy().into_owned(), + ]); + } + let spec = command::spec(&self.output, "curl", &args)?; + command::run(&spec, 140, &self.output.join(&label))?; + let bytes = crate::automation::receipt_files::bounded( + &self.output.join(format!("{label}.stdout.log")), + 4 * 1024 * 1024, + )?; + if bytes.iter().all(u8::is_ascii_whitespace) { + return Ok(Value::Null); + } + Ok(serde_json::from_slice(&bytes)?) + } + fn api(&mut self, operation: &str, body: &Value) -> DynResult { + self.request( + &format!("/api/2.0/mlflow/{operation}"), + "POST", + Some(body), + None, + ) + } + fn ensure_run( + &mut self, + key: &str, + name: &str, + tags: &BTreeMap, + ) -> DynResult { + if key.len() > 512 + || !key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b)) + { + return Err("invalid idempotent AgentX run key".into()); + } + let response=self.api("runs/search",&json!({"experiment_ids":["6"],"filter":format!("tags.ax_run_key = '{key}'"),"max_results":2}))?; + let runs = response.get("runs").and_then(Value::as_array); + if runs.is_some_and(|rows| rows.len() > 1) { + return Err("duplicate MLflow run keys".into()); + } + if let Some(run) = runs.and_then(|rows| rows.first()) { + let stored = run["data"]["tags"] + .as_array() + .ok_or("MLflow tags missing")?; + for (key, value) in tags { + if !stored + .iter() + .any(|tag| tag["key"] == *key && tag["value"] == *value) + { + return Err("existing MLflow run identity conflicts".into()); + } + } + return Ok(run.clone()); + } + let mut tags = tags.clone(); + tags.insert("ax_run_key".into(), key.into()); + tags.insert("mlflow.runName".into(), name.into()); + let response=self.api("runs/create",&json!({"experiment_id":"6","start_time":now()?,"run_name":name, + "tags":tags.into_iter().map(|(key,value)|json!({"key":key,"value":value})).collect::>()}))?; + response + .get("run") + .cloned() + .ok_or_else(|| "MLflow create response missing run".into()) + } + fn finish(&mut self, run: &Value) -> DynResult { + let id = run_id(run)?; + self.api( + "runs/update", + &json!({"run_id":id,"status":"FINISHED","end_time":now()?}), + )?; + let saved = self.request( + &format!("/api/2.0/mlflow/runs/get?run_id={id}"), + "GET", + None, + None, + )?; + if saved["run"]["info"]["status"] != "FINISHED" { + return Err("MLflow completion readback failed".into()); + } + Ok(saved["run"].clone()) + } + fn artifact(&mut self, run: &Value, name: &str, file: &File) -> DynResult<()> { + let uri = run["info"]["artifact_uri"] + .as_str() + .ok_or("MLflow artifact URI missing")?; + let path = uri + .strip_prefix("mlflow-artifacts:/6/") + .ok_or("existing experiment6 artifact proxy required")?; + if path.split('/').any(|part| part == "..") || name.contains('/') { + return Err("invalid MLflow artifact route".into()); + } + let route = format!("/api/2.0/mlflow-artifacts/artifacts/6/{path}/{name}"); + self.request(&route, "PUT", None, Some(file))?; + self.sequence += 1; + let destination = self + .output + .join(format!("artifact-{}.verified", self.sequence)); + let spec = command::spec( + &self.output, + "curl", + &[ + "--disable".into(), + "--silent".into(), + "--show-error".into(), + "--fail".into(), + "--proto".into(), + "=https".into(), + "--max-time".into(), + "120".into(), + "--config".into(), + self.auth.path().to_string_lossy().into(), + "--max-filesize".into(), + std::fs::metadata(&file.path)? + .len() + .saturating_add(1) + .to_string(), + "--output".into(), + destination.to_string_lossy().into(), + self.base.join(&route)?.to_string(), + ], + )?; + command::run( + &spec, + 140, + &self.output.join(format!("artifact-{}", self.sequence)), + )?; + File { + path: destination, + sha256: file.sha256.clone(), + } + .verify()?; + Ok(()) + } +} +fn run_id(run: &Value) -> DynResult<&str> { + let id = run["info"]["run_id"] + .as_str() + .ok_or("MLflow run ID missing")?; + if id.len() != 32 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("invalid MLflow run ID".into()); + } + Ok(id) +} +fn now() -> DynResult { + Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()) +} +pub(super) fn run(plan: Plan, output: &Path) -> DynResult<()> { + mlflow_export::validate_plan(&plan)?; + std::fs::create_dir(output)?; + let mut client = Client::new(output)?; + let existing = client.request( + "/api/2.0/mlflow/experiments/get?experiment_id=6", + "GET", + None, + None, + )?; + mlflow_export::validate_experiment(&existing)?; + let campaign_root = client.ensure_run( + &plan.campaign_root.run_key, + &plan.campaign_root.name, + &plan.campaign_root.tags, + )?; + let mut group_tags = plan.tags.clone(); + group_tags.insert("mlflow.parentRunId".into(), run_id(&campaign_root)?.into()); + let parent = client.ensure_run(&plan.run_key, &plan.name, &group_tags)?; + let parent_id = run_id(&parent)?.to_string(); + let mut index = Vec::new(); + for child in &plan.children { + let mut tags = child.tags.clone(); + tags.insert("mlflow.parentRunId".into(), parent_id.clone()); + let run = client.ensure_run(&child.run_key, &child.name, &tags)?; + let saved = if run["info"]["status"] != "FINISHED" { + let timestamp = now()?; + client.api("runs/log-batch",&json!({"run_id":run_id(&run)?,"params":[],"tags":[], + "metrics":child.metrics.iter().map(|(key,value)|json!({"key":key,"value":value,"timestamp":timestamp,"step":0})).collect::>()}))?; + client.finish(&run)? + } else { + run.clone() + }; + for (key, value) in &child.metrics { + if !saved["data"]["metrics"].as_array().is_some_and(|rows| { + rows.iter() + .any(|row| row["key"] == *key && row["value"].as_f64() == Some(*value)) + }) { + return Err("MLflow metric readback differs from campaign".into()); + } + } + index.push(json!({"run_key":child.run_key,"run_id":run_id(&run)?})); + } + client.artifact(&parent, "campaign-result.json", &plan.report)?; + client.artifact(&parent, "campaign-evidence.tar.gz", &plan.archive)?; + client.finish(&parent)?; + write( + &output.join("publication.json"), + &json!({"experiment_id":"6","experiment_name":mlflow_export::EXPERIMENT_NAME, + "campaign_run_id":run_id(&campaign_root)?,"campaign_status":"RUNNING until a separate eight-group audit; this publisher finishes only one model/backend group", + "parent_run_id":parent_id,"children":index,"report_sha256":plan.report.sha256,"archive_sha256":plan.archive.sha256, + "publication":"finished; artifacts uploaded, execution/work accounting is distinct from numerical qualification", + "plan_sha256":inputs::digest(&serde_json::to_vec(&plan)?)}), + ) +} diff --git a/tools/xtask/src/automation/agentx/mod.rs b/tools/xtask/src/automation/agentx/mod.rs new file mode 100644 index 0000000000..487bb603f1 --- /dev/null +++ b/tools/xtask/src/automation/agentx/mod.rs @@ -0,0 +1,221 @@ +//! AgentX owns its workload, provenance and lifecycle independently of replay-matrix. +mod agentic_config; +mod cache_decisions; +mod campaign; +mod capacity; +mod command; +mod comparison_cohort; +mod completed_work; +mod container; +mod contention_cohort; +mod context_support; +mod final_sweep; +#[cfg(test)] +mod final_sweep_tests; +mod hardware; +mod inputs; +mod lifecycle; +mod memory; +mod mlflow_export; +mod mlflow_publish; +mod native_kv_span; +mod overlap; +mod phase_outcome; +mod prepared_launch; +mod prepared_tools; +mod results; +mod scheduler_profile; +mod trace_context; +mod workload; +use crate::{command::DynResult, repository::check_args::Grammar}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "kebab-case")] +pub(super) enum Profile { + Smoke, + Benchmark, + Comparison, + Contention, +} +impl Profile { + fn harness_version(self) -> &'static str { + match self { + Self::Smoke => "agentx-1.0.12.post2-local-smoke-9", + Self::Benchmark => "agentx-1.0.12.post2-local-benchmark-8", + Self::Comparison => "agentx-1.0.12.post2-local-comparison-3", + Self::Contention => "agentx-1.0.12.post2-local-contention-2", + } + } + fn label(self) -> &'static str { + match self { + Self::Smoke => "smoke", + Self::Benchmark => "benchmark", + Self::Comparison => "comparison", + Self::Contention => "contention", + } + } + fn parse(value: &str) -> DynResult { + match value { + "smoke" => Ok(Self::Smoke), + "benchmark" => Ok(Self::Benchmark), + "comparison" => Ok(Self::Comparison), + "contention" => Ok(Self::Contention), + _ => Err("profile must be smoke, benchmark, comparison or contention".into()), + } + } + fn concurrencies(self) -> &'static [u32] { + // Offered load is independent of engine-planned serving capacity. + match self { + Self::Contention => &[4, 8, 16], + _ => &[1, 2, 4], + } + } +} +#[derive(Clone, Copy)] +pub(super) enum Engine { + Llama, + Skippy, +} +impl Engine { + fn parse(value: &str) -> DynResult { + match value { + "llama" => Ok(Self::Llama), + "skippy" => Ok(Self::Skippy), + _ => Err("engine must be llama or skippy".into()), + } + } + fn label(self) -> &'static str { + match self { + Self::Llama => "llama", + Self::Skippy => "skippy", + } + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct FilePin { + name: String, + sha256: String, +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Model { + key: String, + family: String, + repo: String, + revision: String, + tokenizer: String, + tokenizer_revision: String, + files: Vec, +} +impl Model { + fn registry_ref(&self) -> String { + format!("hf:{}@{}#{}", self.repo, self.revision, self.files[0].name) + } +} +#[derive(Deserialize, Serialize)] +struct Prepared { + #[serde(default)] + tools: Option, + root: PathBuf, + output: PathBuf, + model: Model, + weights: PathBuf, + dataset: PathBuf, + profile: Profile, +} +pub(crate) fn run(args: &[String]) -> DynResult<()> { + if args == ["--help"] { + return crate::repository::check_report::CheckReport::success(final_sweep::USAGE.into()) + .emit(); + } + if matches!( + args.first().map(String::as_str), + Some("pin" | "comparison" | "mlflow-export" | "mlflow-publish") + ) { + return final_sweep::command(args); + } + if args.first().map(String::as_str) != Some("worker") { + return Err("AgentX accepts comparison --input JSON --output DIR or mlflow-export; legacy unpinned launch modes are not admitted".into()); + } + const GRAMMAR: Grammar = Grammar { + usage: "cargo xtool automation agentx {container|run} --engine {llama|skippy} --model KEY --profile {smoke|benchmark|comparison|contention} --output PATH [--only-concurrency N] | worker --input PATH --port PORT --concurrency N", + values: &[ + "--model", + "--engine", + "--profile", + "--output", + "--input", + "--port", + "--concurrency", + "--only-concurrency", + ], + flags: &["--help"], + }; + let parsed = GRAMMAR + .parse(args) + .map_err(|_| "invalid AgentX arguments")?; + if parsed.flag("--help") { + return crate::repository::check_report::CheckReport::success(GRAMMAR.usage.into()).emit(); + } + match parsed.positionals.as_slice() { + [verb] if *verb == "container" => { + if parsed.last("--only-concurrency").is_some() { + return Err( + "only-concurrency applies to a native run, not a container launch".into(), + ); + } + container::run( + Engine::parse(parsed.last("--engine").ok_or("missing engine")?)?, + parsed.last("--model").ok_or("missing model")?, + Profile::parse(parsed.last("--profile").ok_or("missing profile")?)?, + PathBuf::from(parsed.last("--output").ok_or("missing output")?), + ) + } + [verb] if *verb == "run" => { + hardware::admit_execution()?; + let root = std::env::current_dir()?; + let profile = Profile::parse(parsed.last("--profile").ok_or("missing profile")?)?; + let output = PathBuf::from(parsed.last("--output").ok_or("missing output")?); + if !output.is_absolute() { + return Err("output must be absolute".into()); + } + std::fs::create_dir(&output)?; + let engine = Engine::parse(parsed.last("--engine").ok_or("missing engine")?)?; + let only_concurrency = parsed + .last("--only-concurrency") + .map(str::parse::) + .transpose()?; + let prepared = inputs::prepare( + root, + output.clone(), + parsed.last("--model").ok_or("missing model")?, + profile, + ); + let result = + prepared.and_then(|prepared| campaign::run(&prepared, engine, only_concurrency)); + let archive = results::archive(&output); + result?; + archive + } + [verb] if *verb == "worker" => { + let prepared: Prepared = serde_json::from_slice(&std::fs::read( + parsed.last("--input").ok_or("missing input")?, + )?)?; + workload::run( + &prepared, + parsed.last("--port").ok_or("missing port")?.parse()?, + parsed + .last("--concurrency") + .ok_or("missing concurrency")? + .parse()?, + ) + } + _ => Err(GRAMMAR.usage.into()), + } +} +fn write(path: &Path, value: &impl Serialize) -> DynResult<()> { + crate::command::write_json_file(path, value) +} diff --git a/tools/xtask/src/automation/agentx/native_kv_span.rs b/tools/xtask/src/automation/agentx/native_kv_span.rs new file mode 100644 index 0000000000..c75111f665 --- /dev/null +++ b/tools/xtask/src/automation/agentx/native_kv_span.rs @@ -0,0 +1,170 @@ +//! Retain only numeric native KV observations from the standalone Skippy CLI. +use std::{ + fs::File, + io::{self, BufWriter, ErrorKind, Write}, + path::Path, +}; + +use crate::process::{ObservedLine, Stream, retained::MemberId}; + +const MAX_OBSERVATIONS: usize = 100_000; + +#[derive(Clone, Copy)] +struct Observation { + stream: u32, + n: u32, + used: u32, + head: u32, + size: u32, + n_swa: u32, +} + +#[derive(Default)] +pub(super) struct NativeKvSpan { + observations: Vec, + overflowed: bool, +} + +impl NativeKvSpan { + pub(super) fn observe(&mut self, member: MemberId, line: &ObservedLine<'_>) { + if member != MemberId::Seed { + return; + } + let observation = match line.stream { + Stream::Stdout => parse_jsonl_observation(line.bytes), + Stream::Stderr => parse_observation(line.bytes), + }; + let Some(observation) = observation else { + return; + }; + if self.observations.len() == MAX_OBSERVATIONS { + self.overflowed = true; + } else { + self.observations.push(observation); + } + } + + pub(super) fn save(&self, output: &Path) -> io::Result { + if self.observations.is_empty() || self.overflowed { + return Err(io::Error::new( + ErrorKind::InvalidData, + "native KV span observations absent or exceeded the bounded capture", + )); + } + let mut retained = BufWriter::new(File::create(output.join("native-kv-span.log"))?); + for observation in &self.observations { + writeln!( + retained, + "find_slot: stream[{}], n = {}, used = {}, head = {}, size = {}, n_swa = {}", + observation.stream, + observation.n, + observation.used, + observation.head, + observation.size, + observation.n_swa, + )?; + } + retained.flush()?; + Ok(self.observations.len()) + } +} + +fn parse_jsonl_observation(bytes: &[u8]) -> Option { + if !std::str::from_utf8(bytes) + .ok()? + .contains("find_slot: stream[") + { + return None; + } + let event: serde_json::Value = serde_json::from_slice(bytes).ok()?; + if event.get("type")?.as_str()? != "native_log" { + return None; + } + parse_observation(event.pointer("/data/message")?.as_str()?.as_bytes()) +} + +fn parse_observation(bytes: &[u8]) -> Option { + let line = std::str::from_utf8(bytes).ok()?; + let (_, values) = line.split_once("find_slot: stream[")?; + let (stream, values) = values.split_once("], n =")?; + let (n, values) = values.split_once(", used =")?; + let (used, values) = values.split_once(", head =")?; + let (head, values) = values.split_once(", size =")?; + let (size, values) = values.split_once(", n_swa =")?; + Some(Observation { + stream: stream.trim().parse().ok()?, + n: n.trim().parse().ok()?, + used: used.trim().parse().ok()?, + head: head.trim().parse().ok()?, + size: size.trim().parse().ok()?, + n_swa: values.trim().parse().ok()?, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::process::LineEnding; + + #[test] + fn saves_only_numeric_standalone_native_observations() { + let dir = tempfile::tempdir().unwrap(); + let mut span = NativeKvSpan::default(); + let native = + b"find_slot: stream[0], n = 256, used = 128, head = 256, size = 4096, n_swa = 0"; + span.observe( + MemberId::Seed, + &ObservedLine { + stream: Stream::Stderr, + bytes: native, + ending: LineEnding::Lf, + }, + ); + span.observe( + MemberId::WorkerOne, + &ObservedLine { + stream: Stream::Stderr, + bytes: native, + ending: LineEnding::Lf, + }, + ); + span.observe( + MemberId::Seed, + &ObservedLine { + stream: Stream::Stderr, + bytes: b"find_slot: stream[secret], n = prompt", + ending: LineEnding::Lf, + }, + ); + assert_eq!(span.save(dir.path()).unwrap(), 1); + let saved = std::fs::read_to_string(dir.path().join("native-kv-span.log")).unwrap(); + assert_eq!(saved.trim(), std::str::from_utf8(native).unwrap()); + } + + #[test] + fn captures_native_kv_spans_from_standalone_jsonl_stdout() { + let dir = tempfile::tempdir().unwrap(); + let mut span = NativeKvSpan::default(); + let native = br#"{"data":{"message":"find_slot: stream[0], n = 256, used = 128, head = 256, size = 4096, n_swa = 0\n"},"schema_version":1,"sequence":17,"type":"native_log"}"#; + for (member, bytes) in [ + (MemberId::Seed, native.as_slice()), + (MemberId::WorkerOne, native.as_slice()), + (MemberId::Seed, br#"{"data":{"message":"find_slot: stream[1], n = 1, used = 1, head = 1, size = 1, n_swa = 0"},"type":"status"}"#.as_slice()), + ] { + span.observe( + member, + &ObservedLine { + stream: Stream::Stdout, + bytes, + ending: LineEnding::Lf, + }, + ); + } + assert_eq!(span.save(dir.path()).unwrap(), 1); + let saved = std::fs::read_to_string(dir.path().join("native-kv-span.log")).unwrap(); + assert_eq!( + saved.trim(), + "find_slot: stream[0], n = 256, used = 128, head = 256, size = 4096, n_swa = 0" + ); + } +} diff --git a/tools/xtask/src/automation/agentx/overlap.rs b/tools/xtask/src/automation/agentx/overlap.rs new file mode 100644 index 0000000000..cbd5c059e9 --- /dev/null +++ b/tools/xtask/src/automation/agentx/overlap.rs @@ -0,0 +1,105 @@ +//! Client HTTP overlap is evidence of in-flight requests, not GPU decode slots. +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + io::{BufRead, BufReader}, + path::Path, +}; + +pub(super) fn read(output: &Path) -> Value { + match measure(&output.join("upstream/profile_export.jsonl")) { + Ok((requests, peak)) => json!({"source":"client_http_trace", "requests":requests, + "peak_in_flight_requests":peak,"gpu_decode_concurrency":null}), + Err(error) => json!({"source":"client_http_trace", "peak_in_flight_requests":null, + "gpu_decode_concurrency":null,"unavailable_reason":error.to_string()}), + } +} + +fn measure(path: &Path) -> DynResult<(usize, i64)> { + let mut boundaries = BTreeMap::::new(); + let mut requests = 0; + for line in BufReader::new(std::fs::File::open(path)?).lines() { + let record: Value = serde_json::from_str(&line?)?; + let phase = record["metadata"]["benchmark_phase"] + .as_str() + .ok_or("missing AgentX benchmark phase")?; + if phase != "profiling" { + continue; + } + let trace = &record["trace_data"]; + let start = trace["request_send_start_ns"] + .as_u64() + .ok_or("missing HTTP start")?; + let end = trace["response_receive_end_ns"] + .as_u64() + .ok_or("missing HTTP end")?; + if end <= start { + return Err("invalid HTTP interval".into()); + } + *boundaries.entry(start).or_default() += 1; + *boundaries.entry(end).or_default() -= 1; + requests += 1; + } + if requests == 0 { + return Err("no profiling HTTP intervals".into()); + } + let (mut active, mut peak) = (0, 0); + for delta in boundaries.values() { + active += delta; + peak = peak.max(active); + } + Ok((requests, peak)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn measures_overlap_excluding_warmup_and_touching_intervals() { + let file = tempfile::NamedTempFile::new().unwrap(); + let rows = [ + ("warmup", 0, 100), + ("profiling", 1, 5), + ("profiling", 2, 4), + ("profiling", 5, 9), + ] + .map(|(phase, start, end)| { + json!({"metadata":{"benchmark_phase":phase}, + "trace_data":{"request_send_start_ns":start,"response_receive_end_ns":end}}) + .to_string() + }); + std::fs::write(file.path(), rows.join("\n")).unwrap(); + assert_eq!(measure(file.path()).unwrap(), (3, 2)); + std::fs::write(file.path(), "{}").unwrap(); + assert!(measure(file.path()).is_err()); + } + + #[test] + fn reads_pinned_agentx_export_with_fewer_active_requests_than_offered_sessions() { + // Reduced AgentX 1.0.7 export from an offered-c4 smoke. Preserve the + // real phase and interval fields; omit request identities and payloads. + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write( + file.path(), + include_str!("../../../tests/fixtures/agentx/http-overlap.jsonl"), + ) + .unwrap(); + assert_eq!(measure(file.path()).unwrap(), (3, 3)); + } + + #[test] + fn rejects_missing_phase_and_incomplete_http_intervals() { + let file = tempfile::NamedTempFile::new().unwrap(); + for record in [ + json!({"metadata":{"credit_phase":"profiling"}}), + json!({"metadata":{"benchmark_phase":"profiling"}, + "trace_data":{"request_send_start_ns":1}}), + json!({"metadata":{"benchmark_phase":"profiling"}, + "trace_data":{"request_send_start_ns":5,"response_receive_end_ns":5}}), + ] { + std::fs::write(file.path(), record.to_string()).unwrap(); + assert!(measure(file.path()).is_err()); + } + } +} diff --git a/tools/xtask/src/automation/agentx/phase_outcome.rs b/tools/xtask/src/automation/agentx/phase_outcome.rs new file mode 100644 index 0000000000..5766439813 --- /dev/null +++ b/tools/xtask/src/automation/agentx/phase_outcome.rs @@ -0,0 +1,114 @@ +use crate::command::DynResult; +use serde::Serialize; + +/// AgentX 1.0.7 omits grace-period cancellations from its aggregate JSON. +/// Its pinned phase-complete log is the authoritative request accounting. +#[derive(Default, Debug, Serialize, PartialEq)] +pub(super) struct PhaseOutcome { + pub completed: u64, + pub cancelled: u64, + pub errors: u64, +} + +pub(super) fn parse(log: &str, expected_completed: u64) -> DynResult { + let outcome = parse_counts(log, expected_completed)?; + if outcome.errors != 0 { + return Err("AgentX profiling phase contains request errors".into()); + } + Ok(outcome) +} + +pub(super) fn context_limited( + log: &str, + completed: u64, + overflows: u64, +) -> DynResult { + let total = completed + .checked_add(overflows) + .ok_or("request count overflow")?; + let outcome = parse_counts(log, total)?; + if overflows == 0 || outcome.errors != overflows || outcome.cancelled != 0 { + return Err("context overflows do not account for all unsuccessful requests".into()); + } + Ok(outcome) +} + +fn parse_counts(log: &str, expected_completed: u64) -> DynResult { + let mut outcome = PhaseOutcome::default(); + let mut phases = 0; + for line in log.lines() { + let Some((_, counters)) = line.split_once("(profiling) complete | ") else { + continue; + }; + let counters = counters + .split(" | ") + .next() + .ok_or("missing phase counters")?; + let values = counters.split(", ").collect::>(); + let [completed, cancelled, errors] = values.as_slice() else { + return Err("invalid AgentX phase counters".into()); + }; + for (total, field, prefix) in [ + (&mut outcome.completed, *completed, "completed="), + (&mut outcome.cancelled, *cancelled, "cancelled="), + (&mut outcome.errors, *errors, "errors="), + ] { + let value: u64 = field + .strip_prefix(prefix) + .ok_or("missing phase counter")? + .parse()?; + *total = total.checked_add(value).ok_or("phase counter overflow")?; + } + phases += 1; + } + if phases == 0 || outcome.completed != expected_completed { + return Err( + "AgentX phase accounting missing or disagrees with exported completions".into(), + ); + } + Ok(outcome) +} + +#[cfg(test)] +mod tests { + use super::*; + + const DRAINED: &str = "12:21:29 NOTICE Phase profiling (profiling) complete | completed=6, cancelled=1, errors=0 | sessions: completed=0, cancelled=0 | elapsed=210.01s | grace_period_timeout=True"; + + #[test] + fn preserves_grace_cancellations_and_excludes_warmup() { + let log = format!( + "Phase warmup (warmup) complete | completed=2, cancelled=0, errors=0\n{DRAINED}" + ); + assert_eq!( + parse(&log, 6).unwrap(), + PhaseOutcome { + completed: 6, + cancelled: 1, + errors: 0 + } + ); + } + + #[test] + fn rejects_missing_malformed_failed_and_inconsistent_accounting() { + for (log, expected) in [ + (String::new(), 6), + (DRAINED.to_owned(), 7), + (DRAINED.replace("cancelled=1", "cancelled=-1"), 6), + (DRAINED.replace("errors=0", "errors=1"), 6), + ] { + assert!(parse(&log, expected).is_err()); + } + } + + #[test] + fn sums_multiple_measured_phases() { + assert_eq!( + parse(&format!("{DRAINED}\n{DRAINED}"), 12) + .unwrap() + .cancelled, + 2 + ); + } +} diff --git a/tools/xtask/src/automation/agentx/prepared_launch.rs b/tools/xtask/src/automation/agentx/prepared_launch.rs new file mode 100644 index 0000000000..f0b802fe45 --- /dev/null +++ b/tools/xtask/src/automation/agentx/prepared_launch.rs @@ -0,0 +1,142 @@ +//! Final comparison launch settings and pre-load resolved-capacity evidence. +use super::{ + Prepared, command, + prepared_tools::{Backend, Tools}, + write, +}; +use crate::{command::DynResult, process}; +use serde_json::{Value, json}; + +pub(super) fn arguments(args: &mut Vec, engine: &str, tools: &Tools) { + if let Some(index) = args.iter().position(|arg| arg == "--n-gpu-layers") { + args[index + 1] = if tools.backend == Backend::Cpu { + "0" + } else { + "99" + } + .into(); + } + args.extend([ + "--threads".into(), + tools.threads.to_string(), + "--threads-batch".into(), + tools.threads.to_string(), + ]); + if engine == "skippy" { + args.splice(0..0, ["--output".into(), "jsonl".into()]); + args.extend([ + "--ctx-size".into(), + "131072".into(), + "--prefill-chunk-size".into(), + "64".into(), + "--prefill-chunk-policy".into(), + "fixed".into(), + ]); + } +} + +pub(super) fn doctor( + tools: &Tools, + root: &std::path::Path, + output: &std::path::Path, +) -> DynResult<()> { + let spec = command::spec( + root, + tools + .skippy + .path + .to_str() + .ok_or("CLI path Unicode required")?, + &[ + "--output".into(), + "json".into(), + "--runtime-bundle".into(), + tools.runtime.path.to_string_lossy().into(), + "--runtime-selection".into(), + tools.backend.name().into(), + "doctor".into(), + ], + )?; + command::run(&spec, 120, &output.join("doctor"))?; + let value: Value = serde_json::from_slice(&std::fs::read(output.join("doctor.stdout.log"))?)?; + if value["native_runtime"]["path"].as_str() != tools.runtime.path.to_str() + || value + .get("runtime_issue") + .is_none_or(|issue| !issue.is_null()) + { + return Err("doctor must select the exact prepared runtime leaf without issue".into()); + } + Ok(()) +} + +pub(super) fn effective_config(input: &Prepared, server: &process::ProcessSpec) -> DynResult<()> { + let mut probe = process::ProcessSpec { + executable: server.executable.clone(), + arguments: server.arguments.clone(), + cwd: server.cwd.clone(), + environment: server.environment.clone(), + }; + if let Some(index) = probe + .arguments + .iter() + .position(|arg| matches!(arg,process::Value::Public(v) if v=="--output")) + { + probe.arguments[index + 1] = process::Value::Public("json".into()); + } + probe + .arguments + .push(process::Value::Public("--print-effective-config".into())); + command::run(&probe, 900, &input.output.join("effective-config"))?; + let value: Value = serde_json::from_slice(&std::fs::read( + input.output.join("effective-config.stdout.log"), + )?)?; + validate_config( + &value, + input + .tools + .as_ref() + .ok_or("prepared launch missing tools")?, + )?; + write(&input.output.join("effective-config.json"), &value) +} +pub(super) fn validate_config(value: &Value, tools: &Tools) -> DynResult<()> { + let stage = &value["stage"]; + let lanes = stage["lane_count"] + .as_u64() + .filter(|n| *n > 0) + .ok_or("resolved lanes unavailable")?; + if stage["ctx_size"] != 131072 + || stage["n_batch"] != 2048 + || stage["n_ubatch"] != 512 + || stage["cache_type_k"] != "f16" + || stage["cache_type_v"] != "f16" + || stage["flash_attn_type"] != "enabled" + || stage["kv_cache"]["l2_max_bytes"] != 8589934592u64 + || value["options"]["kv-cache-disk"] != "off" + || value["execution"]["threads"] != tools.threads + || value["execution"]["threads_batch"] != tools.threads + || value["frontend"]["prefill_chunk_size"] != 64 + || value["frontend"]["prefill_chunk_policy"] != "fixed" + || value["frontend"]["generation_concurrency"].as_u64() != Some(lanes) + || value["constraints"]["unified_kv"] != "required" + || stage["kv_unified"] == false + || tools + .diagnostic_generation_lanes + .is_some_and(|n| u64::from(n) != lanes) + { + return Err("resolved Skippy settings disagree with the final comparison contract".into()); + } + Ok(()) +} +pub(super) fn configured(output: &std::path::Path) -> Option { + let config: Value = + serde_json::from_slice(&std::fs::read(output.join("effective-config.json")).ok()?).ok()?; + let context = config["stage"]["ctx_size"].as_u64()?; + let lanes = config["stage"]["lane_count"].as_u64()?; + Some( + json!({"status":"observed","source":"print-effective-config_before_model_load", + "context_tokens_per_lane":context,"lanes":lanes,"configured_pool_tokens":context.checked_mul(lanes)?, + "native_allocation":"separately observed; configured pool is not a memory residency measurement", + "frontend":config["frontend"],"execution":config["execution"],"kv_cache":config["stage"]["kv_cache"]}), + ) +} diff --git a/tools/xtask/src/automation/agentx/prepared_tools.rs b/tools/xtask/src/automation/agentx/prepared_tools.rs new file mode 100644 index 0000000000..c53898cfc2 --- /dev/null +++ b/tools/xtask/src/automation/agentx/prepared_tools.rs @@ -0,0 +1,230 @@ +//! Prepared offline tools: byte identities are authoritative, source IDs are provenance. +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Debug)] +#[serde(rename_all = "lowercase")] +pub(super) enum Backend { + Cpu, + Cuda, + Metal, +} +impl Backend { + pub(super) fn name(self) -> &'static str { + match self { + Self::Cpu => "cpu", + Self::Cuda => "cuda", + Self::Metal => "metal", + } + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct File { + pub path: PathBuf, + pub sha256: String, +} +impl File { + pub(super) fn verify(&self) -> DynResult<()> { + absolute(&self.path)?; + if crate::product::digest::file_sha256(&self.path).map_err(|e| e.error)? != self.sha256 { + return Err(format!("prepared file SHA mismatch: {}", self.path.display()).into()); + } + Ok(()) + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Tree { + pub path: PathBuf, + pub sha256: String, +} +impl Tree { + pub(super) fn verify(&self) -> DynResult<()> { + if self.observe()? != self.sha256 { + return Err(format!("prepared tree SHA mismatch: {}", self.path.display()).into()); + } + Ok(()) + } + pub(super) fn observe(&self) -> DynResult { + absolute(&self.path)?; + // Unlike the runtime-only validator, a prepared Python environment may + // contain interpreter links outside the environment. Charge their actual + // regular-file bytes. Internal directory aliases (venv lib64 -> lib) + // are hashed as aliases without traversal; external editable installs + // remain refused. + let root = self.path.canonicalize()?; + let mut aliases = Vec::new(); + let mut pending = vec![(self.path.clone(), 0)]; + let mut count = 0usize; + while let Some((dir, depth)) = pending.pop() { + if depth > 64 { + return Err("prepared tree exceeds64 levels".into()); + } + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + count += 1; + if count > 250_000 { + return Err("prepared tree exceeds250000 entries".into()); + } + entry + .file_name() + .to_str() + .ok_or("prepared tree names must be Unicode")?; + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push((entry.path(), depth + 1)); + } else if kind.is_symlink() && entry.path().canonicalize()?.is_dir() { + let target = entry.path().canonicalize()?; + if !target.starts_with(&root) { + return Err("prepared directory alias escapes its root".into()); + } + aliases.push(( + entry + .path() + .strip_prefix(&self.path)? + .to_str() + .ok_or("alias path Unicode required")? + .to_owned(), + target + .strip_prefix(&root)? + .to_str() + .ok_or("alias target Unicode required")? + .to_owned(), + )); + } else if !kind.is_file() + && !(kind.is_symlink() && entry.path().canonicalize()?.is_file()) + { + return Err("prepared trees require regular files or regular-file links".into()); + } + } + } + if count == 0 { + return Err("prepared tree is empty".into()); + } + let files = crate::product::digest::tree_sha256(&self.path).map_err(|e| e.error)?; + if aliases.is_empty() { + return Ok(files); + } + use sha2::{Digest, Sha256}; + aliases.sort(); + let mut hash = Sha256::new(); + hash.update(b"agentx-prepared-tree-aliases-v1\0"); + hash.update(files.as_bytes()); + for (path, target) in aliases { + for value in [path, target] { + hash.update((value.len() as u64).to_be_bytes()); + hash.update(value.as_bytes()); + } + } + Ok(hex::encode(hash.finalize())) + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Tools { + pub backend: Backend, + pub product_source_commit: String, + pub native_source_commit: String, + pub native_patch_digest: String, + pub runtime: Tree, + pub skippy: File, + pub llama: File, + pub standard_runtime: Tree, + pub standard_upstream: String, + pub client: File, + pub client_environment: Tree, + pub client_lock: File, + pub tokenizer: Tree, + pub threads: u32, + /// None preserves the product's automatic lane plan independently of offered C. + pub diagnostic_generation_lanes: Option, + pub diagnostic_cpu: bool, + pub cell_seconds: u64, +} +impl Tools { + pub(super) fn pin(&mut self) -> DynResult<()> { + for file in [ + &mut self.skippy, + &mut self.llama, + &mut self.client, + &mut self.client_lock, + ] { + file.sha256 = crate::product::digest::file_sha256(&file.path).map_err(|e| e.error)?; + } + for tree in [ + &mut self.runtime, + &mut self.standard_runtime, + &mut self.client_environment, + &mut self.tokenizer, + ] { + tree.sha256 = tree.observe()?; + } + Ok(()) + } + pub(super) fn verify(&self, root: &Path) -> DynResult<()> { + for source in [ + &self.product_source_commit, + &self.native_source_commit, + &self.standard_upstream, + ] { + if !hex(source, 40) { + return Err("prepared source requires full40-hex commit".into()); + } + } + if self.threads == 0 + || self.threads > 1024 + || !(60..=14_400).contains(&self.cell_seconds) + || self + .diagnostic_generation_lanes + .is_some_and(|n| n == 0 || n > 256) + || (self.backend == Backend::Cpu && !self.diagnostic_cpu) + { + return Err("invalid prepared bounds or CPU performance qualification request".into()); + } + for file in [&self.skippy, &self.llama, &self.client, &self.client_lock] { + file.verify()?; + } + for tree in [ + &self.runtime, + &self.standard_runtime, + &self.client_environment, + &self.tokenizer, + ] { + tree.verify()?; + } + let lock = std::fs::read(root.join("skippy/evals/agentx/uv.lock"))?; + if super::inputs::digest(&lock) != self.client_lock.sha256 { + return Err("client lock differs from the owned external AgentX lock".into()); + } + if std::fs::read_to_string(root.join("skippy/llama_cpp/upstream.txt"))?.trim() + != self.standard_upstream + { + return Err("standard llama must use the candidate's unpatched upstream pin".into()); + } + let manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(self.runtime.path.join("manifest.json"))?)?; + self.validate_manifest(&manifest) + } + pub(super) fn validate_manifest(&self, manifest: &serde_json::Value) -> DynResult<()> { + if manifest["runtime"]["backend"]["kind"] != self.backend.name() + || manifest["build"]["llama_patched_sha"] != self.native_source_commit + || manifest["build"]["llama_patch_digest"] != self.native_patch_digest + || manifest["build"]["llama_upstream_sha"] != self.standard_upstream + || manifest["runtime"]["skippy_abi"] != "0.1.76" + { + return Err("runtime must be exact matching ABI76 backend/native leaf".into()); + } + Ok(()) + } +} +pub(super) fn absolute(path: &Path) -> DynResult<()> { + if !path.is_absolute() { + return Err("prepared paths must be absolute".into()); + } + Ok(()) +} +fn hex(value: &str, n: usize) -> bool { + value.len() == n && value.bytes().all(|b| b.is_ascii_hexdigit()) +} diff --git a/tools/xtask/src/automation/agentx/results.rs b/tools/xtask/src/automation/agentx/results.rs new file mode 100644 index 0000000000..0d4f185736 --- /dev/null +++ b/tools/xtask/src/automation/agentx/results.rs @@ -0,0 +1,249 @@ +use super::{Prepared, Profile, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use std::path::Path; + +fn metric(export: &Value, name: &str) -> DynResult { + export[name]["avg"] + .as_f64() + .filter(|value| value.is_finite()) + .ok_or_else(|| format!("missing finite AgentX metric: {name}").into()) +} +fn count(export: &Value, name: &str) -> DynResult { + let value = metric(export, name)?; + if value < 0.0 || value.fract() != 0.0 || value > (1_u64 << 53) as f64 { + return Err(format!("invalid AgentX count: {name}").into()); + } + Ok(value as u64) +} + +fn validate_output_numerator(export: &Value, completed_work: &Value) -> DynResult<()> { + let output_tokens = completed_work["output_tokens"] + .as_u64() + .ok_or("missing completed AgentX output count")?; + if count(export, "total_output_tokens")? != output_tokens + || count(export, "total_osl")? != output_tokens + { + return Err("AgentX throughput numerator differs from completed fixed work".into()); + } + Ok(()) +} + +fn distribution(export: &Value, name: &str) -> DynResult { + if export[name]["unit"] != "ms" || metric(export, name)? < 0.0 { + return Err(format!("expected nonnegative milliseconds: {name}").into()); + } + let mut percentiles = serde_json::Map::new(); + for (key, value) in export[name].as_object().ok_or("metric is not an object")? { + if let Some(percentile) = key.strip_prefix('p') + && percentile + .parse::() + .is_ok_and(|p| (0.0..=100.0).contains(&p)) + { + if !value.as_f64().is_some_and(|v| v.is_finite() && v >= 0.0) { + return Err(format!("invalid percentile: {name}.{key}").into()); + } + percentiles.insert(percentile.into(), value.clone()); + } + } + Ok(json!({"mean":metric(export,name)?,"p":percentiles})) +} + +pub(super) fn point(input: &Prepared, concurrency: u32) -> DynResult { + let export: Value = serde_json::from_slice(&std::fs::read( + input.output.join("upstream/profile_export_aiperf.json"), + )?)?; + validate(&export, input.profile)?; + metric_point(&export, concurrency) +} + +fn metric_point(export: &Value, concurrency: u32) -> DynResult { + let duration = metric(export, "benchmark_duration")?; + let throughput = metric(export, "output_token_throughput")?; + if export["benchmark_duration"]["unit"] != "sec" + || export["output_token_throughput"]["unit"] != "tokens/sec" + || duration <= 0.0 + || throughput <= 0.0 + { + return Err("invalid AgentX duration or throughput".into()); + } + Ok(json!({ + "concurrency":concurrency, + "requests_completed":count(export,"request_count")?,"requests_failed":0, + "duration_s":duration, + "throughput":{"output_tok_s":throughput}, + "tokens":{"input":count(export,"total_usage_prompt_tokens")?, + "output":count(export,"total_output_tokens")?}, + "ttft_ms":distribution(export,"time_to_first_token")?, + "tpot_ms":distribution(export,"inter_token_latency")?, + "e2e_ms":distribution(export,"request_latency")? + })) +} +pub(super) fn validate(export: &Value, profile: Profile) -> DynResult<()> { + let submission = &export["metadata"]["submission_valid"]; + let local = if matches!(profile, Profile::Comparison | Profile::Contention) { + submission.is_null() + } else { + submission == false + }; + if export["was_cancelled"] == true || !local { + return Err("expected uncancelled, explicitly non-submission local-corpus export".into()); + } + if metric(export, "request_count")? < 1.0 + || metric(export, "output_token_count")? < 1.0 + || metric(export, "usage_prompt_tokens")? < 1.0 + || metric(export, "usage_completion_tokens")? < 1.0 + || metric(export, "time_to_first_token")? < 0.0 + || metric(export, "inter_token_latency")? < 0.0 + { + return Err( + "AgentX requires completed measured requests, token usage and streaming metrics".into(), + ); + } + let errors = export["error_request_count"]["avg"].as_f64().unwrap_or(0.0); + let overflow = export["context_overflow_count"]["avg"] + .as_f64() + .unwrap_or(0.0); + if errors != 0.0 || overflow != 0.0 { + return Err("AgentX cell contains failed or context-overflow requests".into()); + } + if profile == Profile::Smoke && export["warmup_metrics"].is_null() { + return Err("duration-bounded warmup evidence missing".into()); + } + Ok(()) +} +pub(super) fn read(input: &Prepared, engine: &str, concurrency: u32) -> DynResult { + let path = input.output.join("upstream/profile_export_aiperf.json"); + let export: Value = serde_json::from_slice(&std::fs::read(&path)?)?; + validate(&export, input.profile)?; + let phase_outcome = super::phase_outcome::parse( + &std::fs::read_to_string(input.output.join("upstream/logs/aiperf.log"))?, + count(&export, "request_count")?, + )?; + let memory: Value = + serde_json::from_slice(&std::fs::read(input.output.join("memory-summary.json"))?)?; + let completed_work = if matches!(input.profile, Profile::Comparison | Profile::Contention) { + let completed_work = super::completed_work::validate(input)?; + validate_output_numerator(&export, &completed_work)?; + Some(completed_work) + } else { + None + }; + let summary = json!({ + "name":format!("agentx/{}/{}/{}/c{}",input.model.key,engine,input.profile.label(),concurrency), + "engine":engine,"offered_sessions":concurrency, + "cohort":serde_json::from_slice::(&std::fs::read(input.output.join("cohort.json"))?)?, + "capacity_policy":super::capacity::policy(engine, input.profile), + "configured_capacity":super::capacity::read_configured(&input.output), + "native_capacity":super::capacity::read_verified(&input.output, engine, input.profile, concurrency)?, + "submission_valid":false,"request_count":metric(&export,"request_count")?, + "phase_outcome":phase_outcome, + "completed_work":completed_work, + "output_tok_s":metric(&export,"output_token_throughput")?, + "ttft":export["time_to_first_token"],"itl":export["inter_token_latency"],"e2e":export["request_latency"], + "errors":export["error_request_count"],"context_overflows":export["context_overflow_count"], + "usage_prompt_tokens":export["usage_prompt_tokens"],"usage_completion_tokens":export["usage_completion_tokens"], + "cache_read_tokens":export["usage_prompt_cache_read_tokens"], + "memory":memory,"observed_concurrency":super::overlap::read(&input.output), + "scheduler_profile":std::fs::read(input.output.join("scheduler-profile.json")).ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()), + "upstream_metadata":export["metadata"], + "export_sha256":crate::product::digest::file_sha256(&path).map_err(|failure|failure.error)? + }); + write(&input.output.join("summary.json"), &summary)?; + Ok(summary) +} +pub(super) fn archive(output: &Path) -> DynResult<()> { + let path = output.with_extension("tar.gz"); + let encoder = flate2::write::GzEncoder::new( + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?, + flate2::Compression::fast(), + ); + let mut archive = tar::Builder::new(encoder); + archive.follow_symlinks(false); + archive.append_dir_all("agentx", output)?; + archive.into_inner()?.finish()?; + let sha = crate::product::digest::file_sha256(&path).map_err(|e| e.error)?; + write( + &output.with_extension("archive.json"), + &json!({"archive":path.to_str().ok_or("archive path Unicode required")?,"sha256":sha}), + ) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn projects_real_export_without_averaging_token_totals_or_rescaling_ms() { + let export: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/agentx/smoke-metrics.json" + )) + .unwrap(); + validate(&export, Profile::Smoke).unwrap(); + let point = metric_point(&export, 1).unwrap(); + assert_eq!(point["requests_completed"], 4); + assert_eq!(point["tokens"]["input"], 263976); + assert_eq!(point["tokens"]["output"], 1236); + assert_eq!(point["ttft_ms"]["p"]["50"], 873.2040969999999); + assert_eq!(point["throughput"]["output_tok_s"], 20.599353189236243); + for (name, value) in [ + ("total_output_tokens", json!({"avg":1.5})), + ("total_usage_prompt_tokens", Value::Null), + ("time_to_first_token", json!({"avg":1,"unit":"sec"})), + ("benchmark_duration", json!({"avg":-1,"unit":"sec"})), + ] { + let mut invalid = export.clone(); + invalid[name] = value; + assert!(metric_point(&invalid, 1).is_err(), "{name}"); + } + } + fn export() -> Value { + json!({"metadata":{"submission_valid":false},"request_count":{"avg":2},"output_token_count":{"avg":8},"usage_prompt_tokens":{"avg":32},"usage_completion_tokens":{"avg":4},"time_to_first_token":{"avg":2},"inter_token_latency":{"avg":1},"warmup_metrics":{}}) + } + #[test] + fn explicit_comparison_is_local_and_requires_its_own_work_audit() { + let mut local = export(); + assert!(validate(&local, Profile::Comparison).is_err()); + assert!(validate(&local, Profile::Contention).is_err()); + local["metadata"] = Value::Null; + assert!(validate(&local, Profile::Comparison).is_ok()); + local["warmup_metrics"] = Value::Null; + assert!(validate(&local, Profile::Contention).is_ok()); + assert!(validate(&local, Profile::Smoke).is_err()); + local["metadata"] = json!({"submission_valid":true}); + assert!(validate(&local, Profile::Comparison).is_err()); + } + #[test] + fn rejects_empty_failed_and_cancelled_runs() { + assert!(validate(&export(), Profile::Smoke).is_ok()); + for (name, value) in [ + ("request_count", json!({"avg":0})), + ("error_request_count", json!({"avg":1})), + ("context_overflow_count", json!({"avg":1})), + ("was_cancelled", json!(true)), + ("inter_token_latency", Value::Null), + ("usage_completion_tokens", Value::Null), + ] { + let mut failed = export(); + failed[name] = value; + assert!(validate(&failed, Profile::Smoke).is_err(), "{name}"); + } + } + + #[test] + fn comparison_requires_throughput_numerator_to_match_completed_output() { + let mut export = json!({ + "total_output_tokens":{"avg":18_713}, + "total_osl":{"avg":18_713} + }); + let work = json!({"output_tokens":18_713}); + validate_output_numerator(&export, &work).unwrap(); + export["total_osl"]["avg"] = json!(18_714); + assert!(validate_output_numerator(&export, &work).is_err()); + export["total_osl"]["avg"] = json!(18_713); + export["total_output_tokens"]["avg"] = json!(18_712); + assert!(validate_output_numerator(&export, &work).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/scheduler_profile.rs b/tools/xtask/src/automation/agentx/scheduler_profile.rs new file mode 100644 index 0000000000..79fb17dfea --- /dev/null +++ b/tools/xtask/src/automation/agentx/scheduler_profile.rs @@ -0,0 +1,228 @@ +//! Content-free aggregates of serving scheduler debug timings. +use crate::process::{ObservedLine, Stream, retained::MemberId}; +use serde::Serialize; +use serde_json::Value; + +#[derive(Default, Serialize)] +struct Samples { + count: u64, + sum: f64, + max: f64, + at_least_10: u64, + at_least_100: u64, + at_least_1000: u64, +} + +impl Samples { + fn add(&mut self, value: f64) { + if !value.is_finite() || value < 0.0 { + return; + } + self.count += 1; + self.sum += value; + self.max = self.max.max(value); + self.at_least_10 += u64::from(value >= 10.0); + self.at_least_100 += u64::from(value >= 100.0); + self.at_least_1000 += u64::from(value >= 1000.0); + } +} + +#[derive(Default, Serialize)] +pub(super) struct SchedulerProfile { + schema_version: u8, + iterations: u64, + batch_size: Samples, + token_count: Samples, + batch_wait_max_ms: Samples, + runtime_lock_wait_ms: Samples, + runtime_lock_hold_ms: Samples, + planned_iterations: u64, + planned_decode_batches: PlannedDecodeBatches, + planned_running_sequences: Samples, + planned_waiting_sequences: Samples, + planned_decode_tokens: Samples, + planned_prefill_tokens: Samples, + planned_step_ms: Samples, + planned_execution_ms: Samples, + planned_overhead_ms: Samples, +} + +#[derive(Default, Serialize)] +struct PlannedDecodeBatches { + none: u64, + one: u64, + two: u64, + three: u64, + four_or_more: u64, +} + +impl PlannedDecodeBatches { + fn add(&mut self, count: u64) { + let bucket = match count { + 0 => &mut self.none, + 1 => &mut self.one, + 2 => &mut self.two, + 3 => &mut self.three, + _ => &mut self.four_or_more, + }; + *bucket += 1; + } +} + +enum SchedulerEvent { + Direct, + Planned, +} + +impl SchedulerProfile { + pub(super) fn new() -> Self { + Self { + schema_version: 2, + ..Self::default() + } + } + + pub(super) fn observe(&mut self, member: MemberId, line: &ObservedLine<'_>) { + if member != MemberId::Seed || line.stream != Stream::Stderr { + return; + } + let Some((event, attributes)) = parse(line.bytes) else { + return; + }; + match event { + SchedulerEvent::Direct => self.observe_direct(&attributes), + SchedulerEvent::Planned => self.observe_planned(&attributes), + } + } + + fn observe_direct(&mut self, attributes: &serde_json::Map) { + self.iterations += 1; + for (name, samples) in [ + ("skippy.scheduler.batch_size", &mut self.batch_size), + ("skippy.scheduler.token_count", &mut self.token_count), + ( + "skippy.scheduler.batch_wait_max_ms", + &mut self.batch_wait_max_ms, + ), + ( + "skippy.scheduler.runtime_lock_wait_ms", + &mut self.runtime_lock_wait_ms, + ), + ( + "skippy.scheduler.runtime_lock_hold_ms", + &mut self.runtime_lock_hold_ms, + ), + ] { + if let Some(value) = attributes.get(name).and_then(Value::as_f64) { + samples.add(value); + } + } + } + + fn observe_planned(&mut self, attributes: &serde_json::Map) { + self.planned_iterations += 1; + if let Some(count) = attributes + .get("skippy.scheduler.decode_tokens") + .and_then(Value::as_u64) + { + self.planned_decode_batches.add(count); + } + for (name, samples) in [ + ( + "skippy.scheduler.running", + &mut self.planned_running_sequences, + ), + ( + "skippy.scheduler.waiting", + &mut self.planned_waiting_sequences, + ), + ( + "skippy.scheduler.decode_tokens", + &mut self.planned_decode_tokens, + ), + ( + "skippy.scheduler.prefill_tokens", + &mut self.planned_prefill_tokens, + ), + ("skippy.scheduler.step_ms", &mut self.planned_step_ms), + ( + "skippy.scheduler.execution_ms", + &mut self.planned_execution_ms, + ), + ( + "skippy.scheduler.overhead_ms", + &mut self.planned_overhead_ms, + ), + ] { + if let Some(value) = attributes.get(name).and_then(Value::as_f64) { + samples.add(value); + } + } + } +} + +fn parse(line: &[u8]) -> Option<(SchedulerEvent, serde_json::Map)> { + if !line.starts_with(b"{\"event\":") { + return None; + } + let event: Value = serde_json::from_slice(line).ok()?; + let kind = match event["event"].as_str()? { + "stage.scheduler_feature_iteration" => SchedulerEvent::Direct, + "stage.scheduler_iteration" => SchedulerEvent::Planned, + _ => return None, + }; + Some((kind, event["attributes"].as_object()?.clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aggregates_only_allowlisted_numeric_scheduler_fields() { + let mut profile = SchedulerProfile::new(); + let raw = br#"{"event":"stage.scheduler_feature_iteration","attributes":{"skippy.scheduler.batch_size":4,"skippy.scheduler.token_count":512,"skippy.scheduler.batch_wait_max_ms":12.5,"skippy.scheduler.runtime_lock_wait_ms":101.0,"skippy.scheduler.runtime_lock_hold_ms":1001.0,"prompt":"secret"}}"#; + profile.observe( + MemberId::Seed, + &ObservedLine { + stream: Stream::Stderr, + bytes: raw, + ending: crate::process::LineEnding::Lf, + }, + ); + let value = serde_json::to_value(profile).unwrap(); + assert_eq!(value["iterations"], 1); + assert_eq!(value["batch_size"]["sum"], 4.0); + assert_eq!(value["runtime_lock_wait_ms"]["at_least_100"], 1); + assert_eq!(value["runtime_lock_hold_ms"]["at_least_1000"], 1); + assert!(!value.to_string().contains("secret")); + } + + #[test] + fn captures_planned_decode_occupancy_after_direct_prefill_handoff() { + let mut profile = SchedulerProfile::new(); + for (decode, execution) in [(0, 120.0), (1, 35.0), (4, 51.0)] { + let event = format!( + r#"{{"event":"stage.scheduler_iteration","attributes":{{"skippy.scheduler.running":4,"skippy.scheduler.waiting":1,"skippy.scheduler.decode_tokens":{decode},"skippy.scheduler.prefill_tokens":0,"skippy.scheduler.step_ms":{},"skippy.scheduler.execution_ms":{execution},"skippy.scheduler.overhead_ms":2.0,"prompt":"private content"}}}}"#, + execution + 2.0 + ); + profile.observe( + MemberId::Seed, + &ObservedLine { + stream: Stream::Stderr, + bytes: event.as_bytes(), + ending: crate::process::LineEnding::Lf, + }, + ); + } + let value = serde_json::to_value(profile).unwrap(); + assert_eq!(value["iterations"], 0); + assert_eq!(value["planned_iterations"], 3); + assert_eq!(value["planned_decode_batches"]["none"], 1); + assert_eq!(value["planned_decode_batches"]["one"], 1); + assert_eq!(value["planned_decode_batches"]["four_or_more"], 1); + assert_eq!(value["planned_decode_tokens"]["sum"], 5.0); + assert_eq!(value["planned_execution_ms"]["sum"], 206.0); + assert!(!value.to_string().contains("private content")); + } +} diff --git a/tools/xtask/src/automation/agentx/trace_context.rs b/tools/xtask/src/automation/agentx/trace_context.rs new file mode 100644 index 0000000000..34787eb428 --- /dev/null +++ b/tools/xtask/src/automation/agentx/trace_context.rs @@ -0,0 +1,168 @@ +//! Audit the whole-trace budget used by the pinned upstream Weka loader. +//! Selection itself remains owned by AgentX's --max-context-length option. +use super::{Prepared, Profile, write}; +use crate::command::DynResult; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +pub(super) const LIMIT: u64 = 131_072; + +pub(super) fn describe(trace: &Value, bytes: &[u8]) -> DynResult { + let peak = peak_context( + trace["requests"] + .as_array() + .ok_or("missing trace requests")?, + )?; + Ok(json!({ + "trace_id":trace["id"].as_str().ok_or("missing trace ID")?, + "trace_sha256":hex::encode(Sha256::digest(bytes)), + "recorded_peak_input_plus_output_tokens":peak, + "status":if peak <= LIMIT { "eligible" } else { "unsupported_context" }, + })) +} + +fn peak_context(requests: &[Value]) -> DynResult { + let mut peak = 0; + for request in requests { + let tokens = match request["type"].as_str() { + Some("subagent") => peak_context( + request["requests"] + .as_array() + .ok_or("missing child requests")?, + )?, + Some("n" | "s") => { + let input = request["in"].as_u64().ok_or("invalid input token count")?; + // AgentX emits at least one output token even for recorded out=0. + let output = request["out"] + .as_u64() + .ok_or("invalid output token count")? + .max(1); + input + .checked_add(output) + .ok_or("context token count overflow")? + } + _ => return Err("unknown Weka request type".into()), + }; + peak = peak.max(tokens); + } + Ok(peak) +} + +pub(super) fn record(input: &Prepared, concurrency: u32) -> DynResult { + let source = input + .dataset + .parent() + .ok_or("missing cohort parent")? + .join("cohort.json"); + let cohort: Value = serde_json::from_slice(&std::fs::read(source)?)?; + let traces = cohort["trace_context"] + .as_array() + .ok_or("missing trace context audit")?; + let selection = selection(traces, input.profile, concurrency)?; + write(&input.output.join("cohort.json"), &selection)?; + Ok(selection) +} + +fn selection(traces: &[Value], profile: Profile, concurrency: u32) -> DynResult { + let eligible: Vec<_> = traces + .iter() + .filter(|trace| trace["status"] == "eligible") + .collect(); + let limit = match profile { + Profile::Smoke => concurrency.max(4) as usize, + Profile::Contention => super::contention_cohort::SESSIONS, + _ => eligible.len(), + }; + if limit == 0 || eligible.len() < limit { + return Err("not enough complete context-compatible traces for offered concurrency".into()); + } + let selected = &eligible[..limit]; + // IDs plus original row digests make independent engine jobs comparable. + let digest = hex::encode(Sha256::digest(serde_json::to_vec(selected)?)); + Ok(json!({ + "harness_version":profile.harness_version(), + "policy":"common_whole_trace_recorded_input_plus_output", + "max_context_tokens":LIMIT, + "token_count_scope":"recorded_counts_not_rendered_chat_template_tokens", + "source_traces":traces.len(), + "eligible_traces":eligible.len(), + "excluded_unsupported_context_traces":traces.len()-eligible.len(), + "selected_traces":selected, + "selected_cohort_sha256":digest, + "exclusion_manifest":"../cohort.json", + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn includes_output_and_every_child_and_accepts_exact_boundary() { + for (requests, expected) in [ + (json!([{"type":"n","in":131071,"out":1}]), "eligible"), + ( + json!([{"type":"s","in":131071,"out":2}]), + "unsupported_context", + ), + ( + json!([{"type":"s","in":131072,"out":0}]), + "unsupported_context", + ), + ( + json!([{"type":"n","in":8,"out":2},{"type":"subagent","requests":[{"type":"s","in":131070,"out":3}]}]), + "unsupported_context", + ), + ] { + let trace = json!({"id":"trace","requests":requests}); + assert_eq!( + describe(&trace, b"unchanged row").unwrap()["status"], + expected + ); + } + } + + #[test] + fn malformed_counts_fail_closed() { + for request in [ + json!({"type":"n","in":-1,"out":2}), + json!({"type":"n","in":1,"out":1.5}), + json!({"type":"n","in":u64::MAX,"out":1}), + json!({"type":"subagent"}), + json!({"type":"unknown"}), + ] { + assert!(peak_context(&[request]).is_err()); + } + } + + #[test] + fn context_filter_precedes_smoke_cap_and_is_identical_across_concurrencies() { + let traces: Vec<_> = (0..8) + .map(|index| { + json!({ + "trace_id":index.to_string(), + "status":if index < 3 { "unsupported_context" } else { "eligible" }, + }) + }) + .collect(); + let first = selection(&traces, Profile::Smoke, 1).unwrap(); + assert_eq!(first["selected_traces"][0]["trace_id"], "3"); + assert_eq!(first["selected_traces"].as_array().unwrap().len(), 4); + assert_eq!(first["excluded_unsupported_context_traces"], 3); + for concurrency in [2, 4] { + assert_eq!( + first, + selection(&traces, Profile::Smoke, concurrency).unwrap() + ); + } + assert_eq!( + selection(&traces, Profile::Benchmark, 4).unwrap()["selected_traces"] + .as_array() + .unwrap() + .len(), + 5 + ); + assert!(selection(&traces[..6], Profile::Smoke, 4).is_err()); + assert!(selection(&[], Profile::Benchmark, 4).is_err()); + } +} diff --git a/tools/xtask/src/automation/agentx/workload.rs b/tools/xtask/src/automation/agentx/workload.rs new file mode 100644 index 0000000000..e563a31770 --- /dev/null +++ b/tools/xtask/src/automation/agentx/workload.rs @@ -0,0 +1,265 @@ +use super::{Prepared, Profile, command}; +use crate::command::DynResult; +use std::{ + path::Path, + time::{Duration, Instant}, +}; + +pub(super) fn arguments(input: &Prepared, port: u16, concurrency: u32) -> Vec { + if matches!(input.profile, Profile::Comparison | Profile::Contention) { + let name = if input.profile == Profile::Comparison { + "comparison-config.json" + } else { + "contention-config.json" + }; + return vec![ + "profile".into(), + "--config".into(), + input.output.join(name).to_string_lossy().into_owned(), + ]; + } + let mut args = command::strings(&[ + "profile", + "--url", + &format!("http://127.0.0.1:{port}"), + "--endpoint", + "/v1/chat/completions", + "--model", + &input.model.key, + "--tokenizer", + ]); + // Use the pinned host-cache tokenizer without contacting HF. + let cache = std::env::var_os("HF_HOME") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| input.root.join(".cache/huggingface")); + args.push( + cache + .join("hub") + .join(format!( + "models--{}", + input.model.tokenizer.replace('/', "--") + )) + .join("snapshots") + .join(&input.model.tokenizer_revision) + .to_string_lossy() + .into_owned(), + ); + args.extend(command::strings(&[ + "--tokenizer-revision", + &input.model.tokenizer_revision, + ])); + args.extend(command::strings(&[ + "--custom-dataset-type", + "weka_trace", + // Upstream drops whole traces before selecting the first N eligible + // entries, including parent and child input + requested output. + "--max-context-length", + &super::trace_context::LIMIT.to_string(), + "--input-file", + ])); + args.push(input.dataset.to_string_lossy().into()); + args.extend(command::strings(&[ + "--session-header", + "X-Session-ID", + "--random-seed", + "42", + "--concurrency", + &concurrency.to_string(), + "--unsafe-override", + "--export-level", + "records", + "--export-http-trace", + "--output-artifact-dir", + ])); + args.push(input.output.join("upstream").to_string_lossy().into()); + args.extend(command::strings(&["--benchmark-grace-period", "inf"])); + if input.profile == Profile::Smoke { + args.extend(command::strings(&[ + "--num-dataset-entries", + &concurrency.max(4).to_string(), + "--benchmark-duration", + "60", + "--warmup-requests-per-lane", + "1", + // Recorded first-request spacing can exceed the entire smoke + // window (81.4s in the pinned c4 cohort). Admit every lane at the + // phase boundary while preserving later inter-turn delays. + "--burst-phase-starts", + "--trajectory-start-min-ratio", + "0", + "--trajectory-start-max-ratio", + "0", + ])); + } + args +} +pub(super) fn run(input: &Prepared, port: u16, concurrency: u32) -> DynResult<()> { + ready(&input.root, port, &input.output)?; + match input.profile { + Profile::Comparison => super::write( + &input.output.join("comparison-config.json"), + &super::comparison_cohort::configuration(input, port, concurrency)?, + )?, + Profile::Contention => super::write( + &input.output.join("contention-config.json"), + &super::contention_cohort::configuration(input, port, concurrency)?, + )?, + _ => {} + } + // JY's macOS work directory exceeds sockaddr_un's 103-byte path limit + // after AgentX appends its temporary directory and ZMQ socket names. + // Own a short private directory until the supervised harness has stopped. + let ipc = ipc_directory()?; + let executable = input.tools.as_ref().map_or_else( + || input.root.join("skippy/evals/agentx/.venv/bin/agentx"), + |tools| tools.client.path.clone(), + ); + let mut spec = command::spec( + &input.root, + executable.to_str().ok_or("AgentX executable")?, + &arguments(input, port, concurrency), + )?; + // A 1.0.7 mmap cache hit can finish dataset configuration before record + // processors subscribe, leaving completed requests without exported metrics. + // Rebuild the dataset before measurement for both engines; keep HF weights. + spec.environment.insert( + "AIPERF_DATASET_MMAP_CACHE_ENABLED".into(), + crate::process::Value::Public("false".into()), + ); + if input.profile == Profile::Contention { + // The 16-process Weka reconstruction path spent minutes before + // dispatch on Apple Silicon. Serial reconstruction completed in + // seconds for this capped cohort and avoids competing with serving. + spec.environment.insert( + "AIPERF_DATASET_WEKA_PARALLEL_WORKERS".into(), + crate::process::Value::Public("1".into()), + ); + } + spec.environment.insert( + "TMPDIR".into(), + crate::process::Value::Public(ipc.path().as_os_str().to_owned()), + ); + command::run( + &spec, + if matches!(input.profile, Profile::Smoke | Profile::Contention) { + 3600 + } else { + 9000 + }, + &input.output.join("agentx"), + ) +} +fn ipc_directory() -> DynResult { + Ok(tempfile::Builder::new() + .prefix("agentx-") + .tempdir_in("/tmp")?) +} +fn ready(root: &Path, port: u16, output: &Path) -> DynResult<()> { + let spec = command::spec( + root, + "curl", + &command::strings(&[ + "--fail", + "--silent", + "--show-error", + "--max-time", + "5", + &format!("http://127.0.0.1:{port}/health"), + ]), + )?; + let seconds = super::lifecycle::STARTUP_TIMEOUT_SECS; + let deadline = Instant::now() + Duration::from_secs(seconds); + let mut attempt = 0; + while Instant::now() < deadline { + let log = output.join(format!("health-{attempt}")); + if command::run(&spec, 10, &log).is_ok() { + return Ok(()); + } + attempt += 1; + std::thread::sleep(Duration::from_secs(2)); + } + Err(format!("server never became healthy within {seconds}s").into()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[cfg(unix)] + #[test] + fn private_ipc_directory_fits_agentx_unix_socket_paths() { + let directory = ipc_directory().unwrap(); + let path = directory.path().to_owned(); + let socket = path.join("tmp01234567/aiperf/event_bus_proxy_frontend.ipc"); + assert!(socket.as_os_str().as_encoded_bytes().len() < 103); + std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); + let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap(); + drop(listener); + drop(directory); + assert!(!path.exists()); + } + + #[test] + fn smoke_changes_workload_size_without_shortening_context_or_outputs() { + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let mut input = Prepared { + tools: None, + root: "/repo".into(), + output: "/results".into(), + weights: "/weights/model.gguf".into(), + dataset: "/traces".into(), + model: models[1].clone(), + profile: Profile::Smoke, + }; + let smoke = arguments(&input, 8080, 1); + for pair in [ + ["--benchmark-duration", "60"], + ["--num-dataset-entries", "4"], + ["--warmup-requests-per-lane", "1"], + ["--trajectory-start-min-ratio", "0"], + ] { + assert!(smoke.windows(2).any(|args| args == pair)); + } + assert!(!smoke.iter().any(|arg| arg == "--synthesis-max-isl" + || arg == "--synthesis-max-osl" + || arg == "--output-tokens")); + assert!( + smoke + .windows(2) + .any(|args| args == ["--max-context-length", "131072"]) + ); + assert!(smoke.iter().any(|arg| arg == "--burst-phase-starts")); + let wide = arguments(&input, 8080, 128); + assert!( + wide.windows(2) + .any(|args| args == ["--num-dataset-entries", "128"]) + ); + assert!(wide.windows(2).any(|args| args == ["--concurrency", "128"])); + assert!( + wide.windows(2) + .any(|args| args == ["--benchmark-grace-period", "inf"]) + ); + input.profile = Profile::Benchmark; + + let full = arguments(&input, 8080, 8); + assert!(!full.iter().any(|arg| matches!( + arg.as_str(), + "--benchmark-duration" | "--num-dataset-entries" | "--burst-phase-starts" + ))); + assert!(full.windows(2).any(|args| args == ["--concurrency", "8"])); + assert!( + full.windows(2) + .any(|args| args == ["--max-context-length", "131072"]) + ); + input.profile = Profile::Contention; + for concurrency in [4, 8, 16] { + let diagnostic = arguments(&input, 8080, concurrency); + assert_eq!( + diagnostic, + ["profile", "--config", "/results/contention-config.json"] + ); + } + } +} diff --git a/tools/xtask/src/automation/mod.rs b/tools/xtask/src/automation/mod.rs index 37b883b9e0..18fc253f9c 100644 --- a/tools/xtask/src/automation/mod.rs +++ b/tools/xtask/src/automation/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod agent_fixture_evidence; pub(crate) mod agent_fixture_inputs; pub(crate) mod agent_model; pub(crate) mod agentic_prompt_manifest; +pub(crate) mod agentx; pub(crate) mod binary_stage_readiness; pub(crate) mod cache_family_cell; pub(crate) mod cache_family_correctness; diff --git a/tools/xtask/src/cli.rs b/tools/xtask/src/cli.rs index 00047cf5f9..3117d6956f 100644 --- a/tools/xtask/src/cli.rs +++ b/tools/xtask/src/cli.rs @@ -109,6 +109,7 @@ pub(crate) struct Cli<'a> { pub(crate) enum CliCommand<'a> { KvValidation(&'a [String]), + Agentx(&'a [String]), MtpScheduler(&'a [String]), MtpSchedulerWorker(&'a [String]), SuffixProposer(&'a [String]), @@ -309,6 +310,9 @@ impl<'a> Cli<'a> { [domain, scope, rest @ ..] if domain == "automation" && scope == "kv-validation" => { CliCommand::KvValidation(rest) } + [domain, scope, rest @ ..] if domain == "automation" && scope == "agentx" => { + CliCommand::Agentx(rest) + } [domain, scope, rest @ ..] if domain == "automation" && scope == "cache-family-run" => { CliCommand::CacheFamilyRun(rest) } diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs index ebf1ca3a56..8442785149 100644 --- a/tools/xtask/src/main.rs +++ b/tools/xtask/src/main.rs @@ -53,6 +53,7 @@ fn run() -> DynResult<()> { .transpose()?; match parsed.command { cli::CliCommand::KvValidation(rest) => automation::kv_validation::run(rest), + cli::CliCommand::Agentx(rest) => automation::agentx::run(rest), cli::CliCommand::EndpointModelDiscovery(rest) => { automation::endpoint_model_discovery::run(rest) } diff --git a/tools/xtask/tests/fixtures/agentx/complete-trace-records.jsonl b/tools/xtask/tests/fixtures/agentx/complete-trace-records.jsonl new file mode 100644 index 0000000000..b5962097ec --- /dev/null +++ b/tools/xtask/tests/fixtures/agentx/complete-trace-records.jsonl @@ -0,0 +1,16 @@ +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-2","source_outer_idx":0,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":8,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-3","source_outer_idx":0,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":8,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-1","source_outer_idx":0,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":8,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-a","source_outer_idx":0,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":8,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-2","source_outer_idx":1,"source_inner_idx":0,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":3,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-3","source_outer_idx":1,"source_inner_idx":0,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":3,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-1","source_outer_idx":1,"source_inner_idx":0,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":3,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-a","source_outer_idx":1,"source_inner_idx":0,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":3,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-2","source_outer_idx":1,"source_inner_idx":1,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":4,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-3","source_outer_idx":1,"source_inner_idx":1,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":4,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-1","source_outer_idx":1,"source_inner_idx":1,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":4,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-a","source_outer_idx":1,"source_inner_idx":1,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":4,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-2","source_outer_idx":2,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":5,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-3","source_outer_idx":2,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":5,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-1","source_outer_idx":2,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":5,"unit":"tokens"}},"error":null} +{"metadata":{"benchmark_phase":"profiling","source_trace_id":"fixture-a","source_outer_idx":2,"source_inner_idx":null,"was_cancelled":false,"context_overflow_skip":false},"metrics":{"output_token_count":{"value":5,"unit":"tokens"}},"error":null} diff --git a/tools/xtask/tests/fixtures/agentx/http-overlap.jsonl b/tools/xtask/tests/fixtures/agentx/http-overlap.jsonl new file mode 100644 index 0000000000..b18777cfa3 --- /dev/null +++ b/tools/xtask/tests/fixtures/agentx/http-overlap.jsonl @@ -0,0 +1,7 @@ +{"metadata":{"benchmark_phase":"warmup"},"trace_data":{"request_send_start_ns":1792418963533980712,"response_receive_end_ns":1792418963742353121}} +{"metadata":{"benchmark_phase":"warmup"},"trace_data":{"request_send_start_ns":1792418963538394598,"response_receive_end_ns":1792418963952754593}} +{"metadata":{"benchmark_phase":"warmup"},"trace_data":{"request_send_start_ns":1792418963543063794,"response_receive_end_ns":1792418964162859507}} +{"metadata":{"benchmark_phase":"warmup"},"trace_data":{"request_send_start_ns":1792418963536341455,"response_receive_end_ns":1792418991697525017}} +{"metadata":{"benchmark_phase":"profiling"},"trace_data":{"request_send_start_ns":1792418991761966031,"response_receive_end_ns":1792419064375353124}} +{"metadata":{"benchmark_phase":"profiling"},"trace_data":{"request_send_start_ns":1792418992673094438,"response_receive_end_ns":1792419068398475393}} +{"metadata":{"benchmark_phase":"profiling"},"trace_data":{"request_send_start_ns":1792418991907700007,"response_receive_end_ns":1792419074310227604}} diff --git a/tools/xtask/tests/fixtures/agentx/smoke-metrics.json b/tools/xtask/tests/fixtures/agentx/smoke-metrics.json new file mode 100644 index 0000000000..03fb47849e --- /dev/null +++ b/tools/xtask/tests/fixtures/agentx/smoke-metrics.json @@ -0,0 +1,139 @@ +{ + "metadata": { + "scenario": "agentx", + "submission_valid": false, + "submission_invalid_reasons": [ + "unsafe_override" + ] + }, + "was_cancelled": false, + "warmup_metrics": {}, + "request_count": { + "unit": "requests", + "avg": 4.0 + }, + "output_token_count": { + "unit": "tokens", + "avg": 309.0, + "p1": 257.24, + "p5": 258.2, + "p10": 259.4, + "p25": 263.0, + "p50": 292.0, + "p75": 338.0, + "p90": 372.20000000000005, + "p95": 383.59999999999997, + "p99": 392.71999999999997, + "min": 257.0, + "max": 395.0, + "std": 55.08175741568164, + "count": 4, + "sum": 1236.0 + }, + "usage_prompt_tokens": { + "unit": "tokens", + "avg": 65994.0, + "p1": 63776.22, + "p5": 63977.1, + "p10": 64228.2, + "p25": 64981.5, + "p50": 66138.5, + "p75": 67151.0, + "p90": 67644.2, + "p95": 67808.6, + "p99": 67940.12, + "min": 63726.0, + "max": 67973.0, + "std": 1596.307457853906, + "count": 4, + "sum": 263976.0 + }, + "usage_completion_tokens": { + "unit": "tokens", + "avg": 309.0, + "p1": 257.24, + "p5": 258.2, + "p10": 259.4, + "p25": 263.0, + "p50": 292.0, + "p75": 338.0, + "p90": 372.20000000000005, + "p95": 383.59999999999997, + "p99": 392.71999999999997, + "min": 257.0, + "max": 395.0, + "std": 55.08175741568164, + "count": 4, + "sum": 1236.0 + }, + "benchmark_duration": { + "unit": "sec", + "avg": 59.16004224 + }, + "output_token_throughput": { + "unit": "tokens/sec", + "avg": 20.599353189236243 + }, + "total_usage_prompt_tokens": { + "unit": "tokens", + "avg": 263976.0 + }, + "total_output_tokens": { + "unit": "tokens", + "avg": 1236.0 + }, + "time_to_first_token": { + "unit": "ms", + "avg": 5258.603724, + "p1": 642.6898356099999, + "p5": 661.5067700499999, + "p10": 685.0279381, + "p25": 755.59144225, + "p50": 873.2040969999999, + "p75": 5376.216378749999, + "p90": 13340.499211500004, + "p95": 15995.260155749993, + "p99": 18119.068911149992, + "min": 637.985602, + "max": 18650.021099999998, + "std": 7732.333532363163, + "count": 4, + "sum": 21034.414896 + }, + "inter_token_latency": { + "unit": "ms", + "avg": 24.907246940049827, + "p1": 24.565975348816913, + "p5": 24.61049427707949, + "p10": 24.666142937407706, + "p25": 24.833088918392363, + "p50": 24.95918544436553, + "p75": 25.033343466022995, + "p90": 25.106800139239386, + "p95": 25.131285696978185, + "p99": 25.15087414316922, + "min": 24.55484561675127, + "max": 25.15577125471698, + "std": 0.21998325136590122, + "count": 4, + "sum": 99.62898776019931 + }, + "request_latency": { + "unit": "ms", + "avg": 12921.76724225, + "p1": 7350.46888239, + "p5": 7353.53016795, + "p10": 7357.356774899999, + "p25": 7368.83659575, + "p50": 8006.3675674999995, + "p75": 13559.298213999999, + "p90": 22418.4974494, + "p95": 25371.563861199993, + "p99": 27734.016990639993, + "min": 7349.703560999999, + "max": 28324.630273, + "std": 8908.073586595576, + "count": 4, + "sum": 51687.068969 + } +} From 31a0eb8a628eb000a3d83e387e3cfa078dd08893 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 20:32:10 +1100 Subject: [PATCH 15/81] fix(skippy): enable resident prefix reuse with one lane --- skippy/docs/CONFIGURATION.md | 2 +- ...ippy-define-graph-derived-native-ABI.patch | 4 +- ...ize-admitted-stages-from-live-graphs.patch | 29 +++++++--- ...cover-live-graph-and-state-contracts.patch | 56 +++++++++++++++++++ 4 files changed, 79 insertions(+), 12 deletions(-) diff --git a/skippy/docs/CONFIGURATION.md b/skippy/docs/CONFIGURATION.md index 2b73e00f67..ae13bf98d4 100644 --- a/skippy/docs/CONFIGURATION.md +++ b/skippy/docs/CONFIGURATION.md @@ -83,7 +83,7 @@ website configuration reference, with the same `Wiring status`. | 5.1 | KV cache K dtype | `model_fit.cache_type_k` | P0 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig | single-stage, staged | restart/reload only | package-validated publisher KV declaration, then compute dtype, then F16 | enum value accepted by embedded llama runtime; explicit value wins | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-host-runtime/src/plugin/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | explicit K cache dtype override | wired | | 5.1 | KV cache V dtype | `model_fit.cache_type_v` | P0 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig | single-stage, staged | restart/reload only | package-validated publisher KV declaration, then compute dtype, then F16 | enum value accepted by embedded llama runtime; explicit value wins | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-host-runtime/src/plugin/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | explicit V cache dtype override | wired | | 5.1 | KV offload | `model_fit.kv_offload` | P1 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig, native `skippy_runtime_config.kv_offload` tri-state | single-stage, staged | restart/reload only | backend runtime default | boolean or auto; auto preserves llama.cpp's derived `offload_kqv` default | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-host-runtime/src/plugin/config.rs`; capture tests in `skippy/crates/skippy-runtime/src/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | controls KV residency and offload policy | wired | -| 5.1 | Unified KV cache | `model_fit.kv_unified` | P1 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig, native `skippy_runtime_config.kv_unified` tri-state | single-stage, staged | restart/reload only | derived from lane count | auto derives from lane count; true and false override it (recurrent/hybrid models force true and multi-lane activation exports require true) | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-config/src/model_validation.rs` and `skippy/crates/skippy-runtime/src/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | KV layout selection preserved from v0.78.0 | wired | +| 5.1 | Unified KV cache | `model_fit.kv_unified` | P1 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig, native `skippy_runtime_config.kv_unified` tri-state | single-stage, staged | restart/reload only | unified, including one lane | auto selects unified KV; true and false override it (recurrent/hybrid models force true and multi-lane activation exports require true). Explicit non-unified attention contexts do not advertise resident-prefix caching. | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-config/src/model_validation.rs` and `skippy/crates/skippy-runtime/src/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | One-lane defaults support cache-owned sequence IDs | wired | | 5.1 | Cache RAM budget | `model_fit.cache_ram_mib` | P1 | `plugin/config.rs`, `skippy-serving`, `skippy-cache` | `StageKvCacheConfig.l2_max_bytes` and bounded host-RAM L2 exact-state tier | single-stage, staged | restart/reload only | disabled by default | integer >= 0 MiB; zero or unset disables L2; positive values require prefix caching and active L3 | `#model-fit-context-and-kv-cache` | resolver propagation tests in `mesh/crates/mesh-llm-host-runtime/src/inference/skippy/resolver/tests.rs`; promotion and admission tests in `skippy-serving` and `skippy-cache`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | repeated or high-value L3 fills promote to L2; L2 hits restore before disk and asynchronously rewarm L1 | wired | | 5.1 | Cache idle slots | `model_fit.cache_idle_slots` | P1 | `plugin/config.rs` | SkippyModelLoadOptions, StageConfig, `skippy-serving::RuntimeState::max_idle_sessions` idle-pool bound | single-stage, staged | restart/reload only | runtime default (unbounded, capped only by `lane_count`) | integer >= 0; bounds the idle session pool size | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-host-runtime/src/plugin/config.rs`; `skippy/crates/skippy-serving/src/runtime_state.rs` and `skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs` unit tests; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | bounds retained idle sessions so `drop_session_timed` discards lanes past the configured cap instead of growing the pool unbounded | wired | | 5.1 | Prompt cache / cache prompt | `model_fit.prompt_cache` | P1 | `plugin/config.rs` | cache config or request adapter defaults when executable | single-stage, staged | restart/reload only | disabled unless operator enables reuse | boolean only; reject when selected runtime does not expose prompt-cache behavior | `#model-fit-context-and-kv-cache` | `plugin::config` tests in `mesh/crates/mesh-llm-host-runtime/src/plugin/config.rs`; parity: `website_docs_parity` in `mesh/crates/mesh-llm-config/src/website_docs_parity.rs` | request prompt reuse toggle | wired | diff --git a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch index a988945550..76e684da11 100644 --- a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch +++ b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch @@ -1055,7 +1055,7 @@ index 000000000..5d77f4804 +#endif // SKIPPY_MODEL_SOURCE_H diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h new file mode 100644 -index 000000000..799bdca2d +index 000000000..b47c55f82 --- /dev/null +++ b/include/skippy/runtime.h @@ -0,0 +1,277 @@ @@ -1157,7 +1157,7 @@ index 000000000..799bdca2d + // Tri-state KV/session controls resolved from `model_fit` config. + /** @brief Whether K/V tensors are offloaded to the compute backend (mirrors upstream `offload_kqv`). */ + int32_t kv_offload; -+ /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO derives the setting from lane count; recurrent and hybrid models force it true. */ ++ /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO enables unified caching at every lane count. Explicit false selects non-unified caching, except recurrent and hybrid models force it true. */ + int32_t kv_unified; + /** @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`). */ + int32_t swa_full; diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 7eb2a5d724..99f31feee8 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -50,7 +50,7 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/model_lifecycle.cpp | 155 +++ src/skippy/model_load_config.cpp | 213 ++++ src/skippy/model_load_config_internal.h | 35 + - src/skippy/model_loading.cpp | 1188 +++++++++++++++++++++++ + src/skippy/model_loading.cpp | 1189 +++++++++++++++++++++++ src/skippy/model_loading_internal.h | 38 + src/skippy/model_package.cpp | 782 +++++++++++++++ src/skippy/model_source.cpp | 463 +++++++++ @@ -77,7 +77,7 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/state.cpp | 1189 +++++++++++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ - src/skippy/state_memory.cpp | 115 +++ + src/skippy/state_memory.cpp | 125 +++ src/skippy/state_memory.h | 16 + src/skippy/tokenization.cpp | 179 ++++ src/skippy/verification.cpp | 256 +++++ @@ -7922,10 +7922,10 @@ index 000000000..554d2bdd3 +skippy_context_capabilities skippy_context_capabilities_of(const llama_model * model); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp new file mode 100644 -index 000000000..b82ec9aca +index 000000000..d6e24cd2a --- /dev/null +++ b/src/skippy/model_loading.cpp -@@ -0,0 +1,1188 @@ +@@ -0,0 +1,1189 @@ +#include "skippy.h" +#include "skippy/errors.h" +#include "skippy/environment.h" @@ -8620,7 +8620,8 @@ index 000000000..b82ec9aca + params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : params.n_threads; + params.n_seq_max = stage_model->lane_count; -+ params.kv_unified = stage_model->lane_count > 1; ++ // Cache-owned sequence IDs share the attention pool even with one lane. ++ params.kv_unified = true; + if (config != nullptr) { + params.kv_unified = skippy_resolve_tristate(config->kv_unified, params.kv_unified); + params.offload_kqv = skippy_resolve_tristate(config->kv_offload, params.offload_kqv); @@ -9088,7 +9089,7 @@ index 000000000..b82ec9aca + ctx_params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + ctx_params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : ctx_params.n_threads; + ctx_params.n_seq_max = target_model->lane_count; -+ ctx_params.kv_unified = target_model->lane_count > 1; ++ ctx_params.kv_unified = true; + if (config != nullptr) { + ctx_params.kv_unified = skippy_resolve_tristate(config->kv_unified, ctx_params.kv_unified); + ctx_params.offload_kqv = skippy_resolve_tristate(config->kv_offload, ctx_params.offload_kqv); @@ -16930,10 +16931,10 @@ index 000000000..5bb6b779b + std::string & error); diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp new file mode 100644 -index 000000000..2d7b1a2ae +index 000000000..806e79d72 --- /dev/null +++ b/src/skippy/state_memory.cpp -@@ -0,0 +1,115 @@ +@@ -0,0 +1,125 @@ +#include "skippy/state_memory.h" +#include "skippy/state.h" +#include "skippy/runtime_types.h" @@ -17044,10 +17045,20 @@ index 000000000..2d7b1a2ae +} + +extern "C" uint32_t skippy_model_memory_cache_capabilities(const skippy_model * model) { -+ return model && model->ctx ++ uint32_t capabilities = model && model->ctx + ? model->ctx->admit_skippy_cache_capabilities( + skippy_memory_cache_capabilities(model->ctx->get_memory())) + : 0; ++ // Explicit non-unified attention contexts cannot admit the resident API. ++ // Preserve their complete export representations, but never advertise ++ // cache ownership that resident_prefix::validate_session will refuse. ++ if (model && model->ctx && !model->ctx->get_cparams().kv_unified ++ && (capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION)) { ++ capabilities &= ~(SKIPPY_MEMORY_CACHE_RESIDENT ++ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION ++ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); ++ } ++ return capabilities; +} diff --git a/src/skippy/state_memory.h b/src/skippy/state_memory.h new file mode 100644 diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 25c7342fc2..600332cf3f 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -6844,6 +6844,59 @@ index 000000000..9e134586f + release(session); +} + ++void dense_resident_configuration(const char * path, skippy_runtime_config config) { ++ config.lane_count = 1; ++ config.kv_unified = SKIPPY_TRISTATE_AUTO; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ ok(skippy_model_open(path, &config, &model, &error), error); ++ CHECK(model->ctx->get_cparams().kv_unified); ++ CHECK(skippy_model_memory_cache_capabilities(model) & SKIPPY_MEMORY_CACHE_RESIDENT); ++ constexpr int32_t cache_id = 8; ++ const std::vector tokens(16, 1); ++ auto * source = create(model); ++ prefill(source, tokens); ++ const auto page = export_page(source, tokens.size()); ++ error = nullptr; ++ ok(skippy_session_save_prefix(source, cache_id, tokens.size(), &error), error); ++ const auto expected = decode_logits(source, 2); ++ release(source); ++ skippy_session * restored = nullptr; ++ error = nullptr; ++ ok(skippy_session_create_from_resident_prefix(model, cache_id, ++ tokens.data(), tokens.size(), &restored, &error), error); ++ CHECK(export_page(restored, tokens.size()) == page); ++ CHECK(decode_logits(restored, 2) == expected); ++ release(restored); ++ error = nullptr; ++ ok(skippy_model_free(model, &error), error); ++ ++ // Explicit overrides remain supported, but must not claim resident APIs ++ // that reject this context. Cover both one stream and real multi-stream. ++ for (const uint32_t lanes : {1u, 2u}) { ++ config.lane_count = lanes; ++ config.kv_unified = SKIPPY_TRISTATE_FALSE; ++ model = nullptr; ++ error = nullptr; ++ ok(skippy_model_open(path, &config, &model, &error), error); ++ CHECK(!model->ctx->get_cparams().kv_unified); ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(!(capabilities & (SKIPPY_MEMORY_CACHE_RESIDENT ++ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION ++ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT))); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_KV_RECURRENT); ++ source = create(model); ++ prefill(source, tokens); ++ error = nullptr; ++ CHECK(skippy_session_save_prefix(source, cache_id, tokens.size(), &error) ++ == SKIPPY_STATUS_UNSUPPORTED); ++ skippy_error_free(error); ++ release(source); ++ error = nullptr; ++ ok(skippy_model_free(model, &error), error); ++ } ++} ++ +} // namespace + +int main(int argc, char ** argv) { @@ -6910,6 +6963,9 @@ index 000000000..9e134586f + error = nullptr; + const auto freed = skippy_model_free(model, &error); + ok(freed, error); ++ if (resident && !require_recurrent) { ++ dense_resident_configuration(argv[1], config); ++ } + return 0; +} diff --git a/src/skippy/tests/stage_plan_header.c b/src/skippy/tests/stage_plan_header.c From 83a052ff616e3db992b070bb742802bff0df9bcf Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 31 Oct 2026 21:02:02 +1100 Subject: [PATCH 16/81] fix(bench): bind offline AgentX tokenizers to pinned snapshots --- skippy/evals/agentx/README.md | 7 ++ .../src/automation/agentx/agentic_config.rs | 83 +++++++++++++++---- tools/xtask/src/automation/agentx/command.rs | 4 + .../automation/agentx/comparison_cohort.rs | 4 + .../src/automation/agentx/final_sweep.rs | 4 + tools/xtask/src/automation/agentx/workload.rs | 18 +--- 6 files changed, 88 insertions(+), 32 deletions(-) diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 6b4aef0eb2..6180e4819e 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -27,6 +27,13 @@ runtime, tokenizer snapshot and corpus. External directory links/editable environments are refused; internal aliases such as `lib64 -> lib` are pinned without traversal, and regular-file interpreter links are hashed by content. +Place the tokenizer snapshot in its pinned Hugging Face cache layout and set +`HF_HUB_CACHE` (or `HF_HOME`) to that cache before pinning and running. The +offline client receives the catalog's repository ID and exact revision; pinning +requires that its resolved snapshot is the same canonical directory as +`tools.tokenizer.path`. The child receives that cache path explicitly, so it +cannot silently consume a different snapshot from the operator's home cache. + Create `/abs/request.paths.json` with: ```json diff --git a/tools/xtask/src/automation/agentx/agentic_config.rs b/tools/xtask/src/automation/agentx/agentic_config.rs index 4b0850b066..ed1b9d4b1d 100644 --- a/tools/xtask/src/automation/agentx/agentic_config.rs +++ b/tools/xtask/src/automation/agentx/agentic_config.rs @@ -2,6 +2,37 @@ use super::{Prepared, trace_context}; use crate::command::DynResult; use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +pub(super) fn tokenizer_hub_cache(root: &Path) -> PathBuf { + let cache = std::env::var_os("HF_HUB_CACHE").map_or_else( + || { + std::env::var_os("HF_HOME") + .map_or_else(|| root.join(".cache/huggingface"), PathBuf::from) + .join("hub") + }, + PathBuf::from, + ); + if cache.is_absolute() { + cache + } else { + root.join(cache) + } +} + +pub(super) fn tokenizer_snapshot(root: &Path, model: &super::Model) -> PathBuf { + tokenizer_hub_cache(root) + .join(format!("models--{}", model.tokenizer.replace('/', "--"))) + .join("snapshots") + .join(&model.tokenizer_revision) +} + +pub(super) fn verify_tokenizer_snapshot(pinned: &Path, resolved: &Path) -> DynResult<()> { + if pinned.canonicalize()? != resolved.canonicalize()? { + return Err("offline tokenizer cache must resolve to the exact pinned snapshot".into()); + } + Ok(()) +} pub(super) fn configuration( input: &Prepared, @@ -10,21 +41,12 @@ pub(super) fn configuration( sessions: usize, namespace_label: &str, ) -> DynResult { - let cache = std::env::var_os("HF_HOME") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| input.root.join(".cache/huggingface")); - let tokenizer = cache - .join("hub") - .join(format!( - "models--{}", - input.model.tokenizer.replace('/', "--") - )) - .join("snapshots") - .join(&input.model.tokenizer_revision); - let tokenizer = input - .tools - .as_ref() - .map_or(tokenizer, |tools| tools.tokenizer.path.clone()); + if let Some(tools) = &input.tools { + verify_tokenizer_snapshot( + &tools.tokenizer.path, + &tokenizer_snapshot(&input.root, &input.model), + )?; + } let cohort = input .dataset .parent() @@ -40,7 +62,9 @@ pub(super) fn configuration( "endpoint":{"url":format!("http://127.0.0.1:{port}/v1/chat/completions"), "type":"chat","streaming":true,"timeout":1800, "use_server_token_count":true,"session_header":"X-Session-ID","extra":{"ignore_eos":true}}, - "tokenizer":{"name":tokenizer,"revision":input.model.tokenizer_revision}, + // The locked offline client resolves repository IDs through the HF cache; + // passing an absolute snapshot path triggers its repo-ID validation. + "tokenizer":{"name":input.model.tokenizer,"revision":input.model.tokenizer_revision}, "dataset":{"type":"file","path":input.dataset,"format":"weka_trace", "sampling":"sequential","entries":sessions,"max_context_length":trace_context::LIMIT, "ignore_trace_delays":false,"use_think_time_only":true, @@ -54,3 +78,30 @@ pub(super) fn configuration( "records":["jsonl"],"trace":true},"gpu_telemetry":{"enabled":false} }})) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn offline_resolution_rejects_a_different_or_missing_pinned_snapshot() { + let root = tempfile::tempdir().unwrap(); + let pinned = root.path().join("pinned"); + let other = root.path().join("other"); + std::fs::create_dir(&pinned).unwrap(); + std::fs::create_dir(&other).unwrap(); + verify_tokenizer_snapshot(&pinned, &pinned).unwrap(); + assert!(verify_tokenizer_snapshot(&pinned, &other).is_err()); + assert!(verify_tokenizer_snapshot(&pinned, &root.path().join("missing")).is_err()); + } + + #[test] + fn child_uses_the_same_explicit_cache_as_snapshot_admission() { + let root = tempfile::tempdir().unwrap(); + let spec = super::super::command::spec(root.path(), "true", &[]).unwrap(); + assert!( + matches!(spec.environment.get(std::ffi::OsStr::new("HF_HUB_CACHE")), + Some(crate::process::Value::Public(path)) if path == tokenizer_hub_cache(root.path()).as_os_str()) + ); + } +} diff --git a/tools/xtask/src/automation/agentx/command.rs b/tools/xtask/src/automation/agentx/command.rs index cd7e7cb130..19682868f6 100644 --- a/tools/xtask/src/automation/agentx/command.rs +++ b/tools/xtask/src/automation/agentx/command.rs @@ -38,6 +38,10 @@ pub(super) fn spec(root: &Path, executable: &str, args: &[String]) -> DynResult< .collect(); environment.insert("PYTHONDONTWRITEBYTECODE".into(), Value::Public("1".into())); environment.insert("HF_HUB_OFFLINE".into(), Value::Public("1".into())); + environment.insert( + "HF_HUB_CACHE".into(), + Value::Public(super::agentic_config::tokenizer_hub_cache(root).into_os_string()), + ); Ok(ProcessSpec { executable: self::executable(executable)?, arguments: args.iter().map(|arg| Value::Public(arg.into())).collect(), diff --git a/tools/xtask/src/automation/agentx/comparison_cohort.rs b/tools/xtask/src/automation/agentx/comparison_cohort.rs index 7d08fdddb3..ae5c42c725 100644 --- a/tools/xtask/src/automation/agentx/comparison_cohort.rs +++ b/tools/xtask/src/automation/agentx/comparison_cohort.rs @@ -139,6 +139,10 @@ mod tests { for concurrency in [1, 2, 4] { let config = configuration(&input, 8080, concurrency).unwrap(); let benchmark = &config["benchmark"]; + assert_eq!( + benchmark["tokenizer"], + json!({"name": input.model.tokenizer, "revision": input.model.tokenizer_revision}) + ); assert_eq!(benchmark["dataset"]["cache_bust"]["namespace"], namespace); assert!(benchmark["scenario"].is_null()); assert_eq!( diff --git a/tools/xtask/src/automation/agentx/final_sweep.rs b/tools/xtask/src/automation/agentx/final_sweep.rs index 3eedb23c42..3a96dc8e6a 100644 --- a/tools/xtask/src/automation/agentx/final_sweep.rs +++ b/tools/xtask/src/automation/agentx/final_sweep.rs @@ -58,6 +58,10 @@ impl Request { let model = inputs::select_model(&self.workspace, &self.model_key)?; inputs::verify(&self.model, &model.files[0].sha256)?; self.tools.verify(&self.workspace)?; + super::agentic_config::verify_tokenizer_snapshot( + &self.tools.tokenizer.path, + &super::agentic_config::tokenizer_snapshot(&self.workspace, &model), + )?; Ok(model) } } diff --git a/tools/xtask/src/automation/agentx/workload.rs b/tools/xtask/src/automation/agentx/workload.rs index e563a31770..96f3500c05 100644 --- a/tools/xtask/src/automation/agentx/workload.rs +++ b/tools/xtask/src/automation/agentx/workload.rs @@ -28,22 +28,8 @@ pub(super) fn arguments(input: &Prepared, port: u16, concurrency: u32) -> Vec Date: Sat, 31 Oct 2026 21:19:13 +1100 Subject: [PATCH 17/81] fix(bench): parse structured output independently of diagnostic redaction --- skippy/evals/agentx/README.md | 3 + tools/xtask/src/automation/agentx/command.rs | 63 ++++++++++++++++++- .../src/automation/agentx/mlflow_publish.rs | 10 +-- .../src/automation/agentx/prepared_launch.rs | 13 ++-- 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 6180e4819e..9574241284 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -68,6 +68,9 @@ capacity observations, raw client records/HTTP traces, lifecycle/memory/work receipts, scalar summaries, final result and a sibling archive+SHA receipt. Failure retains partial evidence and returns nonzero. Clean process-tree shutdown is required; no partial campaign becomes a successful point. +Doctor, effective-config and MLflow JSON are parsed from bounded structured +capture, independently of redacted diagnostic logs. Public evidence projections +remain available even when ordinary logs suppress a line containing `token`. ## Capacity and backend policy diff --git a/tools/xtask/src/automation/agentx/command.rs b/tools/xtask/src/automation/agentx/command.rs index 19682868f6..55568d46df 100644 --- a/tools/xtask/src/automation/agentx/command.rs +++ b/tools/xtask/src/automation/agentx/command.rs @@ -60,6 +60,39 @@ pub(super) fn limits(seconds: u64) -> process::Limits { } } pub(super) fn run(spec: &ProcessSpec, seconds: u64, log: &Path) -> DynResult<()> { + capture(spec, seconds, log, None).map(|_| ()) +} + +/// Parse trusted public CLI/API JSON without interpreting redacted diagnostics +/// as machine data. Raw bytes remain bounded in memory and are never logged. +pub(super) fn public_json( + spec: &ProcessSpec, + seconds: u64, + log: &Path, +) -> DynResult { + let report = capture( + spec, + seconds, + log, + std::num::NonZeroUsize::new(4 * 1024 * 1024), + )?; + let bytes = report + .stdout + .as_ref() + .ok_or("public JSON capture absent")? + .as_bytes(); + if bytes.iter().all(u8::is_ascii_whitespace) { + return Ok(serde_json::Value::Null); + } + Ok(serde_json::from_slice(bytes)?) +} + +fn capture( + spec: &ProcessSpec, + seconds: u64, + log: &Path, + stdout: Option, +) -> DynResult { let interrupt = crate::automation::command_interrupt::Interrupt::install()?; let result = process::supervise_raw_with_files( spec, @@ -70,7 +103,7 @@ pub(super) fn run(spec: &ProcessSpec, seconds: u64, log: &Path) -> DynResult<()> stderr: Some(log.with_extension("stderr.log")), }, process::RawCaptureOptions { - stdout: None, + stdout, stderr: None, }, ); @@ -85,8 +118,34 @@ pub(super) fn run(spec: &ProcessSpec, seconds: u64, log: &Path) -> DynResult<()> ) .into()); } - Ok(()) + Ok(report) } pub(super) fn strings(args: &[&str]) -> Vec { args.iter().map(|arg| (*arg).into()).collect() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn structured_public_json_survives_redaction_without_disabling_log_redaction() { + let root = tempfile::tempdir().unwrap(); + let log = root.path().join("public-json"); + let spec = spec( + root.path(), + "sh", + &strings(&[ + "-c", + r#"printf '%s' '{"context_tokens":8,"model_cache":"/models/tokenizer"}'"#, + ]), + ) + .unwrap(); + let value = public_json(&spec, 10, &log).unwrap(); + assert_eq!(value["context_tokens"], 8); + assert_eq!(value["model_cache"], "/models/tokenizer"); + let diagnostic = std::fs::read_to_string(log.with_extension("stdout.log")).unwrap(); + assert!(diagnostic.contains("[output line suppressed]")); + assert!(!diagnostic.contains("/models/tokenizer")); + } +} diff --git a/tools/xtask/src/automation/agentx/mlflow_publish.rs b/tools/xtask/src/automation/agentx/mlflow_publish.rs index 4980d86b18..d3574e4e0a 100644 --- a/tools/xtask/src/automation/agentx/mlflow_publish.rs +++ b/tools/xtask/src/automation/agentx/mlflow_publish.rs @@ -95,15 +95,7 @@ impl Client { ]); } let spec = command::spec(&self.output, "curl", &args)?; - command::run(&spec, 140, &self.output.join(&label))?; - let bytes = crate::automation::receipt_files::bounded( - &self.output.join(format!("{label}.stdout.log")), - 4 * 1024 * 1024, - )?; - if bytes.iter().all(u8::is_ascii_whitespace) { - return Ok(Value::Null); - } - Ok(serde_json::from_slice(&bytes)?) + command::public_json(&spec, 140, &self.output.join(&label)) } fn api(&mut self, operation: &str, body: &Value) -> DynResult { self.request( diff --git a/tools/xtask/src/automation/agentx/prepared_launch.rs b/tools/xtask/src/automation/agentx/prepared_launch.rs index f0b802fe45..842134ad63 100644 --- a/tools/xtask/src/automation/agentx/prepared_launch.rs +++ b/tools/xtask/src/automation/agentx/prepared_launch.rs @@ -57,8 +57,7 @@ pub(super) fn doctor( "doctor".into(), ], )?; - command::run(&spec, 120, &output.join("doctor"))?; - let value: Value = serde_json::from_slice(&std::fs::read(output.join("doctor.stdout.log"))?)?; + let value = command::public_json(&spec, 120, &output.join("doctor"))?; if value["native_runtime"]["path"].as_str() != tools.runtime.path.to_str() || value .get("runtime_issue") @@ -66,7 +65,10 @@ pub(super) fn doctor( { return Err("doctor must select the exact prepared runtime leaf without issue".into()); } - Ok(()) + write( + &output.join("doctor.json"), + &json!({"native_runtime_path":value["native_runtime"]["path"],"runtime_issue":value["runtime_issue"]}), + ) } pub(super) fn effective_config(input: &Prepared, server: &process::ProcessSpec) -> DynResult<()> { @@ -86,10 +88,7 @@ pub(super) fn effective_config(input: &Prepared, server: &process::ProcessSpec) probe .arguments .push(process::Value::Public("--print-effective-config".into())); - command::run(&probe, 900, &input.output.join("effective-config"))?; - let value: Value = serde_json::from_slice(&std::fs::read( - input.output.join("effective-config.stdout.log"), - )?)?; + let value = command::public_json(&probe, 900, &input.output.join("effective-config"))?; validate_config( &value, input From 58dbff85239f84478be29c3119a8f3a18c838541 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 03:31:43 +1100 Subject: [PATCH 18/81] fix(skippy): admit queued requests until their actual deadline --- skippy/crates/skippy-serving/README.md | 8 +- .../skippy-serving/src/frontend/backend.rs | 7 +- .../src/frontend/backend/tests.rs | 897 +--------------- .../src/frontend/backend/tests/admission.rs | 966 ++++++++++++++++++ .../src/frontend/generation/queue.rs | 58 +- 5 files changed, 987 insertions(+), 949 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs diff --git a/skippy/crates/skippy-serving/README.md b/skippy/crates/skippy-serving/README.md index e22ebe2c03..b8211634b1 100644 --- a/skippy/crates/skippy-serving/README.md +++ b/skippy/crates/skippy-serving/README.md @@ -188,10 +188,10 @@ deadline handling. at once and defaults to the config's KV-derived `lane_count`. `--generation-queue-capacity` independently bounds additional waiting requests (default `clamp(8 * lanes, 16, 256)`), while - `--generation-admission-timeout-secs` can bound predicted and actual queue - wait; the default `0` waits until client cancellation so capacity pressure - drains through the bounded queue instead of rejecting accepted work. KV - restore and prefill-record work runs on a separate + `--generation-admission-timeout-secs` bounds actual queue wait. Predicted wait + remains advisory telemetry; the default `0` waits until client cancellation + so capacity pressure drains through the bounded queue instead of rejecting + accepted work. KV restore and prefill-record work runs on a separate prompt-scaled deadline: admission timeout plus about one minute per 4,000 prompt tokens, clamped to at least 60 seconds and at most 30 minutes. A legitimate prompt-sized prefill is therefore not killed by the queue-wait diff --git a/skippy/crates/skippy-serving/src/frontend/backend.rs b/skippy/crates/skippy-serving/src/frontend/backend.rs index 73501cb732..1bf7edaf8c 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend.rs @@ -578,12 +578,7 @@ impl GenerationAdmissionController { self.generation_service_estimator .set_concurrency(self.generation_limit.current_limit()); let predicted_wait_ms = self.generation_service_estimator.predicted_wait_ms(); - let queued_work = self - .generation_service_estimator - .reserve_queued(work, admission_timeout) - .map_err(|predicted_wait_ms| { - generation_predicted_wait_error(predicted_wait_ms, admission_timeout) - })?; + let queued_work = self.generation_service_estimator.reserve_queued(work); let resources = lease .acquire( self.generation_limit.semaphore(), diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs index 6fbc0f4e54..b3f04c0137 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs @@ -1,8 +1,9 @@ +mod admission; + use super::*; use crate::frontend::EmbeddedOpenAiRequestDefaults; use crate::frontend::SpeculativeDecodeConfig; use crate::frontend::admission::GenerationTokenBudget; -use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS; use crate::frontend::generation::InferenceBackendMode; use crate::frontend::iteration_scheduler::IterationScheduler; use crate::frontend::prefill::PrefillChunkPolicy; @@ -42,900 +43,6 @@ fn test_telemetry() -> crate::telemetry::Telemetry { crate::telemetry::Telemetry::new(None, 1, config, crate::telemetry::TelemetryLevel::Off) } -fn trusted_ids(session_id: &str) -> InferenceGenerationIds { - InferenceGenerationIds::new_with_trust( - InferenceCacheHints::default(), - Some(session_id), - true, - None, - ) -} - -fn trusted_session_key(session_id: &str) -> String { - trusted_generation_session_key(&trusted_ids(session_id)).expect("trusted session key") -} - -fn admission_controller( - generation_concurrency: usize, - generation_queue_limit: usize, -) -> GenerationAdmissionController { - admission_controller_with_budget(generation_concurrency, generation_queue_limit, 4_096) -} - -fn admission_controller_with_budget( - generation_concurrency: usize, - generation_queue_limit: usize, - token_capacity: usize, -) -> GenerationAdmissionController { - GenerationAdmissionController { - generation_limit: Arc::new(GenerationConcurrencyController::fixed( - generation_concurrency, - )), - generation_queue_depth: Arc::new(AtomicUsize::new(0)), - generation_queue_limit, - generation_service_estimator: Arc::new(GenerationServiceEstimator::new( - generation_concurrency, - )), - generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())), - generation_token_budget: Arc::new(GenerationTokenBudget::new(token_capacity)), - } -} - -fn result_error(result: InferenceResult) -> InferenceError { - match result { - Ok(_) => panic!("expected generation admission to fail"), - Err(error) => error, - } -} - -#[tokio::test] -async fn queued_admission_balances_shared_prefix_families_across_lane_wave() { - let controller = admission_controller(1, 4); - let work = GenerationAdmissionWork::new(4, 1); - let active = controller - .acquire_work( - &trusted_ids("active"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_secs(2), - work, - ) - .await - .expect("active request admission"); - let (tx, mut rx) = tokio::sync::mpsc::channel(4); - for (label, prompt) in [ - ("family-a-1", vec![1, 1, 3, 4]), - ("family-a-2", vec![1, 1, 3, 5]), - ("family-b-1", vec![2, 2, 3, 4]), - ("family-b-2", vec![2, 2, 3, 5]), - ] { - let controller = controller.clone(); - let tx = tx.clone(); - tokio::spawn(async move { - let cancellation = skippy_inference_api::CancellationToken::new(); - let admitted = controller - .acquire_scheduled_work( - &trusted_ids(label), - &cancellation, - Duration::from_secs(2), - work, - GenerationAdmissionScheduling::new( - Arc::from(prompt), - Arc::new(skippy_scheduler::CacheAffinity::default), - ), - ) - .await - .expect("queued request admission"); - tx.send((label, admitted)).await.unwrap(); - }); - } - drop(tx); - tokio::time::timeout(Duration::from_secs(1), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 4 { - tokio::task::yield_now().await; - } - }) - .await - .expect("all prompts become scheduler-visible"); - - drop(active); - let (first_label, first) = tokio::time::timeout(Duration::from_millis(250), rx.recv()) - .await - .expect("first queued admission was promoted") - .expect("first queued admission"); - drop(first); - let (second_label, second) = rx.recv().await.expect("second queued admission"); - assert_ne!( - first_label.split('-').nth(1), - second_label.split('-').nth(1), - "one family must not drain the whole lane wave" - ); - drop(second); - let (_, third) = rx.recv().await.expect("third queued admission"); - drop(third); - let (_, fourth) = rx.recv().await.expect("fourth queued admission"); - drop(fourth); -} - -#[tokio::test] -async fn capacity_waiter_holds_neither_a_lane_nor_kv_until_atomic_promotion() { - let controller = admission_controller_with_budget(2, 2, 10); - let active = controller - .acquire_work( - &trusted_ids("active"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - GenerationAdmissionWork::new(7, 0), - ) - .await - .expect("first capacity reservation"); - let waiting_controller = controller.clone(); - let waiter = tokio::spawn(async move { - waiting_controller - .acquire_work( - &trusted_ids("waiting"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - GenerationAdmissionWork::new(7, 0), - ) - .await - }); - - tokio::time::timeout(Duration::from_millis(100), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { - tokio::task::yield_now().await; - } - }) - .await - .expect("capacity waiter entered the queue"); - assert_eq!(controller.generation_limit.available_permits(), 1); - assert_eq!(controller.generation_token_budget.active_tokens(), 7); - - drop(active); - let promoted = tokio::time::timeout(Duration::from_millis(100), waiter) - .await - .expect("capacity waiter promoted") - .expect("capacity waiter task completed") - .expect("capacity waiter admission"); - assert_eq!(controller.generation_limit.available_permits(), 1); - assert_eq!(controller.generation_token_budget.active_tokens(), 7); - drop(promoted); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert_eq!(controller.generation_token_budget.active_tokens(), 0); -} - -#[tokio::test] -async fn capacity_waiters_drain_serially_after_each_kv_release() { - let controller = admission_controller_with_budget(2, 4, 10); - let active = controller - .acquire_work( - &trusted_ids("active"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - GenerationAdmissionWork::new(10, 0), - ) - .await - .expect("active capacity reservation"); - let (tx, mut rx) = tokio::sync::mpsc::channel(4); - for index in 0..4 { - let controller = controller.clone(); - let tx = tx.clone(); - tokio::spawn(async move { - let cancellation = skippy_inference_api::CancellationToken::new(); - let admitted = controller - .acquire_work( - &trusted_ids(&format!("waiting-{index}")), - &cancellation, - Duration::ZERO, - GenerationAdmissionWork::new(10, 0), - ) - .await - .expect("queued capacity admission"); - tx.send(admitted).await.unwrap(); - }); - } - drop(tx); - tokio::time::timeout(Duration::from_secs(1), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 4 { - tokio::task::yield_now().await; - } - }) - .await - .expect("all capacity waiters entered the queue"); - - drop(active); - for _ in 0..4 { - let admitted = tokio::time::timeout(Duration::from_secs(1), rx.recv()) - .await - .expect("next capacity waiter promoted") - .expect("queued capacity admission"); - assert_eq!(controller.generation_token_budget.active_tokens(), 10); - drop(admitted); - } - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert_eq!(controller.generation_token_budget.active_tokens(), 0); -} - -#[tokio::test] -async fn full_pool_waiter_is_admitted_after_bounded_half_pool_bypasses() { - let controller = admission_controller_with_budget(2, 4, 10); - let half_pool_work = GenerationAdmissionWork::new(5, 0); - let full_pool_work = GenerationAdmissionWork::new(10, 0); - let active = controller - .acquire_work( - &trusted_ids("active-half-pool"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - half_pool_work, - ) - .await - .expect("initial half-pool admission"); - - let full_pool_controller = controller.clone(); - let full_pool_waiter = tokio::spawn(async move { - full_pool_controller - .acquire_work( - &trusted_ids("full-pool-waiter"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - full_pool_work, - ) - .await - }); - tokio::time::timeout(Duration::from_secs(1), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { - tokio::task::yield_now().await; - } - }) - .await - .expect("full-pool request entered the queue"); - - // Keep one half-pool reservation active and repeatedly fill/release the - // other half. The full-pool request cannot fit during these admissions. - for wave in 0..ADMISSION_STARVATION_BOUND_TURNS { - let bypass = tokio::time::timeout( - Duration::from_secs(1), - controller.acquire_work( - &trusted_ids(&format!("half-pool-bypass-{wave}")), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - half_pool_work, - ), - ) - .await - .expect("fitting half-pool request completed before the timeout") - .expect("fitting half-pool request admitted before the bound"); - assert_eq!(controller.generation_token_budget.active_tokens(), 10); - drop(bypass); - } - - // The next fitting arrival reaches the bound and must remain queued while - // the controller drains capacity toward the older full-pool request. - let bypass_controller = controller.clone(); - let blocked_bypass = tokio::spawn(async move { - bypass_controller - .acquire_work( - &trusted_ids("half-pool-after-bound"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - half_pool_work, - ) - .await - }); - tokio::time::timeout(Duration::from_secs(1), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 2 { - tokio::task::yield_now().await; - } - }) - .await - .expect("post-bound half-pool request remained queued"); - assert!(!full_pool_waiter.is_finished()); - assert!(!blocked_bypass.is_finished()); - - drop(active); - let admitted_full_pool = tokio::time::timeout(Duration::from_secs(1), full_pool_waiter) - .await - .expect("full-pool waiter admitted after capacity drained") - .expect("full-pool waiter task completed") - .expect("full-pool admission succeeded"); - assert_eq!(controller.generation_token_budget.active_tokens(), 10); - assert!(!blocked_bypass.is_finished()); - - drop(admitted_full_pool); - let admitted_bypass = tokio::time::timeout(Duration::from_secs(1), blocked_bypass) - .await - .expect("younger half-pool waiter admitted after the senior completed") - .expect("half-pool waiter task completed") - .expect("half-pool admission succeeded"); - drop(admitted_bypass); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert_eq!(controller.generation_token_budget.active_tokens(), 0); -} - -#[tokio::test] -async fn request_larger_than_the_kv_pool_fails_without_queueing_or_taking_a_lane() { - let controller = admission_controller_with_budget(2, 2, 128); - let error = result_error( - controller - .acquire_work( - &trusted_ids("too-large"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - GenerationAdmissionWork::new(129, 0), - ) - .await, - ); - - assert_eq!(error.status(), axum::http::StatusCode::BAD_REQUEST); - assert_eq!( - error.body().error.code.as_deref(), - Some("context_length_exceeded") - ); - assert!( - error - .body() - .error - .message - .contains("runtime pool holds 128") - ); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert_eq!(controller.generation_token_budget.active_tokens(), 0); -} - -#[tokio::test] -async fn cancelling_a_capacity_waiter_leaks_neither_lane_nor_kv_reservation() { - let controller = admission_controller_with_budget(2, 2, 128); - let active = controller - .acquire_work( - &trusted_ids("active"), - &skippy_inference_api::CancellationToken::new(), - Duration::ZERO, - GenerationAdmissionWork::new(100, 0), - ) - .await - .expect("first capacity reservation"); - let cancellation = skippy_inference_api::CancellationToken::new(); - let waiter_cancellation = cancellation.clone(); - let waiting_controller = controller.clone(); - let waiter = tokio::spawn(async move { - waiting_controller - .acquire_work( - &trusted_ids("waiting"), - &waiter_cancellation, - Duration::ZERO, - GenerationAdmissionWork::new(64, 0), - ) - .await - }); - tokio::time::timeout(Duration::from_millis(100), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { - tokio::task::yield_now().await; - } - }) - .await - .expect("capacity waiter entered the queue"); - - cancellation.cancel(); - let error = result_error( - tokio::time::timeout(Duration::from_millis(100), waiter) - .await - .expect("cancelled capacity waiter returned") - .expect("capacity waiter task completed"), - ); - assert!(error.body().error.message.contains("request cancelled")); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - assert_eq!(controller.generation_limit.available_permits(), 1); - assert_eq!(controller.generation_token_budget.active_tokens(), 100); - - drop(active); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert_eq!(controller.generation_token_budget.active_tokens(), 0); -} - -#[tokio::test] -async fn predicted_wait_rejection_preserves_queue_capacity() { - let controller = admission_controller(1, 2); - let work = GenerationAdmissionWork::new(100, 100); - controller - .generation_service_estimator - .observe_completed(work, 100.0, 100.0); - let active = controller - .acquire_work( - &trusted_ids("agent-1"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_secs(1), - work, - ) - .await - .expect("active request admission"); - - let error = result_error( - controller - .acquire_work( - &trusted_ids("agent-2"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_millis(199), - work, - ) - .await, - ); - - assert!( - error - .body() - .error - .message - .contains("predicted generation wait") - ); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - drop(active); - assert_eq!(controller.generation_limit.available_permits(), 1); -} - -#[test] -fn session_registry_counts_live_leases_and_cleans_replaced_entries() { - let registry = Arc::new(Mutex::new(BTreeMap::new())); - let first = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) - .expect("first session lease"); - let second = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) - .expect("second session lease"); - - { - let locks = registry.lock().expect("session registry lock"); - let entry = locks.get("agent-1").expect("shared session entry"); - assert_eq!(entry.users.load(Ordering::Acquire), 2); - } - - drop(first); - { - let locks = registry.lock().expect("session registry lock"); - let entry = locks.get("agent-1").expect("live session entry"); - assert_eq!(entry.users.load(Ordering::Acquire), 1); - } - - drop(second); - assert!(registry.lock().expect("session registry lock").is_empty()); - - let replacement = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) - .expect("replacement session lease"); - assert_eq!(registry.lock().expect("session registry lock").len(), 1); - drop(replacement); - assert!(registry.lock().expect("session registry lock").is_empty()); -} - -#[tokio::test] -async fn same_trusted_session_serializes_without_consuming_global_queue_capacity() { - let controller = admission_controller(1, 1); - let session_key = trusted_session_key("agent-1"); - let first_cancellation = skippy_inference_api::CancellationToken::new(); - let first = controller - .acquire( - &trusted_ids("agent-1"), - &first_cancellation, - Duration::from_secs(1), - ) - .await - .expect("first session admission"); - - let second_controller = controller.clone(); - let second_cancellation = skippy_inference_api::CancellationToken::new(); - let waiter_cancellation = second_cancellation.clone(); - let waiter = tokio::spawn(async move { - second_controller - .acquire( - &trusted_ids("agent-1"), - &waiter_cancellation, - Duration::from_secs(1), - ) - .await - }); - - tokio::time::timeout(Duration::from_millis(100), async { - loop { - let users = controller - .generation_session_locks - .lock() - .expect("session registry lock") - .get(&session_key) - .map_or(0, |entry| entry.users.load(Ordering::Acquire)); - if users == 2 { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("second turn registered its session wait"); - - assert!(!waiter.is_finished()); - assert_eq!( - controller.generation_queue_depth.load(Ordering::Acquire), - 0, - "session contention must not consume global queue capacity" - ); - - second_cancellation.cancel(); - let error = result_error( - tokio::time::timeout(Duration::from_millis(100), waiter) - .await - .expect("cancelled session waiter returned") - .expect("session waiter task completed"), - ); - assert!(error.body().error.message.contains("request cancelled")); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - - drop(first); - assert_eq!(controller.generation_limit.available_permits(), 1); - assert!( - controller - .generation_session_locks - .lock() - .expect("session registry lock") - .is_empty() - ); -} - -#[tokio::test] -async fn same_trusted_session_acquires_only_after_the_first_turn_releases() { - let controller = admission_controller(1, 1); - let first_cancellation = skippy_inference_api::CancellationToken::new(); - let first = controller - .acquire( - &trusted_ids("agent-1"), - &first_cancellation, - Duration::from_secs(1), - ) - .await - .expect("first session admission"); - - let second_controller = controller.clone(); - let second = tokio::spawn(async move { - second_controller - .acquire( - &trusted_ids("agent-1"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_secs(1), - ) - .await - }); - - tokio::time::sleep(Duration::from_millis(5)).await; - assert!(!second.is_finished()); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - - drop(first); - let second = tokio::time::timeout(Duration::from_millis(100), second) - .await - .expect("second turn acquired after first released") - .expect("second turn task completed") - .expect("second session admission"); - assert_eq!(controller.generation_limit.available_permits(), 0); - drop(second); - assert_eq!(controller.generation_limit.available_permits(), 1); -} - -#[tokio::test] -async fn session_and_global_admission_share_one_absolute_deadline() { - let controller = admission_controller(1, 1); - let first_cancellation = skippy_inference_api::CancellationToken::new(); - let (global_permit, session_permit) = controller - .acquire( - &trusted_ids("agent-1"), - &first_cancellation, - Duration::from_secs(1), - ) - .await - .expect("first session admission"); - let session_permit = session_permit.expect("trusted session permit"); - let release_session = tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(140)).await; - drop(session_permit); - }); - let started = Instant::now(); - - let error = result_error( - controller - .acquire( - &trusted_ids("agent-1"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_millis(200), - ) - .await, - ); - - assert!(error.body().error.message.contains("timed out waiting")); - assert!( - started.elapsed() < Duration::from_millis(300), - "global-lane waiting must not restart the request admission timeout" - ); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - release_session - .await - .expect("session release task completed"); - drop(global_permit); -} - -#[tokio::test] -async fn unrelated_session_is_not_starved_by_a_same_session_waiter() { - let controller = admission_controller(2, 2); - let session_key = trusted_session_key("agent-1"); - let first_cancellation = skippy_inference_api::CancellationToken::new(); - let first = controller - .acquire( - &trusted_ids("agent-1"), - &first_cancellation, - Duration::from_secs(1), - ) - .await - .expect("first session admission"); - - let duplicate_controller = controller.clone(); - let duplicate_cancellation = skippy_inference_api::CancellationToken::new(); - let waiter_cancellation = duplicate_cancellation.clone(); - let duplicate = tokio::spawn(async move { - duplicate_controller - .acquire( - &trusted_ids("agent-1"), - &waiter_cancellation, - Duration::from_secs(1), - ) - .await - }); - - tokio::time::timeout(Duration::from_millis(100), async { - loop { - let users = controller - .generation_session_locks - .lock() - .expect("session registry lock") - .get(&session_key) - .map_or(0, |entry| entry.users.load(Ordering::Acquire)); - if users == 2 { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("duplicate turn registered its session wait"); - - assert_eq!(controller.generation_limit.available_permits(), 1); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - - let unrelated = controller - .acquire( - &trusted_ids("agent-2"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_millis(100), - ) - .await - .expect("unrelated session used the free global lane"); - assert_eq!(controller.generation_limit.available_permits(), 0); - assert!(!duplicate.is_finished()); - - duplicate_cancellation.cancel(); - let duplicate_error = result_error( - tokio::time::timeout(Duration::from_millis(100), duplicate) - .await - .expect("duplicate waiter cancelled") - .expect("duplicate waiter task completed"), - ); - assert!( - duplicate_error - .body() - .error - .message - .contains("request cancelled") - ); - drop((first, unrelated)); - assert_eq!(controller.generation_limit.available_permits(), 2); -} - -#[tokio::test] -async fn same_session_waiter_does_not_reserve_the_only_global_queue_slot() { - let controller = admission_controller(1, 1); - let session_key = trusted_session_key("agent-1"); - let first = controller - .acquire( - &trusted_ids("agent-1"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_secs(1), - ) - .await - .expect("first session admission"); - - let duplicate_controller = controller.clone(); - let duplicate_cancellation = skippy_inference_api::CancellationToken::new(); - let waiter_cancellation = duplicate_cancellation.clone(); - let duplicate = tokio::spawn(async move { - duplicate_controller - .acquire( - &trusted_ids("agent-1"), - &waiter_cancellation, - Duration::from_secs(1), - ) - .await - }); - tokio::time::timeout(Duration::from_millis(100), async { - loop { - let users = controller - .generation_session_locks - .lock() - .expect("session registry lock") - .get(&session_key) - .map_or(0, |entry| entry.users.load(Ordering::Acquire)); - if users == 2 { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("duplicate turn registered its session wait"); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - - let unrelated_controller = controller.clone(); - let unrelated = tokio::spawn(async move { - unrelated_controller - .acquire( - &trusted_ids("agent-2"), - &skippy_inference_api::CancellationToken::new(), - Duration::from_secs(1), - ) - .await - }); - tokio::time::timeout(Duration::from_millis(100), async { - while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { - tokio::task::yield_now().await; - } - }) - .await - .expect("unrelated turn reserved the only global queue slot"); - assert!(!unrelated.is_finished()); - - duplicate_cancellation.cancel(); - let duplicate_error = result_error( - tokio::time::timeout(Duration::from_millis(100), duplicate) - .await - .expect("duplicate waiter cancelled") - .expect("duplicate waiter task completed"), - ); - assert_eq!(duplicate_error.status().as_u16(), 499); - - drop(first); - let unrelated = tokio::time::timeout(Duration::from_millis(100), unrelated) - .await - .expect("unrelated turn acquired the released lane") - .expect("unrelated waiter task completed") - .expect("unrelated session admission"); - assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); - drop(unrelated); -} - -#[tokio::test] -async fn different_trusted_sessions_can_hold_generation_lanes_concurrently() { - let controller = admission_controller(2, 2); - let first_cancellation = skippy_inference_api::CancellationToken::new(); - let second_cancellation = skippy_inference_api::CancellationToken::new(); - let first_ids = trusted_ids("agent-1"); - let second_ids = trusted_ids("agent-2"); - - let (first, second) = tokio::join!( - controller.acquire(&first_ids, &first_cancellation, Duration::from_secs(1)), - controller.acquire(&second_ids, &second_cancellation, Duration::from_secs(1)), - ); - let first = first.expect("first session admission"); - let second = second.expect("second session admission"); - - assert_eq!(controller.generation_limit.available_permits(), 0); - assert_eq!( - controller - .generation_session_locks - .lock() - .expect("session registry lock") - .len(), - 2 - ); - - drop((first, second)); - assert_eq!(controller.generation_limit.available_permits(), 2); - assert!( - controller - .generation_session_locks - .lock() - .expect("session registry lock") - .is_empty() - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn blocking_worker_holds_global_and_session_permits_until_work_finishes() { - let controller = admission_controller(1, 1); - let session_key = trusted_session_key("agent-1"); - let cancellation = skippy_inference_api::CancellationToken::new(); - let (global_permit, session_permit) = controller - .acquire( - &trusted_ids("agent-1"), - &cancellation, - Duration::from_secs(1), - ) - .await - .expect("worker admission"); - let worker_context = InferenceRequestContext::new(); - let worker_started = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let release_worker = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let started = worker_started.clone(); - let release = release_worker.clone(); - - let worker = tokio::spawn(run_blocking_generation_worker( - global_permit, - worker_context, - move |_| { - let _session_permit = session_permit; - started.store(true, Ordering::Release); - while !release.load(Ordering::Acquire) { - std::thread::yield_now(); - } - }, - )); - - tokio::time::timeout(Duration::from_millis(100), async { - while !worker_started.load(Ordering::Acquire) { - tokio::task::yield_now().await; - } - }) - .await - .expect("blocking generation worker started"); - - assert_eq!(controller.generation_limit.available_permits(), 0); - let entry = controller - .generation_session_locks - .lock() - .expect("session registry lock") - .get(&session_key) - .expect("worker retains session entry") - .semaphore - .clone(); - assert_eq!(entry.available_permits(), 0); - - release_worker.store(true, Ordering::Release); - tokio::time::timeout(Duration::from_millis(100), worker) - .await - .expect("blocking generation worker completed") - .expect("worker task completed") - .expect("blocking worker joined"); - assert_eq!(controller.generation_limit.available_permits(), 1); - assert!( - controller - .generation_session_locks - .lock() - .expect("session registry lock") - .is_empty() - ); -} - -#[test] -fn untrusted_conversation_affinity_bypasses_session_registry() { - let registry = Arc::new(Mutex::new(BTreeMap::new())); - let untrusted = InferenceGenerationIds::new_with_trust( - InferenceCacheHints::default(), - Some("conversation-7"), - false, - None, - ); - assert!(trusted_generation_session_key(&untrusted).is_none()); - assert!(registry.lock().expect("session registry lock").is_empty()); - - let trusted = trusted_ids("agent-7"); - let key = trusted_generation_session_key(&trusted).expect("trusted session key"); - assert_eq!(key, trusted.session_id_string()); - let _permit = - GenerationSessionPermit::new(registry.clone(), key).expect("trusted session lease"); - assert_eq!(registry.lock().expect("session registry lock").len(), 1); -} - #[test] fn direct_backend_calls_ignore_spoofed_request_trust_metadata() { let request: GenerationRequest = serde_json::from_value::(json!({ diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs new file mode 100644 index 0000000000..d702b919a2 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs @@ -0,0 +1,966 @@ +//! Queue, resource and trusted-session admission contracts. +use super::*; +use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS; + +fn trusted_ids(session_id: &str) -> InferenceGenerationIds { + InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some(session_id), + true, + None, + ) +} + +fn trusted_session_key(session_id: &str) -> String { + trusted_generation_session_key(&trusted_ids(session_id)).expect("trusted session key") +} + +fn admission_controller( + generation_concurrency: usize, + generation_queue_limit: usize, +) -> GenerationAdmissionController { + admission_controller_with_budget(generation_concurrency, generation_queue_limit, 4_096) +} + +fn admission_controller_with_budget( + generation_concurrency: usize, + generation_queue_limit: usize, + token_capacity: usize, +) -> GenerationAdmissionController { + GenerationAdmissionController { + generation_limit: Arc::new(GenerationConcurrencyController::fixed( + generation_concurrency, + )), + generation_queue_depth: Arc::new(AtomicUsize::new(0)), + generation_queue_limit, + generation_service_estimator: Arc::new(GenerationServiceEstimator::new( + generation_concurrency, + )), + generation_session_locks: Arc::new(Mutex::new(BTreeMap::new())), + generation_token_budget: Arc::new(GenerationTokenBudget::new(token_capacity)), + } +} + +fn result_error(result: InferenceResult) -> InferenceError { + match result { + Ok(_) => panic!("expected generation admission to fail"), + Err(error) => error, + } +} + +#[tokio::test] +async fn queued_admission_balances_shared_prefix_families_across_lane_wave() { + let controller = admission_controller(1, 4); + let work = GenerationAdmissionWork::new(4, 1); + let active = controller + .acquire_work( + &trusted_ids("active"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(2), + work, + ) + .await + .expect("active request admission"); + let (tx, mut rx) = tokio::sync::mpsc::channel(4); + for (label, prompt) in [ + ("family-a-1", vec![1, 1, 3, 4]), + ("family-a-2", vec![1, 1, 3, 5]), + ("family-b-1", vec![2, 2, 3, 4]), + ("family-b-2", vec![2, 2, 3, 5]), + ] { + let controller = controller.clone(); + let tx = tx.clone(); + tokio::spawn(async move { + let cancellation = skippy_inference_api::CancellationToken::new(); + let admitted = controller + .acquire_scheduled_work( + &trusted_ids(label), + &cancellation, + Duration::from_secs(2), + work, + GenerationAdmissionScheduling::new( + Arc::from(prompt), + Arc::new(skippy_scheduler::CacheAffinity::default), + ), + ) + .await + .expect("queued request admission"); + tx.send((label, admitted)).await.unwrap(); + }); + } + drop(tx); + tokio::time::timeout(Duration::from_secs(1), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 4 { + tokio::task::yield_now().await; + } + }) + .await + .expect("all prompts become scheduler-visible"); + + drop(active); + let (first_label, first) = tokio::time::timeout(Duration::from_millis(250), rx.recv()) + .await + .expect("first queued admission was promoted") + .expect("first queued admission"); + drop(first); + let (second_label, second) = rx.recv().await.expect("second queued admission"); + assert_ne!( + first_label.split('-').nth(1), + second_label.split('-').nth(1), + "one family must not drain the whole lane wave" + ); + drop(second); + let (_, third) = rx.recv().await.expect("third queued admission"); + drop(third); + let (_, fourth) = rx.recv().await.expect("fourth queued admission"); + drop(fourth); +} + +#[tokio::test] +async fn capacity_waiter_holds_neither_a_lane_nor_kv_until_atomic_promotion() { + let controller = admission_controller_with_budget(2, 2, 10); + let active = controller + .acquire_work( + &trusted_ids("active"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(7, 0), + ) + .await + .expect("first capacity reservation"); + let waiting_controller = controller.clone(); + let waiter = tokio::spawn(async move { + waiting_controller + .acquire_work( + &trusted_ids("waiting"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(7, 0), + ) + .await + }); + + tokio::time::timeout(Duration::from_millis(100), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .expect("capacity waiter entered the queue"); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_token_budget.active_tokens(), 7); + + drop(active); + let promoted = tokio::time::timeout(Duration::from_millis(100), waiter) + .await + .expect("capacity waiter promoted") + .expect("capacity waiter task completed") + .expect("capacity waiter admission"); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_token_budget.active_tokens(), 7); + drop(promoted); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); +} + +#[tokio::test] +async fn capacity_waiters_drain_serially_after_each_kv_release() { + let controller = admission_controller_with_budget(2, 4, 10); + let active = controller + .acquire_work( + &trusted_ids("active"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(10, 0), + ) + .await + .expect("active capacity reservation"); + let (tx, mut rx) = tokio::sync::mpsc::channel(4); + for index in 0..4 { + let controller = controller.clone(); + let tx = tx.clone(); + tokio::spawn(async move { + let cancellation = skippy_inference_api::CancellationToken::new(); + let admitted = controller + .acquire_work( + &trusted_ids(&format!("waiting-{index}")), + &cancellation, + Duration::ZERO, + GenerationAdmissionWork::new(10, 0), + ) + .await + .expect("queued capacity admission"); + tx.send(admitted).await.unwrap(); + }); + } + drop(tx); + tokio::time::timeout(Duration::from_secs(1), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 4 { + tokio::task::yield_now().await; + } + }) + .await + .expect("all capacity waiters entered the queue"); + + drop(active); + for _ in 0..4 { + let admitted = tokio::time::timeout(Duration::from_secs(1), rx.recv()) + .await + .expect("next capacity waiter promoted") + .expect("queued capacity admission"); + assert_eq!(controller.generation_token_budget.active_tokens(), 10); + drop(admitted); + } + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); +} + +#[tokio::test] +async fn full_pool_waiter_is_admitted_after_bounded_half_pool_bypasses() { + let controller = admission_controller_with_budget(2, 4, 10); + let half_pool_work = GenerationAdmissionWork::new(5, 0); + let full_pool_work = GenerationAdmissionWork::new(10, 0); + let active = controller + .acquire_work( + &trusted_ids("active-half-pool"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + half_pool_work, + ) + .await + .expect("initial half-pool admission"); + + let full_pool_controller = controller.clone(); + let full_pool_waiter = tokio::spawn(async move { + full_pool_controller + .acquire_work( + &trusted_ids("full-pool-waiter"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + full_pool_work, + ) + .await + }); + tokio::time::timeout(Duration::from_secs(1), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .expect("full-pool request entered the queue"); + + // Keep one half-pool reservation active and repeatedly fill/release the + // other half. The full-pool request cannot fit during these admissions. + for wave in 0..ADMISSION_STARVATION_BOUND_TURNS { + let bypass = tokio::time::timeout( + Duration::from_secs(1), + controller.acquire_work( + &trusted_ids(&format!("half-pool-bypass-{wave}")), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + half_pool_work, + ), + ) + .await + .expect("fitting half-pool request completed before the timeout") + .expect("fitting half-pool request admitted before the bound"); + assert_eq!(controller.generation_token_budget.active_tokens(), 10); + drop(bypass); + } + + // The next fitting arrival reaches the bound and must remain queued while + // the controller drains capacity toward the older full-pool request. + let bypass_controller = controller.clone(); + let blocked_bypass = tokio::spawn(async move { + bypass_controller + .acquire_work( + &trusted_ids("half-pool-after-bound"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + half_pool_work, + ) + .await + }); + tokio::time::timeout(Duration::from_secs(1), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 2 { + tokio::task::yield_now().await; + } + }) + .await + .expect("post-bound half-pool request remained queued"); + assert!(!full_pool_waiter.is_finished()); + assert!(!blocked_bypass.is_finished()); + + drop(active); + let admitted_full_pool = tokio::time::timeout(Duration::from_secs(1), full_pool_waiter) + .await + .expect("full-pool waiter admitted after capacity drained") + .expect("full-pool waiter task completed") + .expect("full-pool admission succeeded"); + assert_eq!(controller.generation_token_budget.active_tokens(), 10); + assert!(!blocked_bypass.is_finished()); + + drop(admitted_full_pool); + let admitted_bypass = tokio::time::timeout(Duration::from_secs(1), blocked_bypass) + .await + .expect("younger half-pool waiter admitted after the senior completed") + .expect("half-pool waiter task completed") + .expect("half-pool admission succeeded"); + drop(admitted_bypass); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); +} + +#[tokio::test] +async fn request_larger_than_the_kv_pool_fails_without_queueing_or_taking_a_lane() { + let controller = admission_controller_with_budget(2, 2, 128); + let error = result_error( + controller + .acquire_work( + &trusted_ids("too-large"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(129, 0), + ) + .await, + ); + + assert_eq!(error.status(), axum::http::StatusCode::BAD_REQUEST); + assert_eq!( + error.body().error.code.as_deref(), + Some("context_length_exceeded") + ); + assert!( + error + .body() + .error + .message + .contains("runtime pool holds 128") + ); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); +} + +#[tokio::test] +async fn cancelling_a_capacity_waiter_leaks_neither_lane_nor_kv_reservation() { + let controller = admission_controller_with_budget(2, 2, 128); + let active = controller + .acquire_work( + &trusted_ids("active"), + &skippy_inference_api::CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(100, 0), + ) + .await + .expect("first capacity reservation"); + let cancellation = skippy_inference_api::CancellationToken::new(); + let waiter_cancellation = cancellation.clone(); + let waiting_controller = controller.clone(); + let waiter = tokio::spawn(async move { + waiting_controller + .acquire_work( + &trusted_ids("waiting"), + &waiter_cancellation, + Duration::ZERO, + GenerationAdmissionWork::new(64, 0), + ) + .await + }); + tokio::time::timeout(Duration::from_millis(100), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .expect("capacity waiter entered the queue"); + + cancellation.cancel(); + let error = result_error( + tokio::time::timeout(Duration::from_millis(100), waiter) + .await + .expect("cancelled capacity waiter returned") + .expect("capacity waiter task completed"), + ); + assert!(error.body().error.message.contains("request cancelled")); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_token_budget.active_tokens(), 100); + + drop(active); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); +} + +#[tokio::test] +async fn inflated_prediction_waits_for_capacity_and_preserves_queue_bounds() { + let controller = admission_controller(1, 1); + let work = GenerationAdmissionWork::new(100, 100); + controller.generation_service_estimator.observe_completed( + GenerationAdmissionWork::new(467, 21), + 994.1, + 115_557.901_853, + ); + let active = controller + .acquire_work( + &trusted_ids("agent-1"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(1), + work, + ) + .await + .expect("active request admission"); + + let timeout = Duration::from_secs(1); + let predicted = controller + .generation_service_estimator + .predicted_wait_ms() + .unwrap(); + assert!(predicted > timeout.as_secs_f64() * 1_000.0); + let ids = trusted_ids("agent-2"); + let cancellation = skippy_inference_api::CancellationToken::new(); + let waiting = controller.acquire_work(&ids, &cancellation, timeout, work); + tokio::pin!(waiting); + // Poll synchronously: this must queue rather than immediately reject the + // inflated prediction, without depending on scheduling delays or sleeps. + assert!(futures_util::poll!(&mut waiting).is_pending()); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 1); + assert_eq!(controller.generation_limit.available_permits(), 0); + assert_eq!(controller.generation_token_budget.active_tokens(), 200); + let overflow = result_error( + controller + .acquire_work( + &trusted_ids("overflow"), + &skippy_inference_api::CancellationToken::new(), + timeout, + work, + ) + .await, + ); + assert!(overflow.body().error.message.contains("queue is full")); + drop(active); + let admitted = waiting + .await + .expect("released lane admits despite inflated prediction"); + assert_eq!(admitted.0.predicted_wait_ms, Some(predicted)); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_token_budget.active_tokens(), 200); + drop(admitted); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); + assert_eq!( + controller.generation_service_estimator.predicted_wait_ms(), + Some(0.0) + ); + assert!( + controller + .generation_session_locks + .lock() + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn advisory_prediction_does_not_bypass_an_expired_admission_deadline() { + let controller = admission_controller(1, 1); + let work = GenerationAdmissionWork::new(100, 100); + controller + .generation_service_estimator + .observe_completed(work, 100.0, 100.0); + let active = controller + .acquire_work( + &trusted_ids("active"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(1), + work, + ) + .await + .expect("active request admission"); + let error = result_error( + controller + .acquire_generation_permit_until( + Some(Instant::now()), + Duration::from_secs(1), + &skippy_inference_api::CancellationToken::new(), + work, + GenerationAdmissionScheduling::default(), + ) + .await, + ); + assert!(error.body().error.message.contains("timed out waiting")); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + assert_eq!(controller.generation_limit.available_permits(), 0); + assert_eq!(controller.generation_token_budget.active_tokens(), 200); + drop(active); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_token_budget.active_tokens(), 0); + assert_eq!( + controller.generation_service_estimator.predicted_wait_ms(), + Some(0.0) + ); +} + +#[test] +fn session_registry_counts_live_leases_and_cleans_replaced_entries() { + let registry = Arc::new(Mutex::new(BTreeMap::new())); + let first = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) + .expect("first session lease"); + let second = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) + .expect("second session lease"); + + { + let locks = registry.lock().expect("session registry lock"); + let entry = locks.get("agent-1").expect("shared session entry"); + assert_eq!(entry.users.load(Ordering::Acquire), 2); + } + + drop(first); + { + let locks = registry.lock().expect("session registry lock"); + let entry = locks.get("agent-1").expect("live session entry"); + assert_eq!(entry.users.load(Ordering::Acquire), 1); + } + + drop(second); + assert!(registry.lock().expect("session registry lock").is_empty()); + + let replacement = GenerationSessionPermit::new(registry.clone(), "agent-1".to_owned()) + .expect("replacement session lease"); + assert_eq!(registry.lock().expect("session registry lock").len(), 1); + drop(replacement); + assert!(registry.lock().expect("session registry lock").is_empty()); +} + +#[tokio::test] +async fn same_trusted_session_serializes_without_consuming_global_queue_capacity() { + let controller = admission_controller(1, 1); + let session_key = trusted_session_key("agent-1"); + let first_cancellation = skippy_inference_api::CancellationToken::new(); + let first = controller + .acquire( + &trusted_ids("agent-1"), + &first_cancellation, + Duration::from_secs(1), + ) + .await + .expect("first session admission"); + + let second_controller = controller.clone(); + let second_cancellation = skippy_inference_api::CancellationToken::new(); + let waiter_cancellation = second_cancellation.clone(); + let waiter = tokio::spawn(async move { + second_controller + .acquire( + &trusted_ids("agent-1"), + &waiter_cancellation, + Duration::from_secs(1), + ) + .await + }); + + tokio::time::timeout(Duration::from_millis(100), async { + loop { + let users = controller + .generation_session_locks + .lock() + .expect("session registry lock") + .get(&session_key) + .map_or(0, |entry| entry.users.load(Ordering::Acquire)); + if users == 2 { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("second turn registered its session wait"); + + assert!(!waiter.is_finished()); + assert_eq!( + controller.generation_queue_depth.load(Ordering::Acquire), + 0, + "session contention must not consume global queue capacity" + ); + + second_cancellation.cancel(); + let error = result_error( + tokio::time::timeout(Duration::from_millis(100), waiter) + .await + .expect("cancelled session waiter returned") + .expect("session waiter task completed"), + ); + assert!(error.body().error.message.contains("request cancelled")); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + + drop(first); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert!( + controller + .generation_session_locks + .lock() + .expect("session registry lock") + .is_empty() + ); +} + +#[tokio::test] +async fn same_trusted_session_acquires_only_after_the_first_turn_releases() { + let controller = admission_controller(1, 1); + let first_cancellation = skippy_inference_api::CancellationToken::new(); + let first = controller + .acquire( + &trusted_ids("agent-1"), + &first_cancellation, + Duration::from_secs(1), + ) + .await + .expect("first session admission"); + + let second_controller = controller.clone(); + let second = tokio::spawn(async move { + second_controller + .acquire( + &trusted_ids("agent-1"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(1), + ) + .await + }); + + tokio::time::sleep(Duration::from_millis(5)).await; + assert!(!second.is_finished()); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + + drop(first); + let second = tokio::time::timeout(Duration::from_millis(100), second) + .await + .expect("second turn acquired after first released") + .expect("second turn task completed") + .expect("second session admission"); + assert_eq!(controller.generation_limit.available_permits(), 0); + drop(second); + assert_eq!(controller.generation_limit.available_permits(), 1); +} + +#[tokio::test] +async fn session_and_global_admission_share_one_absolute_deadline() { + let controller = admission_controller(1, 1); + let first_cancellation = skippy_inference_api::CancellationToken::new(); + let (global_permit, session_permit) = controller + .acquire( + &trusted_ids("agent-1"), + &first_cancellation, + Duration::from_secs(1), + ) + .await + .expect("first session admission"); + let session_permit = session_permit.expect("trusted session permit"); + let release_session = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(140)).await; + drop(session_permit); + }); + let started = Instant::now(); + + let error = result_error( + controller + .acquire( + &trusted_ids("agent-1"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_millis(200), + ) + .await, + ); + + assert!(error.body().error.message.contains("timed out waiting")); + assert!( + started.elapsed() < Duration::from_millis(300), + "global-lane waiting must not restart the request admission timeout" + ); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + release_session + .await + .expect("session release task completed"); + drop(global_permit); +} + +#[tokio::test] +async fn unrelated_session_is_not_starved_by_a_same_session_waiter() { + let controller = admission_controller(2, 2); + let session_key = trusted_session_key("agent-1"); + let first_cancellation = skippy_inference_api::CancellationToken::new(); + let first = controller + .acquire( + &trusted_ids("agent-1"), + &first_cancellation, + Duration::from_secs(1), + ) + .await + .expect("first session admission"); + + let duplicate_controller = controller.clone(); + let duplicate_cancellation = skippy_inference_api::CancellationToken::new(); + let waiter_cancellation = duplicate_cancellation.clone(); + let duplicate = tokio::spawn(async move { + duplicate_controller + .acquire( + &trusted_ids("agent-1"), + &waiter_cancellation, + Duration::from_secs(1), + ) + .await + }); + + tokio::time::timeout(Duration::from_millis(100), async { + loop { + let users = controller + .generation_session_locks + .lock() + .expect("session registry lock") + .get(&session_key) + .map_or(0, |entry| entry.users.load(Ordering::Acquire)); + if users == 2 { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("duplicate turn registered its session wait"); + + assert_eq!(controller.generation_limit.available_permits(), 1); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + + let unrelated = controller + .acquire( + &trusted_ids("agent-2"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_millis(100), + ) + .await + .expect("unrelated session used the free global lane"); + assert_eq!(controller.generation_limit.available_permits(), 0); + assert!(!duplicate.is_finished()); + + duplicate_cancellation.cancel(); + let duplicate_error = result_error( + tokio::time::timeout(Duration::from_millis(100), duplicate) + .await + .expect("duplicate waiter cancelled") + .expect("duplicate waiter task completed"), + ); + assert!( + duplicate_error + .body() + .error + .message + .contains("request cancelled") + ); + drop((first, unrelated)); + assert_eq!(controller.generation_limit.available_permits(), 2); +} + +#[tokio::test] +async fn same_session_waiter_does_not_reserve_the_only_global_queue_slot() { + let controller = admission_controller(1, 1); + let session_key = trusted_session_key("agent-1"); + let first = controller + .acquire( + &trusted_ids("agent-1"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(1), + ) + .await + .expect("first session admission"); + + let duplicate_controller = controller.clone(); + let duplicate_cancellation = skippy_inference_api::CancellationToken::new(); + let waiter_cancellation = duplicate_cancellation.clone(); + let duplicate = tokio::spawn(async move { + duplicate_controller + .acquire( + &trusted_ids("agent-1"), + &waiter_cancellation, + Duration::from_secs(1), + ) + .await + }); + tokio::time::timeout(Duration::from_millis(100), async { + loop { + let users = controller + .generation_session_locks + .lock() + .expect("session registry lock") + .get(&session_key) + .map_or(0, |entry| entry.users.load(Ordering::Acquire)); + if users == 2 { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("duplicate turn registered its session wait"); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + + let unrelated_controller = controller.clone(); + let unrelated = tokio::spawn(async move { + unrelated_controller + .acquire( + &trusted_ids("agent-2"), + &skippy_inference_api::CancellationToken::new(), + Duration::from_secs(1), + ) + .await + }); + tokio::time::timeout(Duration::from_millis(100), async { + while controller.generation_queue_depth.load(Ordering::Acquire) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .expect("unrelated turn reserved the only global queue slot"); + assert!(!unrelated.is_finished()); + + duplicate_cancellation.cancel(); + let duplicate_error = result_error( + tokio::time::timeout(Duration::from_millis(100), duplicate) + .await + .expect("duplicate waiter cancelled") + .expect("duplicate waiter task completed"), + ); + assert_eq!(duplicate_error.status().as_u16(), 499); + + drop(first); + let unrelated = tokio::time::timeout(Duration::from_millis(100), unrelated) + .await + .expect("unrelated turn acquired the released lane") + .expect("unrelated waiter task completed") + .expect("unrelated session admission"); + assert_eq!(controller.generation_queue_depth.load(Ordering::Acquire), 0); + drop(unrelated); +} + +#[tokio::test] +async fn different_trusted_sessions_can_hold_generation_lanes_concurrently() { + let controller = admission_controller(2, 2); + let first_cancellation = skippy_inference_api::CancellationToken::new(); + let second_cancellation = skippy_inference_api::CancellationToken::new(); + let first_ids = trusted_ids("agent-1"); + let second_ids = trusted_ids("agent-2"); + + let (first, second) = tokio::join!( + controller.acquire(&first_ids, &first_cancellation, Duration::from_secs(1)), + controller.acquire(&second_ids, &second_cancellation, Duration::from_secs(1)), + ); + let first = first.expect("first session admission"); + let second = second.expect("second session admission"); + + assert_eq!(controller.generation_limit.available_permits(), 0); + assert_eq!( + controller + .generation_session_locks + .lock() + .expect("session registry lock") + .len(), + 2 + ); + + drop((first, second)); + assert_eq!(controller.generation_limit.available_permits(), 2); + assert!( + controller + .generation_session_locks + .lock() + .expect("session registry lock") + .is_empty() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn blocking_worker_holds_global_and_session_permits_until_work_finishes() { + let controller = admission_controller(1, 1); + let session_key = trusted_session_key("agent-1"); + let cancellation = skippy_inference_api::CancellationToken::new(); + let (global_permit, session_permit) = controller + .acquire( + &trusted_ids("agent-1"), + &cancellation, + Duration::from_secs(1), + ) + .await + .expect("worker admission"); + let worker_context = InferenceRequestContext::new(); + let worker_started = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let release_worker = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let started = worker_started.clone(); + let release = release_worker.clone(); + + let worker = tokio::spawn(run_blocking_generation_worker( + global_permit, + worker_context, + move |_| { + let _session_permit = session_permit; + started.store(true, Ordering::Release); + while !release.load(Ordering::Acquire) { + std::thread::yield_now(); + } + }, + )); + + tokio::time::timeout(Duration::from_millis(100), async { + while !worker_started.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .expect("blocking generation worker started"); + + assert_eq!(controller.generation_limit.available_permits(), 0); + let entry = controller + .generation_session_locks + .lock() + .expect("session registry lock") + .get(&session_key) + .expect("worker retains session entry") + .semaphore + .clone(); + assert_eq!(entry.available_permits(), 0); + + release_worker.store(true, Ordering::Release); + tokio::time::timeout(Duration::from_millis(100), worker) + .await + .expect("blocking generation worker completed") + .expect("worker task completed") + .expect("blocking worker joined"); + assert_eq!(controller.generation_limit.available_permits(), 1); + assert!( + controller + .generation_session_locks + .lock() + .expect("session registry lock") + .is_empty() + ); +} + +#[test] +fn untrusted_conversation_affinity_bypasses_session_registry() { + let registry = Arc::new(Mutex::new(BTreeMap::new())); + let untrusted = InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("conversation-7"), + false, + None, + ); + assert!(trusted_generation_session_key(&untrusted).is_none()); + assert!(registry.lock().expect("session registry lock").is_empty()); + + let trusted = trusted_ids("agent-7"); + let key = trusted_generation_session_key(&trusted).expect("trusted session key"); + assert_eq!(key, trusted.session_id_string()); + let _permit = + GenerationSessionPermit::new(registry.clone(), key).expect("trusted session lease"); + assert_eq!(registry.lock().expect("session registry lock").len(), 1); +} diff --git a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs index d718d86434..22886d5687 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs @@ -472,28 +472,22 @@ impl GenerationServiceEstimator { pub(in crate::frontend) fn reserve_queued( self: &Arc, work: GenerationAdmissionWork, - admission_timeout: Duration, - ) -> Result { + ) -> GenerationQueuedWorkReservation { let Ok(mut state) = self.state.lock() else { - return Ok(GenerationQueuedWorkReservation { + return GenerationQueuedWorkReservation { estimator: self.clone(), work, queued: false, - }); + }; }; - if !admission_timeout.is_zero() - && let Some(wait_ms) = - predicted_wait_ms_for_state(&state, self.concurrency.load(Ordering::Acquire)) - && wait_ms > admission_timeout.as_secs_f64() * 1_000.0 - { - return Err(wait_ms); - } + // Predictions include interference and unfinished requests' original + // work, so they are advisory. The queue owns capacity and deadlines. state.queued = add_work(state.queued, work); - Ok(GenerationQueuedWorkReservation { + GenerationQueuedWorkReservation { estimator: self.clone(), work, queued: true, - }) + } } pub(in crate::frontend) fn start_active( @@ -908,46 +902,24 @@ pub(in crate::frontend) fn generation_queue_timeout_error(timeout: Duration) -> .with_retry_after_secs(GENERATION_RETRY_AFTER_SECS) } -pub(in crate::frontend) fn generation_predicted_wait_error( - predicted_wait_ms: f64, - timeout: Duration, -) -> InferenceError { - InferenceError::from_kind( - StatusCode::TOO_MANY_REQUESTS, - InferenceErrorKind::RateLimit, - format!( - "predicted generation wait {:.3} seconds exceeds the {:.3}-second admission timeout", - predicted_wait_ms / 1_000.0, - timeout.as_secs_f64(), - ), - ) - .with_retry_after_secs(GENERATION_RETRY_AFTER_SECS) -} - #[cfg(test)] mod service_estimator_tests { use super::*; #[test] - fn warm_estimator_rejects_work_beyond_the_wait_slo() { + fn high_prediction_does_not_refuse_work_accounting() { let estimator = Arc::new(GenerationServiceEstimator::new(1)); let work = GenerationAdmissionWork::new(100, 100); estimator.observe_completed(work, 100.0, 100.0); let active = estimator.start_active(work); assert_eq!(estimator.predicted_wait_ms(), Some(200.0)); - assert!( - estimator - .reserve_queued(work, Duration::from_millis(199)) - .is_err() - ); - assert!( - estimator - .reserve_queued(work, Duration::from_millis(200)) - .is_ok() - ); - + let queued = estimator.reserve_queued(work); + assert_eq!(estimator.predicted_wait_ms(), Some(400.0)); + drop(queued); + assert_eq!(estimator.predicted_wait_ms(), Some(200.0)); drop(active); + assert_eq!(estimator.predicted_wait_ms(), Some(0.0)); } #[test] @@ -955,9 +927,7 @@ mod service_estimator_tests { let estimator = Arc::new(GenerationServiceEstimator::new(2)); let work = GenerationAdmissionWork::new(80, 20); estimator.observe_completed(work, 80.0, 20.0); - let queued = estimator - .reserve_queued(work, Duration::from_secs(1)) - .expect("cold queue reservation"); + let queued = estimator.reserve_queued(work); assert_eq!(estimator.predicted_wait_ms(), Some(50.0)); let active = queued.promote(); From ae2b64f773ca64964f6ac3353e924771f7f6b16b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 05:26:16 +1100 Subject: [PATCH 19/81] fix(skippy): restore cooperative prefill and longest-prefix reuse --- .../src/frontend/iteration_scheduler.rs | 46 +- .../iteration_scheduler/cache_runtime.rs | 107 ++- .../src/frontend/iteration_scheduler/tests.rs | 4 +- .../src/frontend/local_generation/tests.rs | 5 + .../tests/cooperative_prefill.rs | 186 +++++ .../tests/recurrent_fixture.rs | 175 +++++ .../local_generation/token_generation.rs | 737 +----------------- .../token_generation/cache_prefill.rs | 732 +++++++++++++++++ .../token_generation/kv_restore.rs | 44 +- .../src/kv_integration/exact_state.rs | 39 +- .../exact_state/resident_preference.rs | 163 ++++ .../skippy-serving/src/kv_integration/mod.rs | 1 + .../src/kv_integration/scheduling.rs | 70 ++ 13 files changed, 1470 insertions(+), 839 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/scheduling.rs diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 71db6d3287..492bfcc19d 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -1,4 +1,4 @@ -mod cache_runtime; +pub(super) mod cache_runtime; mod detached_runtime; mod direct_batch; mod direct_execution; @@ -20,7 +20,7 @@ use crate::frontend::admission::DECODE_BATCH_HEADROOM_TOKENS; use crate::frontend::generation::TokenControl; use crate::frontend::generation::generation_queue_full_error; use crate::frontend::util::openai_backend_error; -use crate::kv_integration::StagePrefixCachePayload; +use crate::kv_integration::scheduling::CacheSchedulingPolicy; use crate::runtime_state::panic_recovery::lock_runtime; use crate::runtime_state::{RuntimeIterationBatchRequest, RuntimeSessionAlignStats, RuntimeState}; use crate::telemetry::Telemetry; @@ -103,16 +103,6 @@ pub(crate) struct DirectIterationChannel { result: std_mpsc::Receiver>, } -pub(crate) struct CacheAwareRuntimeRequest<'a> { - pub(crate) operation_id: String, - pub(crate) deadline: Instant, - pub(crate) cancellation: Option<&'a skippy_inference_api::CancellationToken>, - pub(crate) prompt_tokens: Arc<[i32]>, - pub(crate) priority: u64, - pub(crate) payload: StagePrefixCachePayload, - pub(crate) refresh_affinity: CacheAffinityRefresh, -} - struct IterationSchedulerShared { commands: std_mpsc::SyncSender, max_direct_iteration_tokens: usize, @@ -348,7 +338,7 @@ enum SchedulerCommand { RuntimeOperation, Arc<[i32]>, u64, - StagePrefixCachePayload, + CacheSchedulingPolicy, CacheAffinityRefresh, ), Cancel(String), @@ -799,36 +789,6 @@ impl IterationScheduler { })? } - /// Queue cache restore/prefill work by stage-local radix affinity while - /// retaining aging and decode-turn fairness. - pub(crate) fn execute_cache_aware_runtime_timed( - &self, - label: &'static str, - request: CacheAwareRuntimeRequest<'_>, - operation: impl FnOnce(&mut RuntimeState, &CacheRuntimeContext) -> InferenceResult - + Send - + 'static, - ) -> InferenceResult> - where - T: Send + 'static, - { - let (runtime_operation, result, control) = cache_runtime_operation( - label, - request.operation_id, - request.deadline, - request.cancellation, - operation, - ); - self.enqueue_command(SchedulerCommand::ExecuteCacheAwareRuntime( - runtime_operation, - request.prompt_tokens, - request.priority, - request.payload, - request.refresh_affinity, - ))?; - wait_for_cache_runtime(result, &control) - } - fn enqueue_command(&self, command: SchedulerCommand) -> InferenceResult<()> { self.shared .commands diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs index 1ae996f24b..43c6ea3fc3 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs @@ -1,7 +1,13 @@ -use super::RuntimeOperation; -use crate::kv_integration::StagePrefixCachePayload; +use super::{ + CacheRuntimeContext, IterationScheduler, RuntimeOperation, SchedulerCommand, + SchedulerRuntimeOutcome, cache_runtime_operation, wait_for_cache_runtime, +}; +use crate::kv_integration::scheduling::CacheSchedulingPolicy; +use crate::runtime_state::RuntimeState; +use skippy_inference_api::InferenceResult; use skippy_scheduler::{CacheAffinity, CacheAwareCandidate, order_cache_aware_candidates}; use std::sync::Arc; +use std::time::Instant; pub(super) type CacheAffinityRefresh = Box CacheAffinity + Send>; @@ -12,7 +18,7 @@ pub(super) struct CacheAwareRuntimeOperation { priority: u64, enqueued_turn: u64, order: u64, - payload: StagePrefixCachePayload, + scheduling: CacheSchedulingPolicy, refresh_affinity: Option, affinity_initialized: bool, stale_affinity_fallback: bool, @@ -29,7 +35,7 @@ pub(super) struct CacheRuntimeTelemetry { } struct CacheRuntimeEnqueueState { - payload: StagePrefixCachePayload, + scheduling: CacheSchedulingPolicy, refresh_affinity: Option, affinity_initialized: bool, } @@ -80,7 +86,7 @@ impl CacheRuntimeQueue { prompt_tokens, priority, CacheRuntimeEnqueueState { - payload: StagePrefixCachePayload::ResidentKv, + scheduling: CacheSchedulingPolicy::Serialized, refresh_affinity, affinity_initialized: true, }, @@ -88,13 +94,13 @@ impl CacheRuntimeQueue { } #[cfg(test)] - pub(super) fn enqueue_with_payload( + pub(super) fn enqueue_with_policy( &mut self, operation: RuntimeOperation, affinity: CacheAffinity, prompt_tokens: Arc<[i32]>, priority: u64, - payload: StagePrefixCachePayload, + scheduling: CacheSchedulingPolicy, refresh_affinity: Option, ) { self.enqueue_with_affinity_state( @@ -103,7 +109,7 @@ impl CacheRuntimeQueue { prompt_tokens, priority, CacheRuntimeEnqueueState { - payload, + scheduling, refresh_affinity, affinity_initialized: true, }, @@ -115,7 +121,7 @@ impl CacheRuntimeQueue { operation: RuntimeOperation, prompt_tokens: Arc<[i32]>, priority: u64, - payload: StagePrefixCachePayload, + scheduling: CacheSchedulingPolicy, refresh_affinity: CacheAffinityRefresh, ) { self.enqueue_with_affinity_state( @@ -124,7 +130,7 @@ impl CacheRuntimeQueue { prompt_tokens, priority, CacheRuntimeEnqueueState { - payload, + scheduling, refresh_affinity: Some(refresh_affinity), affinity_initialized: false, }, @@ -148,7 +154,7 @@ impl CacheRuntimeQueue { priority, enqueued_turn: self.turn, order, - payload: state.payload, + scheduling: state.scheduling, refresh_affinity: state.refresh_affinity, affinity_initialized: state.affinity_initialized, stale_affinity_fallback: false, @@ -163,7 +169,7 @@ impl CacheRuntimeQueue { pub(super) fn has_wave_aware_operations(&self) -> bool { self.operations .iter() - .any(|operation| cache_runtime_wave_enabled(operation.payload)) + .any(|operation| cache_runtime_wave_enabled(operation.scheduling)) } pub(super) fn pop_next( @@ -188,7 +194,7 @@ impl CacheRuntimeQueue { .map(|stage| stage.cache_epoch) .max() .unwrap_or(0), - wave_aware: cache_runtime_wave_enabled(queued.payload), + wave_aware: cache_runtime_wave_enabled(queued.scheduling), stale_affinity_fallback: queued.stale_affinity_fallback, }; Some((queued, telemetry)) @@ -295,9 +301,9 @@ pub(super) fn should_suppress_cache_runtime( && active_runtime_sessions >= max_direct_batch_size } -/// Direct-only work still coalesces, but a queued Resident KV operation keeps -/// the legacy scheduler turn cadence. Recurrent-state cache work opts into the -/// wave coalescing behavior. +/// Serialized resident work retains its existing turn cadence. Loaded +/// checkpoint-capable work cooperates with direct iteration waves regardless +/// of whether its state is retained as a native owner or serialized payload. pub(super) fn should_coalesce_direct_iterations( has_cache_runtime: bool, has_wave_aware_cache_runtime: bool, @@ -305,8 +311,50 @@ pub(super) fn should_coalesce_direct_iterations( !has_cache_runtime || has_wave_aware_cache_runtime } -pub(super) fn cache_runtime_wave_enabled(payload: StagePrefixCachePayload) -> bool { - payload.is_exact_state() +pub(super) fn cache_runtime_wave_enabled(scheduling: CacheSchedulingPolicy) -> bool { + scheduling.cooperative() +} + +pub(crate) struct CacheAwareRuntimeRequest<'a> { + pub(crate) operation_id: String, + pub(crate) deadline: Instant, + pub(crate) cancellation: Option<&'a skippy_inference_api::CancellationToken>, + pub(crate) prompt_tokens: Arc<[i32]>, + pub(crate) priority: u64, + pub(crate) scheduling: CacheSchedulingPolicy, + pub(crate) refresh_affinity: CacheAffinityRefresh, +} + +impl IterationScheduler { + /// Queue cache restore/prefill work by stage-local radix affinity while + /// retaining aging and decode-turn fairness. + pub(crate) fn execute_cache_aware_runtime_timed( + &self, + label: &'static str, + request: CacheAwareRuntimeRequest<'_>, + operation: impl FnOnce(&mut RuntimeState, &CacheRuntimeContext) -> InferenceResult + + Send + + 'static, + ) -> InferenceResult> + where + T: Send + 'static, + { + let (runtime_operation, result, control) = cache_runtime_operation( + label, + request.operation_id, + request.deadline, + request.cancellation, + operation, + ); + self.enqueue_command(SchedulerCommand::ExecuteCacheAwareRuntime( + runtime_operation, + request.prompt_tokens, + request.priority, + request.scheduling, + request.refresh_affinity, + ))?; + wait_for_cache_runtime(result, &control) + } } #[cfg(test)] @@ -366,15 +414,12 @@ mod tests { } #[test] - fn cache_wave_gates_are_opt_in_by_payload() { + fn cache_wave_gates_follow_cooperative_scheduling() { assert!(!cache_runtime_wave_enabled( - StagePrefixCachePayload::ResidentKv - )); - assert!(cache_runtime_wave_enabled( - StagePrefixCachePayload::KvRecurrent + CacheSchedulingPolicy::Serialized )); assert!(cache_runtime_wave_enabled( - StagePrefixCachePayload::FullState + CacheSchedulingPolicy::Cooperative )); assert!(!should_fill_cache_runtime_wave(true, false, 1, 4)); @@ -384,7 +429,7 @@ mod tests { } #[test] - fn queue_wave_awareness_and_coalescing_are_payload_specific() { + fn queue_wave_awareness_and_coalescing_follow_scheduling_policy() { let (selected, _selected_rx) = mpsc::channel(); let mut resident_queue = CacheRuntimeQueue::new(4_096, true); resident_queue.enqueue( @@ -417,17 +462,15 @@ mod tests { resident_queue.has_wave_aware_operations(), )); - for payload in [ - StagePrefixCachePayload::KvRecurrent, - StagePrefixCachePayload::FullState, - ] { + { + let scheduling = CacheSchedulingPolicy::Cooperative; let mut queue = CacheRuntimeQueue::new(4_096, true); - queue.enqueue_with_payload( + queue.enqueue_with_policy( operation(&selected, "recurrent"), CacheAffinity::default(), Arc::from([1]), 0, - payload, + scheduling, None, ); assert!(queue.has_wave_aware_operations()); @@ -572,7 +615,7 @@ mod tests { operation(&selected, "lazy"), Arc::from([1, 2, 3]), 0, - StagePrefixCachePayload::ResidentKv, + CacheSchedulingPolicy::Serialized, Box::new(move || { refresh_count.fetch_add(1, Ordering::Relaxed); CacheAffinity::from_stage(StageCacheAffinity { diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index 91bbfabdc1..0a85af6e57 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -800,7 +800,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e last_served_cache_runtime: false, last_emitted_lifecycle_counters: (0, 0, 0, 0), }; - worker.cache_runtime_queue.enqueue_with_payload( + worker.cache_runtime_queue.enqueue_with_policy( RuntimeOperation { label: "full-wave-cache", control: None, @@ -812,7 +812,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e skippy_scheduler::CacheAffinity::default(), Arc::from([1]), 0, - StagePrefixCachePayload::KvRecurrent, + CacheSchedulingPolicy::Cooperative, None, ); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index 8bc2c2addb..b4b573b54f 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -31,6 +31,11 @@ use skippy_runtime::SamplingConfig; #[path = "tests/durable_prefix.rs"] mod durable_prefix; +#[path = "tests/recurrent_fixture.rs"] +mod recurrent_fixture; +use recurrent_fixture::recurrent_test_backend; +#[path = "tests/cooperative_prefill.rs"] +mod cooperative_prefill; // The real-model tests below are deliberately ignored by default. The // fixture contract is explicit: run them with both model-path variables set; diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs new file mode 100644 index 0000000000..9ef8005682 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs @@ -0,0 +1,186 @@ +//! Real scheduler progress, exact checkpoint capture, and cancellation cleanup. +use super::recurrent_fixture::recurrent_test_backend_with_lanes; +use super::*; +use std::sync::mpsc; +use std::time::Instant; + +struct PendingPrefill { + cancellation: skippy_inference_api::CancellationToken, + worker: Option< + thread::JoinHandle< + skippy_inference_api::InferenceResult< + crate::frontend::generation::GenerationCacheStats, + >, + >, + >, +} + +impl Drop for PendingPrefill { + fn drop(&mut self) { + self.cancellation.cancel(); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn resident_checkpoint_prefill_yields_to_decode_and_cancels_without_losing_checkpoint() -> Result<()> +{ + let (backend, speculative) = recurrent_test_backend_with_lanes( + "cooperative-prefill", + "cooperative-prefill", + 8192, + 32, + 1, + 16384, + 2, + )?; + let kv = backend.kv.as_ref().unwrap(); + assert!( + kv.l3.is_none(), + "this test must exercise disk-off capability admission" + ); + assert!(kv.scheduling_policy().cooperative()); + backend.iteration_scheduler.execute_iteration( + "concurrent-decode", + &[11, 12, 13], + &[], + None, + false, + skippy_runtime::IterationBatchPhase::Prefill, + )?; + let prompt = [1, 2, 3, 4, 5, 6, 7, 8].repeat(512); + let ids = InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("cooperative-long"), + true, + None, + ); + let session = ids.session_label.clone(); + let cancel = skippy_inference_api::CancellationToken::new(); + let worker_cancel = cancel.clone(); + let worker_backend = backend.clone(); + let worker_prompt = prompt.clone(); + let (finished_tx, finished_rx) = mpsc::channel(); + let worker = thread::spawn(move || { + let sampling = SamplingConfig { + enabled: false, + ..Default::default() + }; + let result = worker_backend.generate_local_tokens( + LocalGeneration { + prompt_token_ids: &worker_prompt, + recurrent_cache_prefix_token_ids: Some(&worker_prompt[..64]), + max_tokens: 1, + sampling: &sampling, + chat_sampling_metadata: None, + speculative: &speculative, + native_mtp_enabled: false, + hook_request: None, + hook_runtime: None, + cancellation: Some(&worker_cancel), + ids: &ids, + }, + |_| Ok(TokenControl::Continue), + ); + let _ = finished_tx.send(()); + result + }); + let mut pending = PendingPrefill { + cancellation: cancel, + worker: Some(worker), + }; + // Observe a real intermediate native position through the same scheduler. + // A serialized whole-prefill closure cannot satisfy this condition. + let deadline = Instant::now() + Duration::from_secs(30); + let observed = loop { + let session = session.clone(); + let position = backend + .iteration_scheduler + .execute_runtime("test-prefill-progress", move |rt| { + Ok(rt.session_token_count(&session).unwrap_or_default()) + })?; + if position >= 128 && position < prompt.len() as u64 { + break true; + } + if finished_rx.try_recv().is_ok() || Instant::now() >= deadline { + break false; + } + thread::yield_now(); + }; + let decode = if observed { + Some(backend.iteration_scheduler.execute_iteration( + "concurrent-decode", + &[14], + &[], + None, + true, + skippy_runtime::IterationBatchPhase::Decode, + )) + } else { + None + }; + let unfinished_at_decode = !pending.worker.as_ref().unwrap().is_finished(); + pending.cancellation.cancel(); + let result = pending + .worker + .take() + .unwrap() + .join() + .map_err(|_| anyhow::anyhow!("prefill worker panicked"))?; + assert!( + observed, + "the long prefill never yielded an intermediate scheduler boundary" + ); + decode.expect("concurrent decode attempted")?; + assert!( + unfinished_at_decode, + "decode did not complete before long prefill finished" + ); + let error = match result { + Err(error) => error, + Ok(_) => panic!("cancellation must terminate the unfinished prefill"), + }; + assert_eq!( + serde_json::to_value(error.body())?["error"]["code"], + "request_cancelled" + ); + kv.wait_for_exact_state_captures_idle(Duration::from_secs(30)) + .map_err(anyhow::Error::msg)?; + let check_session = session.clone(); + let remaining = + backend + .iteration_scheduler + .execute_runtime("test-cancel-cleanup", move |rt| { + let remaining = rt.session_token_count(&check_session).unwrap_or_default(); + rt.drop_session_timed("concurrent-decode") + .map_err(crate::frontend::util::openai_backend_error)?; + Ok(remaining) + })?; + assert_eq!( + remaining, 0, + "cancelled execution lane still owns prompt state" + ); + let base = backend.local_kv_message_base( + &session, + &InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("checkpoint-probe"), + true, + None, + ), + ); + let checkpoint = kv.prefill_identity(&backend.config, &base, 0, &prompt[..64]); + assert!( + kv.retained_exact_identity(&checkpoint.namespace, &prompt[..64]), + "cancellation lost the captured immutable checkpoint" + ); + assert_eq!( + kv.radix.lock().unwrap().stats().resident_pinned_tokens, + 0, + "checkpoint lease leaked after cancellation" + ); + Ok(()) +} diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs new file mode 100644 index 0000000000..ab983c010f --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -0,0 +1,175 @@ +//! Explicit real-model recurrent cache fixture, including admitted lane capacity. +use super::*; + +const RECURRENT_TEST_CHECKPOINT_RAM_BYTES: u64 = 8 * 1024 * 1024 * 1024; + +pub(super) fn recurrent_test_backend( + run_id: &str, + backend_model_id: &str, + ctx_size: usize, + batch_size: u32, + default_max_tokens: u32, + token_budget: usize, +) -> Result<(StageOpenAiBackend, SpeculativeDecodeConfig)> { + recurrent_test_backend_with_lanes( + run_id, + backend_model_id, + ctx_size, + batch_size, + default_max_tokens, + token_budget, + 1, + ) +} + +pub(super) fn recurrent_test_backend_with_lanes( + run_id: &str, + backend_model_id: &str, + ctx_size: usize, + batch_size: u32, + default_max_tokens: u32, + token_budget: usize, + lane_count: u32, +) -> Result<(StageOpenAiBackend, SpeculativeDecodeConfig)> { + skippy_runtime::test_support::require_native_runtime(); + let model_path = std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_MODEL").ok_or_else(|| { + anyhow::anyhow!("SKIPPY_RECURRENT_CACHE_TEST_MODEL is required for this ignored test") + })?; + let layer_count = + std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS").ok_or_else(|| { + anyhow::anyhow!( + "SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS is required for this ignored test" + ) + })?; + let layer_count = layer_count + .to_string_lossy() + .parse::() + .map_err(|error| anyhow::anyhow!("invalid recurrent cache test layer count: {error}"))?; + let config = StageConfig { + run_id: run_id.to_string(), + topology_id: run_id.to_string(), + model_id: std::env::var("SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID") + .unwrap_or_else(|_| "unsloth/Qwen3.5-0.8B-GGUF:Q6_K".to_string()), + package_ref: None, + manifest_sha256: None, + source_model_path: None, + source_model_sha256: None, + source_model_bytes: None, + materialized_path: None, + materialized_pinned: false, + model_path: Some(model_path.to_string_lossy().into_owned()), + projector_path: None, + stage_id: "stage-0".to_string(), + stage_index: 0, + layer_start: 0, + layer_end: layer_count, + ctx_size: u32::try_from(ctx_size) + .map_err(|error| anyhow::anyhow!("invalid recurrent test context size: {error}"))?, + lane_count, + n_batch: Some(batch_size), + n_ubatch: Some(batch_size), + n_gpu_layers: std::env::var("SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS") + .ok() + .map(|value| value.parse::()) + .transpose() + .map_err(|error| anyhow::anyhow!("invalid recurrent cache GPU layer count: {error}"))? + .unwrap_or(0), + mmap: Some(true), + mlock: false, + repack: false, + op_offload: None, + no_host_buffer: false, + check_tensors: false, + direct_io: false, + main_gpu: None, + split_mode: skippy_protocol::SplitMode::Auto, + cache_type_k: "f16".to_string(), + cache_type_v: "f16".to_string(), + flash_attn_type: Default::default(), + kv_offload: None, + kv_unified: None, + swa_full: None, + cache_idle_slots: None, + resident_tensor_names: Vec::new(), + selected_device: None, + kv_cache: Some(StageKvCacheConfig { + exact_max_bytes: None, + mode: StageKvCacheMode::LookupRecord, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: RECURRENT_TEST_CHECKPOINT_RAM_BYTES, + codec: skippy_protocol::StageKvCacheCodec::Native, + min_tokens: 1, + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + }), + native_mtp_enabled: false, + load_mode: LoadMode::RuntimeSlice, + bind_addr: "127.0.0.1:0".to_string(), + upstream: None, + downstream: None, + ..StageConfig::default() + }; + let runtime = load_runtime(&config)? + .ok_or_else(|| anyhow::anyhow!("recurrent cache test runtime was not loaded"))?; + let kv = KvStageIntegration::from_loaded_model( + &config, + crate::runtime_state::loaded_model_state_kind(Some(&runtime)), + crate::runtime_state::loaded_memory_cache_capabilities(Some(&runtime)), + None, + )? + .map(Arc::new) + .ok_or_else(|| anyhow::anyhow!("recurrent cache test did not enable KV integration"))?; + assert!( + kv.records_resident_prefixes(), + "fixture must exercise native prefix ownership" + ); + assert!( + kv.resident_requires_checkpoint(), + "fixture requires recurrent native memory" + ); + assert_eq!( + kv.resident_checkpoint_max_bytes, + RECURRENT_TEST_CHECKPOINT_RAM_BYTES + ); + assert_eq!(kv.resident_config.max_entries, 8); + let telemetry = Telemetry::new(None, 1, config.clone(), TelemetryLevel::Off); + let speculative = SpeculativeDecodeConfig::default(); + let iteration_scheduler = + IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; + let backend = StageOpenAiBackend { + runtime: runtime.clone(), + workload: Default::default(), + config, + telemetry, + model_id: backend_model_id.to_string(), + default_max_tokens, + request_defaults: EmbeddedOpenAiRequestDefaults::default(), + thinking: None, + ctx_size, + mode: InferenceBackendMode::LocalRuntime, + draft: None, + speculative_window: 0, + adaptive_speculative_window: false, + ngram_max: 0, + speculative: speculative.clone(), + speculation_governor: None, + runahead_governor: None, + generation_limit: Arc::new(GenerationConcurrencyController::fixed(lane_count as usize)), + generation_queue_depth: Arc::new(AtomicUsize::new(0)), + generation_queue_limit: 1, + generation_admission_timeout: std::time::Duration::from_secs(10), + generation_service_estimator: Arc::new(crate::frontend::GenerationServiceEstimator::new( + lane_count as usize, + )), + generation_session_locks: Arc::new(Mutex::new(std::collections::BTreeMap::new())), + generation_token_budget: Arc::new(GenerationTokenBudget::new(token_budget)), + hook_policy: None, + generation_receipt: None, + generation_lifecycle: None, + linear_proposal_ingress: None, + kv: Some(kv), + iteration_scheduler, + }; + Ok((backend, speculative)) +} diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index d02209dbc0..4b8d6f526a 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -24,6 +24,7 @@ use crate::frontend::util::openai_backend_error; use crate::frontend::util::saturating_u32; use crate::kv_integration::proactive_eviction_attrs; use crate::kv_integration::proactive_eviction_error_kind; +use crate::kv_integration::scheduling::CacheSchedulingPolicy; use crate::kv_integration::{KvStageIntegration, PrefillKvIdentity, StagePrefixCachePayload}; use crate::runtime_state::{RuntimeSessionStats, RuntimeState}; use axum::http::StatusCode; @@ -50,9 +51,11 @@ mod exact_state_recording; #[cfg(test)] pub(crate) use exact_state_recording::CaptureTaskOutstandingGuard; +mod cache_prefill; #[cfg(test)] pub(crate) mod capture_trace; mod kv_restore; +use cache_prefill::deferred_suffix_prefill_enabled; /// A `NaN` logprob marks a token whose raw logits row was unavailable when it /// was sampled. OpenAI clients expect numbers, so the request fails instead of @@ -343,49 +346,6 @@ fn scheduler_generation_driver_eligible( && !hooks_enabled } -fn deferred_suffix_prefill_enabled( - payload: Option, - max_tokens: u32, -) -> bool { - // Resident KV suffixes must remain in the serialized cache operation. Releasing - // it between restore and suffix prefill lets another request interleave and - // destroys prefill phase locality on a shared accelerator. - max_tokens > 0 - && matches!( - payload, - Some(StagePrefixCachePayload::KvRecurrent | StagePrefixCachePayload::FullState) - ) -} - -fn deferred_suffix_split( - restored_prefill_tokens: usize, - prompt_token_count: usize, - checkpoint_token_count: Option, -) -> (usize, Option) { - let suffix_start = restored_prefill_tokens.min(prompt_token_count); - let checkpoint = checkpoint_token_count - .filter(|&boundary| boundary > suffix_start && boundary < prompt_token_count); - (suffix_start, checkpoint) -} - -/// Pick the deferred-prefill checkpoint boundary. A valid EXPLICIT chat -/// boundary wins: it is the reusable message-history prefix a follow-up -/// request shares token-for-token, so it is the checkpoint most likely to be -/// on a future request's path. The shared-grid checkpoint is the fallback for -/// absent, invalid, or already-restored chat boundaries. -fn select_deferred_checkpoint_boundary( - shared_checkpoint: Option, - chat_checkpoint: Option, - restored_prefill_tokens: usize, - prompt_token_count: usize, -) -> Option { - let valid = - |boundary: &usize| *boundary > restored_prefill_tokens && *boundary < prompt_token_count; - chat_checkpoint - .filter(valid) - .or_else(|| shared_checkpoint.filter(valid)) -} - impl StageOpenAiBackend { pub(in crate::frontend) fn generate_local_tokens( &self, @@ -707,7 +667,10 @@ impl StageOpenAiBackend { if request.prompt_token_ids.len() > 1 { let chat_sampling_configured = if self.kv.as_ref().is_some_and(|kv| { kv.payload == StagePrefixCachePayload::ResidentKv - || deferred_suffix_prefill_enabled(Some(kv.payload), request.max_tokens) + || deferred_suffix_prefill_enabled( + Some(kv.scheduling_policy()), + request.max_tokens, + ) }) { if let Some(metadata) = request.chat_sampling_metadata { self.configure_chat_sampling( @@ -800,601 +763,6 @@ impl StageOpenAiBackend { Ok(prompt_prefill_sample) } - fn restore_or_record_kv( - &self, - request: &LocalGeneration<'_>, - session_id: &str, - cache_stats: &mut GenerationCacheStats, - ) -> InferenceResult> { - let prefill_timer = PhaseTimer::start(); - let prefill_tokens = - Arc::<[i32]>::from(&request.prompt_token_ids[..request.prompt_token_ids.len() - 1]); - let recurrent_cache_prefix_token_ids = request - .recurrent_cache_prefix_token_ids - .map(<[i32]>::to_vec); - let max_tokens = request.max_tokens; - let identity_timer = PhaseTimer::start(); - let (lookup_identities, refresh_cache_affinity) = match self.kv.as_ref() { - Some(kv) => { - let base = self.local_kv_message_base(session_id, request.ids); - let identities = Arc::<[PrefillKvIdentity]>::from(kv.lookup_identities( - &self.config, - &base, - 0, - prefill_tokens.as_ref(), - )); - let kv = kv.clone(); - let config = self.config.clone(); - let refresh_identities = Arc::clone(&identities); - ( - identities, - Box::new(move || kv.peek_cache_affinity(&config, &refresh_identities)) - as Box skippy_scheduler::CacheAffinity + Send>, - ) - } - None => ( - Arc::<[PrefillKvIdentity]>::from([]), - Box::new(skippy_scheduler::CacheAffinity::default) - as Box skippy_scheduler::CacheAffinity + Send>, - ), - }; - let kv_identity_ms = identity_timer.elapsed_ms(); - let cache_payload = self - .kv - .as_ref() - .map_or(StagePrefixCachePayload::Disabled, |kv| kv.payload); - let scheduler_backend = self.clone(); - let scheduler_session_id = session_id.to_string(); - let scheduler_ids = request.ids.clone(); - let scheduler_lookup_identities = Arc::clone(&lookup_identities); - let scheduler_prefill_tokens = Arc::clone(&prefill_tokens); - let record_prefill_tokens = Arc::clone(&prefill_tokens); - let mut scheduler_cache_stats = std::mem::take(cache_stats); - let cache_operation_deadline = cache_operation_deadline( - self.generation_admission_timeout, - request.prompt_token_ids.len(), - ); - let outcome = self.iteration_scheduler.execute_cache_aware_runtime_timed( - "feature-kv-restore-prefill-record", - super::super::iteration_scheduler::CacheAwareRuntimeRequest { - operation_id: request.ids.request_id_string(), - deadline: cache_operation_deadline, - cancellation: request.cancellation, - prompt_tokens: Arc::clone(&prefill_tokens), - priority: 0, - payload: cache_payload, - refresh_affinity: refresh_cache_affinity, - }, - move |runtime, cache_operation| { - let outcome = scheduler_backend.restore_or_record_kv_on_runtime( - runtime, - cache_operation, - &scheduler_ids, - &scheduler_session_id, - scheduler_prefill_tokens.as_ref(), - scheduler_lookup_identities.as_ref(), - kv_identity_ms, - recurrent_cache_prefix_token_ids.as_deref(), - max_tokens, - &mut scheduler_cache_stats, - )?; - Ok((outcome, scheduler_cache_stats)) - }, - )?; - let mut runtime_lock_wait_ms = outcome.runtime_lock_wait_ms; - let mut runtime_lock_hold_ms = outcome.runtime_lock_hold_ms; - let mut runtime_lock_acquires = 1usize; - let (outcome, updated_cache_stats) = outcome.value; - *cache_stats = updated_cache_stats; - let KvRestoreOutcome { - runtime_sessions_before, - mut runtime_sessions_after, - restored_prefill, - restored_prefill_tokens, - capacity, - mut record, - mut prompt_prefill_sample, - } = outcome; - let mut prefill_chunk_count = 1usize; - let mut scheduler_batch_size_max = 1usize; - let deferred_suffix_prefill = - deferred_suffix_prefill_enabled(self.kv.as_ref().map(|kv| kv.payload), max_tokens); - if deferred_suffix_prefill && capacity.admitted { - let exact_state = self - .kv - .as_ref() - .is_some_and(|kv| kv.payload_is_exact_state()); - let checkpoint = exact_state - .then(|| { - self.deferred_exact_checkpoint_identity( - request, - session_id, - &prefill_tokens, - restored_prefill_tokens, - ) - }) - .flatten(); - let (mut suffix_start, checkpoint_boundary) = deferred_suffix_split( - restored_prefill_tokens, - request.prompt_token_ids.len(), - checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()), - ); - if exact_state && let Some(boundary) = checkpoint_boundary { - let checkpoint_prefill = self.prefill_suffix( - session_id, - &request.prompt_token_ids[suffix_start..boundary], - None, - false, - cache_operation_deadline, - request.cancellation, - )?; - prefill_chunk_count = prefill_chunk_count - .saturating_add(checkpoint_prefill.chunk_count) - .saturating_sub(1); - scheduler_batch_size_max = - scheduler_batch_size_max.max(checkpoint_prefill.max_batch_size); - runtime_lock_wait_ms += checkpoint_prefill.runtime_lock_wait_ms; - runtime_lock_hold_ms += checkpoint_prefill.runtime_lock_hold_ms; - runtime_lock_acquires = - runtime_lock_acquires.saturating_add(checkpoint_prefill.chunk_count); - - if self.enqueue_exact_state_record_at_tokens( - session_id, - request.ids, - request.prompt_token_ids[..boundary].to_vec(), - "shared_prefill_checkpoint", - true, - ) { - record.resident_enqueued_checkpoints = - record.resident_enqueued_checkpoints.saturating_add(1); - } - suffix_start = boundary; - } - - let suffix_outcome = self.prefill_suffix( - session_id, - &request.prompt_token_ids[suffix_start..], - request.sampling.enabled.then_some(request.sampling), - true, - cache_operation_deadline, - request.cancellation, - )?; - prompt_prefill_sample = Some(suffix_outcome.predicted.ok_or_else(|| { - InferenceError::backend("deferred suffix prefill was not sampled") - })?); - prefill_chunk_count = if prefill_chunk_count == 1 { - suffix_outcome.chunk_count - } else { - prefill_chunk_count.saturating_add(suffix_outcome.chunk_count) - }; - scheduler_batch_size_max = scheduler_batch_size_max.max(suffix_outcome.max_batch_size); - runtime_lock_wait_ms += suffix_outcome.runtime_lock_wait_ms; - runtime_lock_hold_ms += suffix_outcome.runtime_lock_hold_ms; - runtime_lock_acquires = - runtime_lock_acquires.saturating_add(suffix_outcome.chunk_count); - - if exact_state { - // The final chunk samples the prompt's next token but leaves - // the native session at the full-prompt boundary. Exporting - // that state is useful for growing prompts, but is strictly - // best-effort after the preferred shared checkpoint above. - // Keep off-checkpoint states resident so every stage reopens - // from the same durable boundary after a restart. - if self.enqueue_exact_state_record_at_tokens( - session_id, - request.ids, - request.prompt_token_ids.to_vec(), - "final_prefill_state", - self.kv.as_ref().is_some_and(|kv| { - kv.full_exact_state_writes_through_l3(request.prompt_token_ids.len()) - }), - ) { - record.resident_enqueued_checkpoints = - record.resident_enqueued_checkpoints.saturating_add(1); - } - } else { - let scheduler_backend = self.clone(); - let scheduler_session_id = session_id.to_string(); - let scheduler_ids = request.ids.clone(); - let emit_debug = self.telemetry.is_debug_enabled(); - let record_outcome = self.iteration_scheduler.execute_runtime_timed_bounded( - "feature-kv-record", - request.ids.request_id_string(), - cache_operation_deadline, - request.cancellation, - move |runtime| { - let record = scheduler_backend.record_and_evict_kv( - runtime, - &scheduler_session_id, - &scheduler_ids, - record_prefill_tokens.as_ref(), - restored_prefill, - restored_prefill_tokens < record_prefill_tokens.len(), - ); - Ok((record, emit_debug.then(|| runtime.session_stats()))) - }, - )?; - runtime_lock_wait_ms += record_outcome.runtime_lock_wait_ms; - runtime_lock_hold_ms += record_outcome.runtime_lock_hold_ms; - runtime_lock_acquires = runtime_lock_acquires.saturating_add(1); - (record, runtime_sessions_after) = record_outcome.value; - } - } - if prompt_prefill_sample.is_some() { - cache_stats.suffix_prefill_tokens = saturating_u32( - request - .prompt_token_ids - .len() - .saturating_sub(restored_prefill_tokens), - ); - } - let prompt_tail_tokens = usize::from(prompt_prefill_sample.is_some()); - cache_stats.prompt_ms = prefill_timer.elapsed_ms(); - if self.telemetry.is_debug_enabled() { - let mut attrs = self.openai_attrs(request.ids); - attrs.insert( - "llama_stage.prefill_token_count".to_string(), - json!( - request - .prompt_token_ids - .len() - .saturating_sub(1) - .saturating_add(prompt_tail_tokens) - ), - ); - attrs.insert( - "llama_stage.prefill_chunk_count".to_string(), - json!(prefill_chunk_count), - ); - attrs.insert( - "skippy.scheduler.prefill_batch_size_max".to_string(), - json!(scheduler_batch_size_max), - ); - attrs.insert( - "skippy.kv.restored_prefill".to_string(), - json!(restored_prefill), - ); - attrs.insert( - "skippy.kv.restored_prefill_tokens".to_string(), - json!(restored_prefill_tokens), - ); - attrs.insert( - "skippy.kv.prefill_suffix_tokens".to_string(), - json!( - request - .prompt_token_ids - .len() - .saturating_sub(1) - .saturating_sub(restored_prefill_tokens) - .saturating_add(prompt_tail_tokens) - ), - ); - attrs.insert( - "skippy.kv.recorded_pages".to_string(), - json!(record.resident_recorded_pages), - ); - attrs.insert( - "skippy.kv.enqueued_checkpoint_pages".to_string(), - json!(record.resident_enqueued_checkpoints), - ); - insert_resident_capacity_attrs(&mut attrs, &capacity); - attrs.insert( - "llama_stage.runtime_lock_wait_ms".to_string(), - json!(runtime_lock_wait_ms), - ); - attrs.insert( - "llama_stage.runtime_lock_hold_ms".to_string(), - json!(runtime_lock_hold_ms), - ); - attrs.insert( - "llama_stage.runtime_lock_acquires".to_string(), - json!(runtime_lock_acquires), - ); - Self::insert_runtime_session_stats( - &mut attrs, - "llama_stage.runtime_sessions_before", - runtime_sessions_before - .as_ref() - .expect("debug session snapshot collected"), - ); - Self::insert_runtime_session_stats( - &mut attrs, - "llama_stage.runtime_sessions_after", - runtime_sessions_after - .as_ref() - .expect("debug session snapshot collected"), - ); - self.emit_openai_phase("stage.openai_prefill", prefill_timer, attrs); - } - self.telemetry.emit( - "stage.openai_kv_record_decision", - proactive_eviction_attrs( - record.proactive_eviction_status, - record.proactive_eviction_error_kind, - record.proactive_eviction_target_tokens, - record.proactive_evicted_entries, - record.proactive_evicted_tokens, - ), - ); - let mut capacity_attrs = self.openai_attrs(request.ids); - insert_resident_capacity_attrs(&mut capacity_attrs, &capacity); - self.telemetry - .emit("stage.openai_kv_capacity_decision", capacity_attrs); - if !capacity.admitted { - return Err(resident_capacity_admission_error(&capacity)); - } - if let Some(error) = record.proactive_eviction_error { - return Err(openai_backend_error(error)); - } - Ok(prompt_prefill_sample) - } - - fn deferred_exact_checkpoint_identity( - &self, - request: &LocalGeneration<'_>, - session_id: &str, - prefill_tokens: &[i32], - restored_prefill_tokens: usize, - ) -> Option { - let kv = self - .kv - .as_ref() - .filter(|kv| kv.retains_recurrent_checkpoints())?; - let base = self.local_kv_message_base(session_id, request.ids); - let shared_checkpoint = - kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); - let chat_checkpoint = request - .recurrent_cache_prefix_token_ids - .filter(|checkpoint_tokens| { - !checkpoint_tokens.is_empty() - && checkpoint_tokens.len() <= prefill_tokens.len() - && prefill_tokens.starts_with(checkpoint_tokens) - }) - .map(|checkpoint_tokens| { - kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens) - }); - let shared_boundary = shared_checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); - let chat_boundary = chat_checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); - let selected_boundary = select_deferred_checkpoint_boundary( - shared_boundary, - chat_boundary, - restored_prefill_tokens, - prefill_tokens.len().saturating_add(1), - ); - if selected_boundary == shared_boundary { - shared_checkpoint - } else { - chat_checkpoint - } - } - - #[allow(clippy::too_many_arguments)] - fn restore_or_record_kv_on_runtime( - &self, - runtime: &mut RuntimeState, - cache_operation: &CacheRuntimeContext, - ids: &InferenceGenerationIds, - session_id: &str, - prefill_tokens: &[i32], - lookup_identities: &[PrefillKvIdentity], - kv_identity_ms: f64, - recurrent_cache_prefix_token_ids: Option<&[i32]>, - max_tokens: u32, - cache_stats: &mut GenerationCacheStats, - ) -> InferenceResult { - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - let emit_debug = self.telemetry.is_debug_enabled(); - let runtime_sessions_before = emit_debug.then(|| runtime.session_stats()); - let (restored_prefill, restored_prefill_tokens, protected_resident_seq_id) = - if let Some(kv) = self.kv.as_ref() { - cache_stats.status = "miss"; - self.lookup_and_restore_kv( - kv, - runtime, - session_id, - ids, - prefill_tokens, - lookup_identities, - kv_identity_ms, - cache_stats, - ) - } else { - (false, 0, None) - }; - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - let capacity = if let Some(kv) = self.kv.as_ref() { - let decode_batch_tokens = u64::from(self.config.n_batch.unwrap_or(2048)); - let target_free_tokens = - decode_batch_tokens.saturating_add(u64::from(max_tokens).min(decode_batch_tokens)); - let request_tokens = if kv.payload == StagePrefixCachePayload::ResidentKv { - prefill_tokens - .len() - .saturating_sub(restored_prefill_tokens) - .saturating_add(usize::from(max_tokens > 0)) as u64 - } else { - prefill_tokens.len() as u64 - }; - kv.admit_resident_capacity( - runtime, - session_id, - request_tokens, - decode_batch_tokens, - target_free_tokens, - protected_resident_seq_id, - ) - .map_err(openai_backend_error)? - } else { - crate::kv_integration::ResidentCapacityDecision { - admitted: true, - ..crate::kv_integration::ResidentCapacityDecision::default() - } - }; - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - if !capacity.admitted { - return Ok(KvRestoreOutcome { - runtime_sessions_before, - runtime_sessions_after: emit_debug.then(|| runtime.session_stats()), - restored_prefill: false, - restored_prefill_tokens: 0, - capacity, - record: KvRecordResult::default(), - prompt_prefill_sample: None, - }); - } - let deferred_suffix_prefill = - deferred_suffix_prefill_enabled(self.kv.as_ref().map(|kv| kv.payload), max_tokens); - if deferred_suffix_prefill { - runtime - .ensure_session_active(session_id) - .map_err(openai_backend_error)?; - cache_stats.matched_prefix_tokens = saturating_u32(restored_prefill_tokens); - cache_stats.suffix_prefill_tokens = - saturating_u32(prefill_tokens.len().saturating_sub(restored_prefill_tokens)); - return Ok(KvRestoreOutcome { - runtime_sessions_before, - runtime_sessions_after: emit_debug.then(|| runtime.session_stats()), - restored_prefill, - restored_prefill_tokens, - capacity, - record: KvRecordResult::default(), - prompt_prefill_sample: None, - }); - } - let prompt_prefill_sample = None; - let mut decoded_prefill_suffix = false; - let cache_prefill_chunk_tokens = usize::try_from(self.config.n_ubatch.unwrap_or(256)) - .unwrap_or(2_048) - .clamp(1, 2_048); - if restored_prefill_tokens < prefill_tokens.len() { - decoded_prefill_suffix = true; - if let Some(checkpoint_tokens) = - recurrent_cache_prefix_token_ids.filter(|checkpoint_tokens| { - !checkpoint_tokens.is_empty() - && checkpoint_tokens.len() <= prefill_tokens.len() - && prefill_tokens.starts_with(checkpoint_tokens) - && restored_prefill_tokens < checkpoint_tokens.len() - }) - { - prefill_cache_chunks( - runtime, - session_id, - &checkpoint_tokens[restored_prefill_tokens..], - cache_prefill_chunk_tokens, - cache_operation, - )?; - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - // This branch is the max_tokens=0 prefill-only fallback. The - // chat-prefix state must be exported before this same runtime - // operation advances through the remaining suffix. A detached - // command cannot run until this operation releases the scheduler, - // by which point the canonical-position guard would reject the - // earlier checkpoint. Generation requests use the split, detached - // FIFO checkpoint path in `restore_or_record_kv` instead. - let _ = self.record_exact_state_at_tokens( - runtime, - session_id, - ids, - checkpoint_tokens, - "chat_prefix_checkpoint", - true, - ); - prefill_cache_chunks( - runtime, - session_id, - &prefill_tokens[checkpoint_tokens.len()..], - cache_prefill_chunk_tokens, - cache_operation, - )?; - } else if let Some(kv) = self.kv.as_ref().filter(|kv| kv.payload_is_exact_state()) { - // Recurrent and full-state payloads cannot reconstruct a shorter - // shared prefix from the state at the end of the request. Stop - // at the near-tail grid boundary while prefilling and snapshot - // native state there; the final exact state is recorded by - // `record_and_evict_kv` below. One checkpoint bounds both the - // extra prefill split and the very large recurrent-state export. - let base = self.local_kv_message_base(session_id, ids); - let checkpoint = - kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); - if let Some(identity) = checkpoint.filter(|identity| { - identity.identity.token_count as usize > restored_prefill_tokens - }) { - let boundary = identity.identity.token_count as usize; - prefill_cache_chunks( - runtime, - session_id, - &prefill_tokens[restored_prefill_tokens..boundary], - cache_prefill_chunk_tokens, - cache_operation, - )?; - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - let cold_prefill_cost = self - .generation_service_estimator - .estimated_prefill_ms(boundary); - let l3_cost = kv.l3_benefit_cost(cold_prefill_cost); - kv.record_exact_state_with_cost( - runtime, - session_id, - &identity, - crate::kv_integration::CaptureAdmission::BestEffort, - l3_cost, - ) - .map_err(openai_backend_error)?; - prefill_cache_chunks( - runtime, - session_id, - &prefill_tokens[boundary..], - cache_prefill_chunk_tokens, - cache_operation, - )?; - } else { - prefill_cache_chunks( - runtime, - session_id, - &prefill_tokens[restored_prefill_tokens..], - cache_prefill_chunk_tokens, - cache_operation, - )?; - } - } else { - prefill_cache_chunks( - runtime, - session_id, - &prefill_tokens[restored_prefill_tokens..], - cache_prefill_chunk_tokens, - cache_operation, - )?; - } - } - ensure_cache_operation_active(runtime, session_id, cache_operation)?; - cache_stats.matched_prefix_tokens = saturating_u32(restored_prefill_tokens); - cache_stats.suffix_prefill_tokens = - saturating_u32(prefill_tokens.len().saturating_sub(restored_prefill_tokens)); - let record = self.record_and_evict_kv( - runtime, - session_id, - ids, - prefill_tokens, - restored_prefill, - decoded_prefill_suffix, - ); - let runtime_sessions_after = emit_debug.then(|| runtime.session_stats()); - Ok(KvRestoreOutcome { - runtime_sessions_before, - runtime_sessions_after, - restored_prefill, - restored_prefill_tokens, - capacity, - record, - prompt_prefill_sample, - }) - } - fn configure_chat_sampling( &self, session_id: &str, @@ -1767,97 +1135,6 @@ fn default_local_text_serving_selects_iteration_scheduler() { )); } -#[cfg(test)] -#[test] -fn resident_kv_suffix_prefill_stays_inside_the_cache_operation() { - assert!(!deferred_suffix_prefill_enabled( - Some(StagePrefixCachePayload::ResidentKv), - 1, - )); -} - -#[cfg(test)] -#[test] -fn recurrent_suffix_prefill_requires_a_nonzero_generation_budget() { - assert!(deferred_suffix_prefill_enabled( - Some(StagePrefixCachePayload::KvRecurrent), - 1, - )); - assert!(deferred_suffix_prefill_enabled( - Some(StagePrefixCachePayload::FullState), - 1, - )); - assert!(!deferred_suffix_prefill_enabled( - Some(StagePrefixCachePayload::KvRecurrent), - 0, - )); - assert!(!deferred_suffix_prefill_enabled(None, 1)); -} - -#[cfg(test)] -#[test] -fn deferred_suffix_split_respects_restore_and_prompt_boundaries() { - assert_eq!(deferred_suffix_split(0, 10, Some(4)), (0, Some(4))); - assert_eq!(deferred_suffix_split(4, 10, Some(4)), (4, None)); - assert_eq!(deferred_suffix_split(8, 10, Some(4)), (8, None)); - assert_eq!(deferred_suffix_split(4, 10, Some(10)), (4, None)); - assert_eq!(deferred_suffix_split(99, 10, Some(4)), (10, None)); -} - -#[cfg(test)] -#[test] -fn deferred_checkpoint_prefers_chat_boundary_with_shared_grid_fallback() { - let prompt = 10; - // Both valid: the explicit chat boundary wins over the shared grid. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(6), 0, prompt), - Some(6) - ); - // Chat absent or None: shared grid is the fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), None, 0, prompt), - Some(8) - ); - // Chat already restored (equal to the restored prefix): shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(4), 4, prompt), - Some(8) - ); - // Chat at the prompt end: invalid, shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(10), 0, prompt), - Some(8) - ); - // Chat beyond the prompt: invalid, shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(99), 0, prompt), - Some(8) - ); - // Shared already restored but chat valid: chat wins. - assert_eq!( - select_deferred_checkpoint_boundary(Some(4), Some(6), 4, prompt), - Some(6) - ); - // Both invalid: nothing selected. - assert_eq!( - select_deferred_checkpoint_boundary(Some(4), Some(10), 4, prompt), - None - ); - // Neither candidate exists: nothing selected. - assert_eq!( - select_deferred_checkpoint_boundary(None, None, 0, prompt), - None - ); -} - -#[cfg(test)] -#[test] -fn deferred_exact_prefill_satisfies_the_recurrent_checkpoint_gate() { - assert!(initial_recurrent_checkpoint_attempted(true, Some(42))); - assert!(!initial_recurrent_checkpoint_attempted(true, None)); - assert!(initial_recurrent_checkpoint_attempted(false, None)); -} - #[cfg(test)] #[test] fn speculative_and_extended_serving_paths_select_the_scheduler_feature_driver() { diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs new file mode 100644 index 0000000000..a11800ca6e --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -0,0 +1,732 @@ +//! Checkpoint-aware prefill yields native iterations between exact boundaries. +use super::*; + +pub(super) fn deferred_suffix_prefill_enabled( + scheduling: Option, + max_tokens: u32, +) -> bool { + max_tokens > 0 && scheduling.is_some_and(CacheSchedulingPolicy::cooperative) +} + +fn deferred_suffix_split( + restored_prefill_tokens: usize, + prompt_token_count: usize, + checkpoint_token_count: Option, +) -> (usize, Option) { + let suffix_start = restored_prefill_tokens.min(prompt_token_count); + let checkpoint = checkpoint_token_count + .filter(|&boundary| boundary > suffix_start && boundary < prompt_token_count); + (suffix_start, checkpoint) +} + +/// Pick the deferred-prefill checkpoint boundary. A valid EXPLICIT chat +/// boundary wins: it is the reusable message-history prefix a follow-up +/// request shares token-for-token, so it is the checkpoint most likely to be +/// on a future request's path. The shared-grid checkpoint is the fallback for +/// absent, invalid, or already-restored chat boundaries. +fn select_deferred_checkpoint_boundary( + shared_checkpoint: Option, + chat_checkpoint: Option, + restored_prefill_tokens: usize, + prompt_token_count: usize, +) -> Option { + let valid = + |boundary: &usize| *boundary > restored_prefill_tokens && *boundary < prompt_token_count; + chat_checkpoint + .filter(valid) + .or_else(|| shared_checkpoint.filter(valid)) +} + +impl StageOpenAiBackend { + pub(super) fn restore_or_record_kv( + &self, + request: &LocalGeneration<'_>, + session_id: &str, + cache_stats: &mut GenerationCacheStats, + ) -> InferenceResult> { + let prefill_timer = PhaseTimer::start(); + let prefill_tokens = + Arc::<[i32]>::from(&request.prompt_token_ids[..request.prompt_token_ids.len() - 1]); + let recurrent_cache_prefix_token_ids = request + .recurrent_cache_prefix_token_ids + .map(<[i32]>::to_vec); + let max_tokens = request.max_tokens; + let identity_timer = PhaseTimer::start(); + let (lookup_identities, refresh_cache_affinity) = match self.kv.as_ref() { + Some(kv) => { + let base = self.local_kv_message_base(session_id, request.ids); + let identities = Arc::<[PrefillKvIdentity]>::from(kv.lookup_identities( + &self.config, + &base, + 0, + prefill_tokens.as_ref(), + )); + let kv = kv.clone(); + let config = self.config.clone(); + let refresh_identities = Arc::clone(&identities); + ( + identities, + Box::new(move || kv.peek_cache_affinity(&config, &refresh_identities)) + as Box skippy_scheduler::CacheAffinity + Send>, + ) + } + None => ( + Arc::<[PrefillKvIdentity]>::from([]), + Box::new(skippy_scheduler::CacheAffinity::default) + as Box skippy_scheduler::CacheAffinity + Send>, + ), + }; + let kv_identity_ms = identity_timer.elapsed_ms(); + let cache_scheduling = self + .kv + .as_ref() + .map_or(CacheSchedulingPolicy::Serialized, |kv| { + kv.scheduling_policy() + }); + let scheduler_backend = self.clone(); + let scheduler_session_id = session_id.to_string(); + let scheduler_ids = request.ids.clone(); + let scheduler_lookup_identities = Arc::clone(&lookup_identities); + let scheduler_prefill_tokens = Arc::clone(&prefill_tokens); + let record_prefill_tokens = Arc::clone(&prefill_tokens); + let mut scheduler_cache_stats = std::mem::take(cache_stats); + let cache_operation_deadline = cache_operation_deadline( + self.generation_admission_timeout, + request.prompt_token_ids.len(), + ); + let outcome = self.iteration_scheduler.execute_cache_aware_runtime_timed( + "feature-kv-restore-prefill-record", + crate::frontend::iteration_scheduler::cache_runtime::CacheAwareRuntimeRequest { + operation_id: request.ids.request_id_string(), + deadline: cache_operation_deadline, + cancellation: request.cancellation, + prompt_tokens: Arc::clone(&prefill_tokens), + priority: 0, + scheduling: cache_scheduling, + refresh_affinity: refresh_cache_affinity, + }, + move |runtime, cache_operation| { + let outcome = scheduler_backend.restore_or_record_kv_on_runtime( + runtime, + cache_operation, + &scheduler_ids, + &scheduler_session_id, + scheduler_prefill_tokens.as_ref(), + scheduler_lookup_identities.as_ref(), + kv_identity_ms, + recurrent_cache_prefix_token_ids.as_deref(), + max_tokens, + &mut scheduler_cache_stats, + )?; + Ok((outcome, scheduler_cache_stats)) + }, + )?; + let mut runtime_lock_wait_ms = outcome.runtime_lock_wait_ms; + let mut runtime_lock_hold_ms = outcome.runtime_lock_hold_ms; + let mut runtime_lock_acquires = 1usize; + let (outcome, updated_cache_stats) = outcome.value; + *cache_stats = updated_cache_stats; + let KvRestoreOutcome { + runtime_sessions_before, + mut runtime_sessions_after, + restored_prefill, + restored_prefill_tokens, + capacity, + mut record, + mut prompt_prefill_sample, + } = outcome; + let mut prefill_chunk_count = 1usize; + let mut scheduler_batch_size_max = 1usize; + let deferred_suffix_prefill = deferred_suffix_prefill_enabled( + self.kv.as_ref().map(|kv| kv.scheduling_policy()), + max_tokens, + ); + if deferred_suffix_prefill && capacity.admitted { + let exact_state = self + .kv + .as_ref() + .is_some_and(|kv| kv.retains_recurrent_checkpoints()); + let checkpoint = exact_state + .then(|| { + self.deferred_exact_checkpoint_identity( + request, + session_id, + &prefill_tokens, + restored_prefill_tokens, + ) + }) + .flatten(); + let (mut suffix_start, checkpoint_boundary) = deferred_suffix_split( + restored_prefill_tokens, + request.prompt_token_ids.len(), + checkpoint + .as_ref() + .and_then(|identity| usize::try_from(identity.identity.token_count).ok()), + ); + if exact_state && let Some(boundary) = checkpoint_boundary { + let checkpoint_prefill = self.prefill_suffix( + session_id, + &request.prompt_token_ids[suffix_start..boundary], + None, + false, + cache_operation_deadline, + request.cancellation, + )?; + prefill_chunk_count = prefill_chunk_count + .saturating_add(checkpoint_prefill.chunk_count) + .saturating_sub(1); + scheduler_batch_size_max = + scheduler_batch_size_max.max(checkpoint_prefill.max_batch_size); + runtime_lock_wait_ms += checkpoint_prefill.runtime_lock_wait_ms; + runtime_lock_hold_ms += checkpoint_prefill.runtime_lock_hold_ms; + runtime_lock_acquires = + runtime_lock_acquires.saturating_add(checkpoint_prefill.chunk_count); + + if self.enqueue_exact_state_record_at_tokens( + session_id, + request.ids, + request.prompt_token_ids[..boundary].to_vec(), + "shared_prefill_checkpoint", + true, + ) { + record.resident_enqueued_checkpoints = + record.resident_enqueued_checkpoints.saturating_add(1); + } + suffix_start = boundary; + } + + let suffix_outcome = self.prefill_suffix( + session_id, + &request.prompt_token_ids[suffix_start..], + request.sampling.enabled.then_some(request.sampling), + true, + cache_operation_deadline, + request.cancellation, + )?; + prompt_prefill_sample = Some(suffix_outcome.predicted.ok_or_else(|| { + InferenceError::backend("deferred suffix prefill was not sampled") + })?); + prefill_chunk_count = if prefill_chunk_count == 1 { + suffix_outcome.chunk_count + } else { + prefill_chunk_count.saturating_add(suffix_outcome.chunk_count) + }; + scheduler_batch_size_max = scheduler_batch_size_max.max(suffix_outcome.max_batch_size); + runtime_lock_wait_ms += suffix_outcome.runtime_lock_wait_ms; + runtime_lock_hold_ms += suffix_outcome.runtime_lock_hold_ms; + runtime_lock_acquires = + runtime_lock_acquires.saturating_add(suffix_outcome.chunk_count); + + if exact_state { + // The final chunk samples the prompt's next token but leaves + // the native session at the full-prompt boundary. Exporting + // that state is useful for growing prompts, but is strictly + // best-effort after the preferred shared checkpoint above. + // Keep off-checkpoint states resident so every stage reopens + // from the same durable boundary after a restart. + if self.enqueue_exact_state_record_at_tokens( + session_id, + request.ids, + request.prompt_token_ids.to_vec(), + "final_prefill_state", + self.kv.as_ref().is_some_and(|kv| { + kv.full_exact_state_writes_through_l3(request.prompt_token_ids.len()) + }), + ) { + record.resident_enqueued_checkpoints = + record.resident_enqueued_checkpoints.saturating_add(1); + } + } else { + let scheduler_backend = self.clone(); + let scheduler_session_id = session_id.to_string(); + let scheduler_ids = request.ids.clone(); + let emit_debug = self.telemetry.is_debug_enabled(); + let record_outcome = self.iteration_scheduler.execute_runtime_timed_bounded( + "feature-kv-record", + request.ids.request_id_string(), + cache_operation_deadline, + request.cancellation, + move |runtime| { + let record = scheduler_backend.record_and_evict_kv( + runtime, + &scheduler_session_id, + &scheduler_ids, + record_prefill_tokens.as_ref(), + restored_prefill, + restored_prefill_tokens < record_prefill_tokens.len(), + ); + Ok((record, emit_debug.then(|| runtime.session_stats()))) + }, + )?; + runtime_lock_wait_ms += record_outcome.runtime_lock_wait_ms; + runtime_lock_hold_ms += record_outcome.runtime_lock_hold_ms; + runtime_lock_acquires = runtime_lock_acquires.saturating_add(1); + (record, runtime_sessions_after) = record_outcome.value; + } + } + if prompt_prefill_sample.is_some() { + cache_stats.suffix_prefill_tokens = saturating_u32( + request + .prompt_token_ids + .len() + .saturating_sub(restored_prefill_tokens), + ); + } + let prompt_tail_tokens = usize::from(prompt_prefill_sample.is_some()); + cache_stats.prompt_ms = prefill_timer.elapsed_ms(); + if self.telemetry.is_debug_enabled() { + let mut attrs = self.openai_attrs(request.ids); + attrs.insert( + "llama_stage.prefill_token_count".to_string(), + json!( + request + .prompt_token_ids + .len() + .saturating_sub(1) + .saturating_add(prompt_tail_tokens) + ), + ); + attrs.insert( + "llama_stage.prefill_chunk_count".to_string(), + json!(prefill_chunk_count), + ); + attrs.insert( + "skippy.scheduler.prefill_batch_size_max".to_string(), + json!(scheduler_batch_size_max), + ); + attrs.insert( + "skippy.kv.restored_prefill".to_string(), + json!(restored_prefill), + ); + attrs.insert( + "skippy.kv.restored_prefill_tokens".to_string(), + json!(restored_prefill_tokens), + ); + attrs.insert( + "skippy.kv.prefill_suffix_tokens".to_string(), + json!( + request + .prompt_token_ids + .len() + .saturating_sub(1) + .saturating_sub(restored_prefill_tokens) + .saturating_add(prompt_tail_tokens) + ), + ); + attrs.insert( + "skippy.kv.recorded_pages".to_string(), + json!(record.resident_recorded_pages), + ); + attrs.insert( + "skippy.kv.enqueued_checkpoint_pages".to_string(), + json!(record.resident_enqueued_checkpoints), + ); + insert_resident_capacity_attrs(&mut attrs, &capacity); + attrs.insert( + "llama_stage.runtime_lock_wait_ms".to_string(), + json!(runtime_lock_wait_ms), + ); + attrs.insert( + "llama_stage.runtime_lock_hold_ms".to_string(), + json!(runtime_lock_hold_ms), + ); + attrs.insert( + "llama_stage.runtime_lock_acquires".to_string(), + json!(runtime_lock_acquires), + ); + Self::insert_runtime_session_stats( + &mut attrs, + "llama_stage.runtime_sessions_before", + runtime_sessions_before + .as_ref() + .expect("debug session snapshot collected"), + ); + Self::insert_runtime_session_stats( + &mut attrs, + "llama_stage.runtime_sessions_after", + runtime_sessions_after + .as_ref() + .expect("debug session snapshot collected"), + ); + self.emit_openai_phase("stage.openai_prefill", prefill_timer, attrs); + } + self.telemetry.emit( + "stage.openai_kv_record_decision", + proactive_eviction_attrs( + record.proactive_eviction_status, + record.proactive_eviction_error_kind, + record.proactive_eviction_target_tokens, + record.proactive_evicted_entries, + record.proactive_evicted_tokens, + ), + ); + let mut capacity_attrs = self.openai_attrs(request.ids); + insert_resident_capacity_attrs(&mut capacity_attrs, &capacity); + self.telemetry + .emit("stage.openai_kv_capacity_decision", capacity_attrs); + if !capacity.admitted { + return Err(resident_capacity_admission_error(&capacity)); + } + if let Some(error) = record.proactive_eviction_error { + return Err(openai_backend_error(error)); + } + Ok(prompt_prefill_sample) + } + + fn deferred_exact_checkpoint_identity( + &self, + request: &LocalGeneration<'_>, + session_id: &str, + prefill_tokens: &[i32], + restored_prefill_tokens: usize, + ) -> Option { + let kv = self + .kv + .as_ref() + .filter(|kv| kv.retains_recurrent_checkpoints())?; + let base = self.local_kv_message_base(session_id, request.ids); + let shared_checkpoint = + kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); + let chat_checkpoint = request + .recurrent_cache_prefix_token_ids + .filter(|checkpoint_tokens| { + !checkpoint_tokens.is_empty() + && checkpoint_tokens.len() <= prefill_tokens.len() + && prefill_tokens.starts_with(checkpoint_tokens) + }) + .map(|checkpoint_tokens| { + kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens) + }); + let shared_boundary = shared_checkpoint + .as_ref() + .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); + let chat_boundary = chat_checkpoint + .as_ref() + .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); + let selected_boundary = select_deferred_checkpoint_boundary( + shared_boundary, + chat_boundary, + restored_prefill_tokens, + prefill_tokens.len().saturating_add(1), + ); + if selected_boundary == shared_boundary { + shared_checkpoint + } else { + chat_checkpoint + } + } + + #[allow(clippy::too_many_arguments)] + fn restore_or_record_kv_on_runtime( + &self, + runtime: &mut RuntimeState, + cache_operation: &CacheRuntimeContext, + ids: &InferenceGenerationIds, + session_id: &str, + prefill_tokens: &[i32], + lookup_identities: &[PrefillKvIdentity], + kv_identity_ms: f64, + recurrent_cache_prefix_token_ids: Option<&[i32]>, + max_tokens: u32, + cache_stats: &mut GenerationCacheStats, + ) -> InferenceResult { + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + let emit_debug = self.telemetry.is_debug_enabled(); + let runtime_sessions_before = emit_debug.then(|| runtime.session_stats()); + let (restored_prefill, restored_prefill_tokens, protected_resident_seq_id) = + if let Some(kv) = self.kv.as_ref() { + cache_stats.status = "miss"; + self.lookup_and_restore_kv( + kv, + runtime, + session_id, + ids, + prefill_tokens, + lookup_identities, + kv_identity_ms, + cache_stats, + ) + } else { + (false, 0, None) + }; + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + let capacity = if let Some(kv) = self.kv.as_ref() { + let decode_batch_tokens = u64::from(self.config.n_batch.unwrap_or(2048)); + let target_free_tokens = + decode_batch_tokens.saturating_add(u64::from(max_tokens).min(decode_batch_tokens)); + let request_tokens = if kv.payload == StagePrefixCachePayload::ResidentKv { + prefill_tokens + .len() + .saturating_sub(restored_prefill_tokens) + .saturating_add(usize::from(max_tokens > 0)) as u64 + } else { + prefill_tokens.len() as u64 + }; + kv.admit_resident_capacity( + runtime, + session_id, + request_tokens, + decode_batch_tokens, + target_free_tokens, + protected_resident_seq_id, + ) + .map_err(openai_backend_error)? + } else { + crate::kv_integration::ResidentCapacityDecision { + admitted: true, + ..crate::kv_integration::ResidentCapacityDecision::default() + } + }; + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + if !capacity.admitted { + return Ok(KvRestoreOutcome { + runtime_sessions_before, + runtime_sessions_after: emit_debug.then(|| runtime.session_stats()), + restored_prefill: false, + restored_prefill_tokens: 0, + capacity, + record: KvRecordResult::default(), + prompt_prefill_sample: None, + }); + } + let deferred_suffix_prefill = deferred_suffix_prefill_enabled( + self.kv.as_ref().map(|kv| kv.scheduling_policy()), + max_tokens, + ); + if deferred_suffix_prefill { + runtime + .ensure_session_active(session_id) + .map_err(openai_backend_error)?; + cache_stats.matched_prefix_tokens = saturating_u32(restored_prefill_tokens); + cache_stats.suffix_prefill_tokens = + saturating_u32(prefill_tokens.len().saturating_sub(restored_prefill_tokens)); + return Ok(KvRestoreOutcome { + runtime_sessions_before, + runtime_sessions_after: emit_debug.then(|| runtime.session_stats()), + restored_prefill, + restored_prefill_tokens, + capacity, + record: KvRecordResult::default(), + prompt_prefill_sample: None, + }); + } + let prompt_prefill_sample = None; + let mut decoded_prefill_suffix = false; + let cache_prefill_chunk_tokens = usize::try_from(self.config.n_ubatch.unwrap_or(256)) + .unwrap_or(2_048) + .clamp(1, 2_048); + if restored_prefill_tokens < prefill_tokens.len() { + decoded_prefill_suffix = true; + if let Some(checkpoint_tokens) = + recurrent_cache_prefix_token_ids.filter(|checkpoint_tokens| { + !checkpoint_tokens.is_empty() + && checkpoint_tokens.len() <= prefill_tokens.len() + && prefill_tokens.starts_with(checkpoint_tokens) + && restored_prefill_tokens < checkpoint_tokens.len() + }) + { + prefill_cache_chunks( + runtime, + session_id, + &checkpoint_tokens[restored_prefill_tokens..], + cache_prefill_chunk_tokens, + cache_operation, + )?; + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + // This branch is the max_tokens=0 prefill-only fallback. The + // chat-prefix state must be exported before this same runtime + // operation advances through the remaining suffix. A detached + // command cannot run until this operation releases the scheduler, + // by which point the canonical-position guard would reject the + // earlier checkpoint. Generation requests use the split, detached + // FIFO checkpoint path in `restore_or_record_kv` instead. + let _ = self.record_exact_state_at_tokens( + runtime, + session_id, + ids, + checkpoint_tokens, + "chat_prefix_checkpoint", + true, + ); + prefill_cache_chunks( + runtime, + session_id, + &prefill_tokens[checkpoint_tokens.len()..], + cache_prefill_chunk_tokens, + cache_operation, + )?; + } else if let Some(kv) = self.kv.as_ref().filter(|kv| kv.payload_is_exact_state()) { + // Recurrent and full-state payloads cannot reconstruct a shorter + // shared prefix from the state at the end of the request. Stop + // at the near-tail grid boundary while prefilling and snapshot + // native state there; the final exact state is recorded by + // `record_and_evict_kv` below. One checkpoint bounds both the + // extra prefill split and the very large recurrent-state export. + let base = self.local_kv_message_base(session_id, ids); + let checkpoint = + kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); + if let Some(identity) = checkpoint.filter(|identity| { + identity.identity.token_count as usize > restored_prefill_tokens + }) { + let boundary = identity.identity.token_count as usize; + prefill_cache_chunks( + runtime, + session_id, + &prefill_tokens[restored_prefill_tokens..boundary], + cache_prefill_chunk_tokens, + cache_operation, + )?; + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + let cold_prefill_cost = self + .generation_service_estimator + .estimated_prefill_ms(boundary); + let l3_cost = kv.l3_benefit_cost(cold_prefill_cost); + kv.record_exact_state_with_cost( + runtime, + session_id, + &identity, + crate::kv_integration::CaptureAdmission::BestEffort, + l3_cost, + ) + .map_err(openai_backend_error)?; + prefill_cache_chunks( + runtime, + session_id, + &prefill_tokens[boundary..], + cache_prefill_chunk_tokens, + cache_operation, + )?; + } else { + prefill_cache_chunks( + runtime, + session_id, + &prefill_tokens[restored_prefill_tokens..], + cache_prefill_chunk_tokens, + cache_operation, + )?; + } + } else { + prefill_cache_chunks( + runtime, + session_id, + &prefill_tokens[restored_prefill_tokens..], + cache_prefill_chunk_tokens, + cache_operation, + )?; + } + } + ensure_cache_operation_active(runtime, session_id, cache_operation)?; + cache_stats.matched_prefix_tokens = saturating_u32(restored_prefill_tokens); + cache_stats.suffix_prefill_tokens = + saturating_u32(prefill_tokens.len().saturating_sub(restored_prefill_tokens)); + let record = self.record_and_evict_kv( + runtime, + session_id, + ids, + prefill_tokens, + restored_prefill, + decoded_prefill_suffix, + ); + let runtime_sessions_after = emit_debug.then(|| runtime.session_stats()); + Ok(KvRestoreOutcome { + runtime_sessions_before, + runtime_sessions_after, + restored_prefill, + restored_prefill_tokens, + capacity, + record, + prompt_prefill_sample, + }) + } +} + +#[cfg(test)] +#[test] +fn resident_kv_suffix_prefill_stays_inside_the_cache_operation() { + assert!(!deferred_suffix_prefill_enabled( + Some(CacheSchedulingPolicy::Serialized), + 1, + )); +} + +#[cfg(test)] +#[test] +fn recurrent_suffix_prefill_requires_a_nonzero_generation_budget() { + assert!(deferred_suffix_prefill_enabled( + Some(CacheSchedulingPolicy::Cooperative), + 1, + )); + assert!(deferred_suffix_prefill_enabled( + Some(CacheSchedulingPolicy::Cooperative), + 1, + )); + assert!(!deferred_suffix_prefill_enabled( + Some(CacheSchedulingPolicy::Cooperative), + 0, + )); + assert!(!deferred_suffix_prefill_enabled(None, 1)); +} + +#[cfg(test)] +#[test] +fn deferred_suffix_split_respects_restore_and_prompt_boundaries() { + assert_eq!(deferred_suffix_split(0, 10, Some(4)), (0, Some(4))); + assert_eq!(deferred_suffix_split(4, 10, Some(4)), (4, None)); + assert_eq!(deferred_suffix_split(8, 10, Some(4)), (8, None)); + assert_eq!(deferred_suffix_split(4, 10, Some(10)), (4, None)); + assert_eq!(deferred_suffix_split(99, 10, Some(4)), (10, None)); +} + +#[cfg(test)] +#[test] +fn deferred_checkpoint_prefers_chat_boundary_with_shared_grid_fallback() { + let prompt = 10; + // Both valid: the explicit chat boundary wins over the shared grid. + assert_eq!( + select_deferred_checkpoint_boundary(Some(8), Some(6), 0, prompt), + Some(6) + ); + // Chat absent or None: shared grid is the fallback. + assert_eq!( + select_deferred_checkpoint_boundary(Some(8), None, 0, prompt), + Some(8) + ); + // Chat already restored (equal to the restored prefix): shared fallback. + assert_eq!( + select_deferred_checkpoint_boundary(Some(8), Some(4), 4, prompt), + Some(8) + ); + // Chat at the prompt end: invalid, shared fallback. + assert_eq!( + select_deferred_checkpoint_boundary(Some(8), Some(10), 0, prompt), + Some(8) + ); + // Chat beyond the prompt: invalid, shared fallback. + assert_eq!( + select_deferred_checkpoint_boundary(Some(8), Some(99), 0, prompt), + Some(8) + ); + // Shared already restored but chat valid: chat wins. + assert_eq!( + select_deferred_checkpoint_boundary(Some(4), Some(6), 4, prompt), + Some(6) + ); + // Both invalid: nothing selected. + assert_eq!( + select_deferred_checkpoint_boundary(Some(4), Some(10), 4, prompt), + None + ); + // Neither candidate exists: nothing selected. + assert_eq!( + select_deferred_checkpoint_boundary(None, None, 0, prompt), + None + ); +} + +#[cfg(test)] +#[test] +fn deferred_exact_prefill_satisfies_the_recurrent_checkpoint_gate() { + assert!(initial_recurrent_checkpoint_attempted(true, Some(42))); + assert!(!initial_recurrent_checkpoint_attempted(true, None)); + assert!(initial_recurrent_checkpoint_attempted(false, None)); +} diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs index 9c70d65652..4ba01698e2 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs @@ -21,12 +21,26 @@ impl StageOpenAiBackend { let estimated_cold_prefill_ms = self .generation_service_estimator .estimated_prefill_ms(prefill_tokens.len()); - match kv.restore_exact_state_with_cold_cost( + let exact = kv.restore_exact_state_with_cold_cost( runtime, session_id, identities, estimated_cold_prefill_ms, - ) { + ); + let exact = match exact { + Err(error) + if kv.records_resident_prefixes() + && matches!(runtime.canonical_session_position(session_id), Ok(0)) => + { + self.emit_kv_restore_error(ids, "exact_error", &error); + // Retry only after verifying the native, Rust-session and tracked + // positions are all zero. A discarded or unverifiable lane + // stays on the existing error path. + Ok(None) + } + result => result, + }; + match exact { Ok(Some(restored)) => { restored_prefill = true; cache_stats.status = "hit"; @@ -153,16 +167,7 @@ impl StageOpenAiBackend { } } } - Err(error) => { - let mut attrs = self.openai_attrs(ids); - attrs.insert("skippy.kv.decision".to_string(), json!("exact_error")); - attrs.insert( - "skippy.kv.error_class".to_string(), - json!(crate::kv_integration::telemetry_error_class(&error)), - ); - self.telemetry - .emit("stage.openai_kv_lookup_decision", attrs); - } + Err(error) => self.emit_kv_restore_error(ids, "exact_error", &error), } if cache_stats.cached_prompt_tokens > 0 { cache_stats.restore_ms = kv_restore_started.elapsed().as_secs_f64() * 1_000.0; @@ -344,4 +349,19 @@ impl StageOpenAiBackend { proactive_eviction_error, } } + fn emit_kv_restore_error( + &self, + ids: &InferenceGenerationIds, + decision: &str, + error: &anyhow::Error, + ) { + let mut attrs = self.openai_attrs(ids); + attrs.insert("skippy.kv.decision".to_string(), json!(decision)); + attrs.insert( + "skippy.kv.error_class".to_string(), + json!(crate::kv_integration::telemetry_error_class(error)), + ); + self.telemetry + .emit("stage.openai_kv_lookup_decision", attrs); + } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index e31a70774e..7ee9399baa 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -14,6 +14,8 @@ use super::{ const MAX_PREFIX_PROBES: usize = 64; +mod resident_preference; +use resident_preference::DurableRestoreLookup; mod restore; mod snapshot_headroom; @@ -187,16 +189,8 @@ impl KvStageIntegration { if !self.should_lookup() || self.exact_state_payload().is_none() { return Ok(None); } - // Persistent storage is the cold floor. A usable native prefix always - // stays on its shared-memory path; a warm hit never reads full KV bytes. - if self.records_resident_prefixes() - && identities - .iter() - .any(|identity| self.probe_resident_prefix(identity).is_some()) - { - return Ok(None); - } - for identity in identities { + for candidate in self.ordered_restore_candidates(identities, shared_durable_fallback) { + let identity = candidate.identity; let lookup_started = Instant::now(); let (lookup, entries) = { let mut radix = self @@ -222,9 +216,12 @@ impl KvStageIntegration { runtime, session_id, identity, - lookup_started, + DurableRestoreLookup { + started: lookup_started, + location: candidate.location.as_ref(), + shared_fallback: shared_durable_fallback, + }, cold_prefill_cost, - shared_durable_fallback, )? { return restore::finish_restore(runtime, session_id, identity, restored); } @@ -691,9 +688,8 @@ impl KvStageIntegration { runtime: &mut RuntimeState, session_id: &str, identity: &PrefillKvIdentity, - lookup_started: Instant, + lookup: DurableRestoreLookup<'_>, cold_prefill_cost: Option, - shared_durable_fallback: bool, ) -> Result> { let Some(l3) = &self.l3 else { return Ok(None); @@ -702,23 +698,26 @@ impl KvStageIntegration { // load on the located entry's manifest key: same-length queries for // different prefixes never suppress each other, and different-length // queries resolving to one entry never load it twice. - let durable_token_ids = if shared_durable_fallback { + let durable_token_ids = if lookup.shared_fallback { self.durable_exact_lookup_token_ids(&identity.token_ids) } else { &identity.token_ids }; - let location = + let location = if let Some(location) = lookup.location { + location.clone() + } else { match l3.locate_longest(&identity.namespace, durable_token_ids, MAX_PREFIX_PROBES) { Ok(Some(location)) => location, // Nothing stored, or a corrupt / identity-mismatched entry. // Either way the miss path is the safe one; the tier has // recorded the reason for the status surface. Ok(None) | Err(_) => return Ok(None), - }; + } + }; // L3 remains the authority for L2: locate and validate the current // manifest identity before a host-RAM mirror may serve the request. if let Some(restored) = - self.restore_from_l2(runtime, session_id, identity, &location, lookup_started)? + self.restore_from_l2(runtime, session_id, identity, &location, lookup.started)? { return Ok(Some(restored)); } @@ -740,7 +739,7 @@ impl KvStageIntegration { runtime, session_id, identity, - lookup_started, + lookup.started, l3, &location, cold_prefill_cost, @@ -1177,7 +1176,7 @@ mod tests { } } - fn native_desc() -> skippy_runtime::RuntimeKvPageDesc { + pub(super) fn native_desc() -> skippy_runtime::RuntimeKvPageDesc { skippy_runtime::RuntimeKvPageDesc { version: 1, layer_start: 0, diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs new file mode 100644 index 0000000000..dcaacd88d1 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -0,0 +1,163 @@ +//! Compare token metadata before choosing a warm alias or loading durable bytes. +use super::*; + +pub(super) struct RestoreCandidate<'a> { + pub(super) identity: &'a PrefillKvIdentity, + pub(super) location: Option, +} + +pub(super) struct DurableRestoreLookup<'a> { + pub(super) started: Instant, + pub(super) location: Option<&'a skippy_cache::L3Location>, + pub(super) shared_fallback: bool, +} + +impl KvStageIntegration { + pub(super) fn ordered_restore_candidates<'a>( + &self, + identities: &'a [PrefillKvIdentity], + shared_durable_fallback: bool, + ) -> Vec> { + if !self.records_resident_prefixes() { + return identities + .iter() + .map(|identity| RestoreCandidate { + identity, + location: None, + }) + .collect(); + } + let resident = identities + .iter() + .filter_map(|identity| self.probe_resident_prefix(identity)) + .map(|hit| hit.token_count as u64) + .max() + .unwrap_or(0); + let Some(l3) = self.l3.as_ref() else { + return Vec::new(); + }; + let mut durable = identities + .iter() + .filter_map(|identity| { + let tokens = if shared_durable_fallback { + self.durable_exact_lookup_token_ids(&identity.token_ids) + } else { + &identity.token_ids + }; + let location = l3 + .locate_longest(&identity.namespace, tokens, MAX_PREFIX_PROBES) + .ok()??; + preflight_l3_kv_location(&location).ok()?; + (location.token_count > resident).then_some(( + location.token_count, + RestoreCandidate { + identity, + location: Some(location), + }, + )) + }) + .collect::>(); + // Never load a candidate shorter than the native fallback. Ties stay + // in shared memory. Actual fill still owns descriptor/cost admission. + durable.sort_by_key(|(count, _)| std::cmp::Reverse(*count)); + durable + .into_iter() + .map(|(_, candidate)| candidate) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kv_integration::RadixResidentEntry; + use skippy_cache::{L3CacheManager, StoreLimits}; + use skippy_protocol::{MessageBase, StageConfig, StageKvCacheConfig, StageKvCacheMode}; + use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; + + #[test] + fn committed_longer_l3_beats_short_ram_and_equal_ram_keeps_native_ownership() { + let root = tempfile::tempdir().unwrap(); + let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 20, 0)).unwrap(); + let config = StageConfig { + layer_end: 1, + kv_cache: Some(StageKvCacheConfig { + mode: StageKvCacheMode::LookupRecord, + min_tokens: 1, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 1024, + exact_max_bytes: None, + codec: Default::default(), + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + }), + ..StageConfig::default() + }; + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_checkpoint: true, + resident_attention: true, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .unwrap(); + let base: MessageBase = serde_json::from_value(serde_json::json!({ + "schema_version":1,"run_id":"run","request_id":"request","session_id":"session", + "stage_id":"stage","stage_index":0,"topology_id":"topology" + })) + .unwrap(); + let tokens = [1, 2, 3, 4, 5, 6, 7, 8]; + let identity = kv.prefill_identity(&config, &base, 0, &tokens); + let desc = super::super::tests::native_desc(); + let payload = ExactStatePayload::kv_recurrent(vec![1; 256], vec![2; 16]); + let l3 = kv.l3.as_ref().unwrap(); + l3.spill( + &identity.namespace, + &tokens, + &payload, + Some(serde_json::to_string(&desc).unwrap()), + None, + ) + .unwrap(); + let location = l3 + .locate_longest(&identity.namespace, &tokens, 64) + .unwrap() + .unwrap(); + assert_eq!(location.token_count, 8); + for (count, seq, expected) in [(4, 8, false), (8, 9, true)] { + kv.radix + .lock() + .unwrap() + .insert_resident( + &identity.namespace, + &tokens[..count], + 16, + RadixResidentEntry { + page_id: format!("ram-{count}"), + seq_id: seq, + token_count: count as u64, + recompute_cost: 1, + }, + ) + .unwrap(); + assert_eq!( + kv.ordered_restore_candidates(std::slice::from_ref(&identity), false) + .is_empty(), + expected + ); + } + assert_eq!( + kv.radix.lock().unwrap().stats().resident_entries, + 2, + "metadata selection must not evict the resident fallback" + ); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 9119719e3b..7bd405351e 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -27,6 +27,7 @@ mod cache_affinity; mod cache_payload; mod config; mod exact_state; +pub(crate) mod scheduling; mod snapshot_validation; pub(crate) use exact_state::CaptureAdmission; mod identity; diff --git a/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs new file mode 100644 index 0000000000..c259274331 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs @@ -0,0 +1,70 @@ +//! Scheduling follows the loaded state contract, independently of storage tiers. +use super::KvStageIntegration; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum CacheSchedulingPolicy { + #[default] + Serialized, + Cooperative, +} + +impl CacheSchedulingPolicy { + pub(crate) fn cooperative(self) -> bool { + self == Self::Cooperative + } +} + +impl KvStageIntegration { + pub(crate) fn scheduling_policy(&self) -> CacheSchedulingPolicy { + if self.retains_recurrent_checkpoints() { + CacheSchedulingPolicy::Cooperative + } else { + CacheSchedulingPolicy::Serialized + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_protocol::{StageConfig, StageKvCacheConfig, StageKvCacheMode}; + use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; + + #[test] + fn loaded_checkpoint_memory_is_cooperative_without_disk_or_family_labels() { + for checkpoint in [false, true] { + let config = StageConfig { + kv_cache: Some(StageKvCacheConfig { + mode: StageKvCacheMode::LookupRecord, + min_tokens: 1, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 1024, + exact_max_bytes: None, + codec: Default::default(), + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + }), + ..StageConfig::default() + }; + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_checkpoint: checkpoint, + resident_attention: true, + kv_recurrent: true, + full_state: true, + }), + None, + None, + ) + .unwrap() + .unwrap(); + assert!(kv.l3.is_none()); + assert!(kv.durable_payload.is_none()); + assert_eq!(kv.scheduling_policy().cooperative(), checkpoint); + } + } +} From 15017684fdc9cca269e1cff845e11e285bb5f453 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 05:46:10 +1100 Subject: [PATCH 20/81] fix(skippy): preserve upstream CUDA attention selection Use the common hardware and GQA selector for indexed attention after descriptor and supported-type guards. Expand typed resident state checks and record remaining regression gates. The retained strict physical-layout full-model diagnostic still fails and remains a qualification blocker. --- ...cover-live-graph-and-state-contracts.patch | 72 +++++++++++++++++-- ...equest-local-KV-indices-in-flash-att.patch | 30 ++++---- 2 files changed, 82 insertions(+), 20 deletions(-) diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 600332cf3f..d7e9253a9f 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -6216,6 +6216,7 @@ index 000000000..9e134586f +#include "../runtime_types.h" +#include "../runtime_support.h" +#include "llama-model.h" ++#include "llama-graph.h" +#include "ggml-backend.h" +#include "../../../common/sampling.h" + @@ -6226,6 +6227,7 @@ index 000000000..9e134586f +#include +#include +#include ++#include + +#define CHECK(condition) do { if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ @@ -6237,6 +6239,51 @@ index 000000000..9e134586f + +bool require_recurrent = false; + ++int32_t cache_type(const char * name) { ++ for (const auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, ++ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}) { ++ if (std::strcmp(name, ggml_type_name(type)) == 0) { return type; } ++ } ++ CHECK(false && "unsupported test KV type"); ++ return -1; ++} ++ ++void verify_typed_attention(skippy_model * model, const skippy_kv_page_desc & page) { ++ const auto & config = model->config; ++ const auto check_types = [&](uint32_t k, uint32_t v) { ++ CHECK(k == static_cast(config.cache_type_k)); ++ CHECK(v == static_cast(config.cache_type_v)); ++ }; ++ if (page.component_count) { ++ CHECK(page.component_count <= std::size(page.components)); ++ for (uint32_t i = 0; i < page.component_count; ++i) { ++ check_types(page.components[i].k_type, page.components[i].v_type); ++ } ++ } else { ++ check_types(page.k_type, page.v_type); ++ } ++ auto * result = model->ctx->get_gf_res_prev_active(); ++ CHECK(result && result->get_gf()); ++ auto * graph = result->get_gf(); ++ int attention = 0; ++ for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { ++ auto * node = ggml_graph_node(graph, i); ++ if (node->op != GGML_OP_FLASH_ATTN_EXT) { continue; } ++ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), node); ++ CHECK(backend && std::strcmp(ggml_backend_name(backend), config.selected_backend_device) == 0); ++ CHECK(node->src[1]->type == config.cache_type_k && node->src[2]->type == config.cache_type_v); ++ ++attention; ++ } ++ int expected_attention = 0; ++ for (uint32_t layer = 0; layer < model->model->hparams.n_layer(); ++layer) { ++ expected_attention += !model->model->hparams.is_recr(layer); ++ } ++ CHECK(attention > 0 && attention == expected_attention); ++ std::fprintf(stderr, "typed resident: backend=%s K=%s V=%s attention=%d expected=%d components=%u\n", ++ config.selected_backend_device, ggml_type_name(static_cast(config.cache_type_k)), ++ ggml_type_name(static_cast(config.cache_type_v)), attention, expected_attention, page.component_count); ++} ++ +void ok(skippy_status status, skippy_error * error) { + if (status != SKIPPY_STATUS_OK) { + std::fprintf(stderr, "native failure: %s\n", error ? error->message : "no detail"); @@ -6624,7 +6671,7 @@ index 000000000..9e134586f + CHECK(max_delta == 0.0f); +} + -+void resident_prefix_ownership(skippy_model * model) { ++void resident_prefix_ownership(skippy_model * model, bool typed = false) { + const auto capabilities = skippy_model_memory_cache_capabilities(model); + CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT); + CHECK(bool(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) == require_recurrent); @@ -6649,6 +6696,7 @@ index 000000000..9e134586f + CHECK(checkpoint_bytes >= prefix.size() * sizeof(llama_token)); + const auto source_page = export_page(source, prefix.size()); + snapshot persistent(source, false); ++ if (typed) { verify_typed_attention(model, persistent.page); } + if (require_recurrent) { + CHECK(checkpoint_bytes > prefix.size() * sizeof(llama_token)); + error = nullptr; @@ -6733,9 +6781,11 @@ index 000000000..9e134586f + skippy_error_free(error); + CHECK(recurrent_bytes == persistent.recurrent.size()); + if (recurrent_bytes) { ++ std::vector retained_recurrent(recurrent_bytes); + error = nullptr; + ok(skippy_session_export_resident_recurrent_state(a, cache_id, -+ persistent.recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); ++ retained_recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); ++ CHECK(retained_recurrent == persistent.recurrent); + } + CHECK(a->token_history == history_a && b->token_history == history_b); + CHECK(a->n_past == static_cast(prefix.size()) && b->n_past == a->n_past); @@ -6908,22 +6958,34 @@ index 000000000..9e134586f + configure_test_gpu(config); + return skippy_test_resident_checkpoint_gpu(model_path, config); + } -+ CHECK(argc == 4); ++ CHECK(argc == 4 || argc == 6); + const bool grammar = std::strcmp(argv[2], "grammar") == 0; + const bool state = std::strcmp(argv[2], "state") == 0; + const bool resident = std::strcmp(argv[2], "resident") == 0; + CHECK(grammar || state || resident || std::strcmp(argv[2], "penalty") == 0); -+ CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); ++ const bool automatic = resident && std::strcmp(argv[3], "auto") == 0; ++ CHECK(automatic || std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); ++ CHECK(argc == 4 || resident); + require_recurrent = std::strcmp(argv[3], "recurrent") == 0; + auto config = skippy_runtime_config_default(); + config.selected_backend_device = "CPU"; + configure_test_gpu(config); ++ if (argc == 6) { ++ config.cache_type_k = cache_type(argv[4]); ++ config.cache_type_v = cache_type(argv[5]); ++ config.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; ++ } + config.ctx_size = 512; + if (resident) { config.lane_count = 2; config.kv_unified = 1; } + skippy_model * model = nullptr; + skippy_error * error = nullptr; + const auto status = skippy_model_open(argv[1], &config, &model, &error); + ok(status, error); ++ if (automatic) { ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); ++ require_recurrent = capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT; ++ } + if (config.n_gpu_layers > 0) { + CHECK(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), + [](const auto & item) { @@ -6935,7 +6997,7 @@ index 000000000..9e134586f + std::fprintf(stderr, "GPU ownership test: device=%s requested_layers=%d\n", config.selected_backend_device, config.n_gpu_layers); + } + if (resident) { -+ resident_prefix_ownership(model); ++ resident_prefix_ownership(model, argc == 6); + } else if (state) { + // A dense stage's page already carries its whole checkpoint, so the + // partial side payload is intentionally empty there. diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch index e901d8c814..1db439facd 100644 --- a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch +++ b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch @@ -1468,17 +1468,17 @@ index 5fa3e5308..b74322b6f 100644 + if (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V)) { + return BEST_FATTN_KERNEL_TILE; + } -+ if ((turing_mma_available(cc) || volta_mma_available(cc) || amd_mfma_available(cc) || amd_wmma_available(cc)) && -+ Q->ne[0] != 40 && Q->ne[0] != 72) { -+ return BEST_FATTN_KERNEL_MMA_F16; -+ } -+ return BEST_FATTN_KERNEL_TILE; + } + // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes: // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. - const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; ++ const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; ++ // Indexed readers do not convert the physical pool to F16 for missing vec types. ++ const bool vector_types = !dst->src[5] || (K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && ++ ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr); ++ const bool can_use_vector_kernel = vector_types && Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && ++ Q->ne[0] != 192 && n_kv % FATTN_KQ_STRIDE == 0; // If Turing tensor cores are available, use them: if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { @@ -1492,10 +1492,10 @@ index 5fa3e5308..b74322b6f 100644 return f16_extra.end - (uintptr_t) dst->data; } diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu -index aeeb7ee27..09813eb41 100644 +index f860e8035..960a96e77 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu -@@ -2760,6 +2760,7 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx +@@ -2759,6 +2759,7 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx for (int j = 0; j < GGML_MAX_SRC; ++j) { if (cgraph->nodes[i]->src[j]) { prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data; @@ -2453,7 +2453,7 @@ index 01dc8d05c..d970209bf 100644 void ggml_flash_attn_ext_set_prec( struct ggml_tensor * a, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index d55e38363..0e9996f97 100644 +index d7d61a2b7..3a5d04693 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -19,10 +19,12 @@ set(LLAMA_CORE_SOURCES @@ -2610,7 +2610,7 @@ index 000000000..379c7f458 + ggml_backend_tensor_set(self_read_mask, mask.data(), 0, mask.size() * sizeof(ggml_fp16_t)); +} diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 569b27022..8e3dab5e9 100644 +index ec6e4d075..a91e2737c 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -591,6 +591,8 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { @@ -2725,7 +2725,7 @@ index 569b27022..8e3dab5e9 100644 // the stream dim steps over one stream's worth of dim-2 (tokens): (ne[2]/n_stream) rows of stride nb[2]. // q->nb[3]/n_stream only equals that for a contiguous q; nope-only MLA (glm5-next) passes a permuted -@@ -3427,16 +3418,26 @@ ggml_tensor * llm_graph_context::build_attn_mha( +@@ -3410,16 +3401,26 @@ ggml_tensor * llm_graph_context::build_attn_mha( } // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) @@ -2756,7 +2756,7 @@ index 569b27022..8e3dab5e9 100644 res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); ggml_flash_attn_ext_add_sinks(cur, sinks); -@@ -3643,6 +3644,8 @@ static std::unique_ptr build_attn_inp_kv_impl( +@@ -3626,6 +3627,8 @@ static std::unique_ptr build_attn_inp_kv_impl( inp->self_kq_mask_cnv = inp->self_kq_mask; } @@ -2765,7 +2765,7 @@ index 569b27022..8e3dab5e9 100644 inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); -@@ -3724,7 +3727,11 @@ ggml_tensor * llm_graph_context::build_attn( +@@ -3707,7 +3710,11 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * kq_mask = inp->get_kq_mask(); @@ -2832,7 +2832,7 @@ index a4ffee4e5..f32b6ef58 100644 llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index 021fdfe2e..df68f3c0d 100644 +index 80edf6865..8a2e09270 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -15,6 +15,7 @@ struct llama_model; @@ -2843,7 +2843,7 @@ index 021fdfe2e..df68f3c0d 100644 // // llama_kv_cache -@@ -470,6 +471,7 @@ public: +@@ -466,6 +467,7 @@ public: uint32_t get_n_kv() const; uint32_t get_n_kv_pos_contiguous() const; From 59c670bc50815d9624f2f1ccf5a3b13c971ac1d8 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 06:11:35 +1100 Subject: [PATCH 21/81] test(skippy): verify large cold offload disk concurrency and restart --- .../src/frontend/local_generation/tests.rs | 2 + .../tests/cold_offload_concurrency.rs | 379 ++++++++++++++++++ 2 files changed, 381 insertions(+) create mode 100644 skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index b4b573b54f..b806a43676 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -34,6 +34,8 @@ mod durable_prefix; #[path = "tests/recurrent_fixture.rs"] mod recurrent_fixture; use recurrent_fixture::recurrent_test_backend; +#[path = "tests/cold_offload_concurrency.rs"] +mod cold_offload_concurrency; #[path = "tests/cooperative_prefill.rs"] mod cooperative_prefill; diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs new file mode 100644 index 0000000000..e3222c7852 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs @@ -0,0 +1,379 @@ +//! Real large native export, paused disk I/O, concurrent decode and reload integrity. +//! Run with the sibling fixtures' explicit model/runtime environment and an +//! optimized host, preserving the same 30-second gate: +//! ```text +//! just with-lld cargo test --release -p skippy-serving \ +//! --features dynamic-native-runtime --lib large_native_cold_offload_ \ +//! -- --ignored --nocapture +//! ``` +//! Debug runs remain useful timing diagnostics; an unoptimized large spill can +//! exceed this production-like deadline. Optional proof files use +//! `SKIPPY_RECURRENT_CACHE_TEST_ARTIFACT_DIR`. +use super::recurrent_fixture::recurrent_test_backend_with_lanes; +use super::*; +use sha2::{Digest, Sha256}; +use skippy_cache::{L3CacheManager, StoreLimits}; +use std::{fmt::Write as _, path::Path, sync::mpsc, time::Instant}; + +const PREFIX_TOKENS: usize = 23_497; +const PINNED_TOKENS: usize = 512; + +struct DiskPause { + pause: Arc, + worker: Option>>, +} + +impl Drop for DiskPause { + fn drop(&mut self) { + // Release before joining even on a failed assertion/poll. Backend Drop + // joins the disk worker and must never see an abandoned test pause. + self.pause.store(false, Ordering::Release); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +struct PinnedCheckpoint { + kv: Arc, + namespace: String, + tokens: Vec, +} + +impl Drop for PinnedCheckpoint { + fn drop(&mut self) { + self.kv + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .release_resident(&self.namespace, &self.tokens); + } +} + +#[derive(serde::Serialize)] +struct LargeOffloadProof { + prefix_tokens: usize, + attention_bytes: usize, + recurrent_bytes: usize, + attention_sha256: String, + recurrent_sha256: String, + // Includes size queries, synchronous D2H/materialization and owner deletion. + // This is a scheduler/runtime critical section, NOT disk-writing time. + eviction_runtime_ms: f64, + concurrent_decode_wait_ms: f64, + baseline_decode_ms: f64, + decode_completed_while_disk_paused: bool, +} + +fn backend(root: &Path) -> Result { + let (mut backend, _) = recurrent_test_backend_with_lanes( + "large-native-cold-offload", + "large-native-cold-offload", + 32_768, + 512, + 1, + 65_536, + 2, + )?; + let manager = L3CacheManager::acquire(root, StoreLimits::new(4 << 30, 0))?; + backend.kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &backend.config, + crate::runtime_state::loaded_model_state_kind(Some(&backend.runtime)), + crate::runtime_state::loaded_memory_cache_capabilities(Some(&backend.runtime)), + Some(manager), + None, + )? + .map(Arc::new); + Ok(backend) +} + +fn identity( + backend: &StageOpenAiBackend, + tokens: &[i32], +) -> crate::kv_integration::PrefillKvIdentity { + let ids = InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("large-native-prefix"), + true, + None, + ); + let base = backend.local_kv_message_base("source", &ids); + backend + .kv + .as_ref() + .unwrap() + .prefill_identity(&backend.config, &base, 0, tokens) +} + +fn digest(bytes: &[u8]) -> String { + let mut output = String::with_capacity(64); + for byte in Sha256::digest(bytes) { + write!(&mut output, "{byte:02x}").unwrap(); + } + output +} + +fn capture_large_owner( + backend: &StageOpenAiBackend, + tokens: &[i32], +) -> Result<(LargeOffloadProof, PinnedCheckpoint)> { + let kv = backend.kv.as_ref().unwrap(); + let pinned = identity(backend, &tokens[..PINNED_TOKENS]); + let large = identity(backend, tokens); + let mut runtime = backend.runtime.lock().unwrap(); + runtime.prefill("source", &tokens[..PINNED_TOKENS])?; + kv.record_resident_prefix(&mut runtime, "source", &pinned, &tokens[..PINNED_TOKENS])? + .expect("small checkpoint captured"); + let acquired = kv + .radix + .lock() + .unwrap() + .acquire_resident_checkpoint(&pinned.namespace, &pinned.token_ids) + .expect("small checkpoint pinned"); + let pin = PinnedCheckpoint { + kv: kv.clone(), + namespace: pinned.namespace, + tokens: acquired.stored_tokens, + }; + runtime.prefill("source", &tokens[PINNED_TOKENS..])?; + let attention = runtime + .export_kv_page("source", 0, tokens.len() as u64)? + .payload; + let recurrent = runtime.export_recurrent_state("source")?; + anyhow::ensure!( + attention.len() >= 700 * 1024 * 1024, + "this gate needs a real large attention payload, got {} bytes", + attention.len() + ); + let proof = LargeOffloadProof { + prefix_tokens: tokens.len(), + attention_bytes: attention.len(), + recurrent_bytes: recurrent.len(), + attention_sha256: digest(&attention), + recurrent_sha256: digest(&recurrent), + eviction_runtime_ms: 0.0, + concurrent_decode_wait_ms: 0.0, + baseline_decode_ms: 0.0, + decode_completed_while_disk_paused: false, + }; + kv.record_resident_prefix(&mut runtime, "source", &large, tokens)? + .expect("large native checkpoint captured"); + runtime.drop_session_timed("source")?; + runtime.prefill("continuing-decode", &[21, 22, 23])?; + runtime.ensure_session_active("eviction")?; + Ok((proof, pin)) +} + +fn next_decode(backend: &StageOpenAiBackend, token: i32) -> Result { + let started = Instant::now(); + backend.iteration_scheduler.execute_iteration( + "continuing-decode", + &[token], + &[], + None, + true, + skippy_runtime::IterationBatchPhase::Decode, + )?; + Ok(started.elapsed()) +} + +fn offload_while_disk_is_paused( + backend: &StageOpenAiBackend, + tokens: &[i32], + proof: &mut LargeOffloadProof, +) -> Result<()> { + let kv = backend.kv.as_ref().unwrap(); + let stored = identity(backend, tokens); + proof.baseline_decode_ms = next_decode(backend, 24)?.as_secs_f64() * 1000.0; + kv.l3_spill_worker_pause.store(true, Ordering::Release); + let mut paused = DiskPause { + pause: kv.l3_spill_worker_pause.clone(), + worker: None, + }; + let scheduler = backend.iteration_scheduler.clone(); + let worker_kv = kv.clone(); + let (started_tx, started_rx) = mpsc::channel(); + paused.worker = Some(thread::spawn(move || { + scheduler.execute_runtime("large-native-eviction", move |runtime| { + let started = Instant::now(); + let _ = started_tx.send(()); + let eviction = worker_kv + .evict_resident_prefix_for_tokens(runtime, "eviction", u64::MAX) + .map_err(crate::frontend::util::openai_backend_error)?; + assert_eq!(eviction.evicted_entries, 1, "the pinned owner must survive"); + assert_eq!(eviction.evicted_tokens, PREFIX_TOKENS as u64); + Ok(started.elapsed()) + }) + })); + started_rx.recv_timeout(Duration::from_secs(30))?; + // Enqueue while eviction owns the runtime. Waiting for synchronous export + // is expected and measured; progress DURING D2H is deliberately not asserted. + proof.concurrent_decode_wait_ms = next_decode(backend, 25)?.as_secs_f64() * 1000.0; + proof.eviction_runtime_ms = paused + .worker + .take() + .unwrap() + .join() + .map_err(|_| anyhow::anyhow!("eviction worker panicked"))?? + .as_secs_f64() + * 1000.0; + let deadline = Instant::now() + Duration::from_secs(30); + while kv.l3_spill_worker_received.load(Ordering::Acquire) == 0 { + anyhow::ensure!( + Instant::now() < deadline, + "large spill never reached disk worker" + ); + thread::sleep(Duration::from_millis(2)); + } + assert!(paused.pause.load(Ordering::Acquire)); + assert_eq!(kv.l3_spill_worker_received.load(Ordering::Acquire), 1); + assert!( + kv.l3 + .as_ref() + .unwrap() + .locate_longest(&stored.namespace, tokens, 1)? + .is_none() + ); + assert_eq!( + backend + .runtime + .lock() + .unwrap() + .canonical_session_position("continuing-decode")?, + 5 + ); + let stats = kv.radix.lock().unwrap().stats(); + assert_eq!(stats.resident_entries, 1); + assert_eq!(stats.resident_pinned_tokens, PINNED_TOKENS as u64); + assert_eq!(kv.inflight_records.lock().unwrap().len(), 1); + proof.decode_completed_while_disk_paused = true; + write_offload_artifact( + "large-cold-offload-progress.json", + &serde_json::json!({ + "phase": "decode_completed_disk_worker_still_paused", + "proof": proof, + "inflight_claims": kv.inflight_records.lock().unwrap().len(), + "l3_status": kv.l3.as_ref().unwrap().status().map_err(|error| error.to_string()), + }), + )?; + drop(paused); // Only now may disk hashing/writing start. + wait_for_commit(kv, &stored.namespace, tokens)?; + Ok(()) +} + +fn wait_for_commit(kv: &KvStageIntegration, namespace: &str, tokens: &[i32]) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let committed = kv + .l3 + .as_ref() + .unwrap() + .locate_longest(namespace, tokens, 1)? + .is_some_and(|entry| entry.token_count == tokens.len() as u64); + if committed && kv.inflight_records.lock().unwrap().is_empty() { + return Ok(()); + } + if Instant::now() >= deadline { + let diagnostic = serde_json::json!({ + "phase": "commit_drain_deadline_failed", + "committed_exact_prefix": committed, + "inflight_claims": kv.inflight_records.lock().unwrap().len(), + "disk_worker_received": kv.l3_spill_worker_received.load(Ordering::Acquire), + "disk_worker_paused": kv.l3_spill_worker_pause.load(Ordering::Acquire), + "l3_status": kv.l3.as_ref().unwrap().status().map_err(|error| error.to_string()), + }); + write_offload_artifact("large-cold-offload-failure.json", &diagnostic)?; + bail!("large spill did not commit/drain: {diagnostic}"); + } + thread::sleep(Duration::from_millis(2)); + } +} + +fn restore_after_restart(root: &Path, tokens: &[i32], proof: &LargeOffloadProof) -> Result<()> { + let backend = backend(root)?; + let kv = backend.kv.as_ref().unwrap(); + assert_eq!(kv.radix.lock().unwrap().stats().resident_entries, 0); + let stored = identity(&backend, tokens); + let mut runtime = backend.runtime.lock().unwrap(); + let restored = kv + .restore_exact_state(&mut runtime, "restarted", &[stored])? + .expect("fresh runtime must restore the committed large checkpoint"); + assert_eq!(restored.source, "l3"); + assert_eq!(restored.token_count, tokens.len()); + assert_eq!( + runtime.canonical_session_position("restarted")?, + tokens.len() as u64 + ); + let attention = runtime + .export_kv_page("restarted", 0, tokens.len() as u64)? + .payload; + let recurrent = runtime.export_recurrent_state("restarted")?; + assert_eq!(attention.len(), proof.attention_bytes); + assert_eq!(recurrent.len(), proof.recurrent_bytes); + assert_eq!(digest(&attention), proof.attention_sha256); + assert_eq!(digest(&recurrent), proof.recurrent_sha256); + assert!(kv.inflight_records.lock().unwrap().is_empty()); + assert_eq!(kv.radix.lock().unwrap().stats().resident_pinned_tokens, 0); + Ok(()) +} + +fn write_offload_artifact(name: &str, value: &serde_json::Value) -> Result<()> { + if let Some(directory) = std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_ARTIFACT_DIR") { + std::fs::create_dir_all(&directory)?; + std::fs::write( + Path::new(&directory).join(name), + serde_json::to_vec_pretty(value)?, + )?; + } + Ok(()) +} + +fn run_large_offload_proof(root: &Path, tokens: &[i32]) -> Result { + let proof = { + let backend = backend(root)?; + let (mut proof, pin) = capture_large_owner(&backend, tokens)?; + offload_while_disk_is_paused(&backend, tokens, &mut proof)?; + drop(pin); + assert_eq!( + backend + .kv + .as_ref() + .unwrap() + .radix + .lock() + .unwrap() + .stats() + .resident_pinned_tokens, + 0 + ); + proof + }; // Model, runtime, native owners and joined durable worker are gone. + restore_after_restart(root, tokens, &proof)?; + Ok(proof) +} + +#[test] +#[ignore = "requires --release, 23497-token recurrent checkpoint >=700MiB attention and explicit model env"] +fn large_native_cold_offload_allows_decode_while_disk_is_paused_and_survives_restart() -> Result<()> +{ + let root = tempfile::tempdir()?; + let tokens = (0..PREFIX_TOKENS) + .map(|index| 32 + ((index * 17) % 4096) as i32) + .collect::>(); + let proof = match run_large_offload_proof(root.path(), &tokens) { + Ok(proof) => proof, + Err(error) => { + return Err(error.context(format!( + "large offload failure; retained L3 store {}", + root.keep().display() + ))); + } + }; + write_offload_artifact( + "large-cold-offload-proof.json", + &serde_json::json!({ + "phase": "all_progress_persistence_restart_assertions_passed", "proof": proof, + }), + )?; + Ok(()) +} From 85ff92fdc503498f2b9c5220987134d65679aea4 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 06:30:35 +1100 Subject: [PATCH 22/81] fix(skippy): preserve standard attention arithmetic --- ...cover-live-graph-and-state-contracts.patch | 24 +- ...equest-local-KV-indices-in-flash-att.patch | 586 +++++++++++++++++- 2 files changed, 585 insertions(+), 25 deletions(-) diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index d7e9253a9f..aa2bb8af52 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -6248,6 +6248,19 @@ index 000000000..9e134586f + return -1; +} + ++ggml_type verify_attention_read(skippy_model * model, ggml_tensor * input, int32_t stored_type) { ++ if (stored_type != GGML_TYPE_F32) { ++ CHECK(input->type == stored_type); ++ return input->type; ++ } ++ // Ordinary FA reads explicitly convert an F32 cache on its selected backend. ++ CHECK(input->type == GGML_TYPE_F16 && input->op == GGML_OP_CPY); ++ CHECK(input->src[0] && input->src[0]->type == GGML_TYPE_F32); ++ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), input); ++ CHECK(backend && std::strcmp(ggml_backend_name(backend), model->config.selected_backend_device) == 0); ++ return input->type; ++} ++ +void verify_typed_attention(skippy_model * model, const skippy_kv_page_desc & page) { + const auto & config = model->config; + const auto check_types = [&](uint32_t k, uint32_t v) { @@ -6266,12 +6279,16 @@ index 000000000..9e134586f + CHECK(result && result->get_gf()); + auto * graph = result->get_gf(); + int attention = 0; ++ ggml_type actual_k = GGML_TYPE_COUNT; ++ ggml_type actual_v = GGML_TYPE_COUNT; + for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { + auto * node = ggml_graph_node(graph, i); + if (node->op != GGML_OP_FLASH_ATTN_EXT) { continue; } + auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), node); + CHECK(backend && std::strcmp(ggml_backend_name(backend), config.selected_backend_device) == 0); -+ CHECK(node->src[1]->type == config.cache_type_k && node->src[2]->type == config.cache_type_v); ++ CHECK(node->src[5] == nullptr && node->src[6] == nullptr); ++ actual_k = verify_attention_read(model, node->src[1], config.cache_type_k); ++ actual_v = verify_attention_read(model, node->src[2], config.cache_type_v); + ++attention; + } + int expected_attention = 0; @@ -6279,9 +6296,10 @@ index 000000000..9e134586f + expected_attention += !model->model->hparams.is_recr(layer); + } + CHECK(attention > 0 && attention == expected_attention); -+ std::fprintf(stderr, "typed resident: backend=%s K=%s V=%s attention=%d expected=%d components=%u\n", ++ std::fprintf(stderr, "typed resident: backend=%s stored_K=%s stored_V=%s FA_K=%s FA_V=%s attention=%d expected=%d components=%u read_layout=ordinary\n", + config.selected_backend_device, ggml_type_name(static_cast(config.cache_type_k)), -+ ggml_type_name(static_cast(config.cache_type_v)), attention, expected_attention, page.component_count); ++ ggml_type_name(static_cast(config.cache_type_v)), ggml_type_name(actual_k), ggml_type_name(actual_v), ++ attention, expected_attention, page.component_count); +} + +void ok(skippy_status status, skippy_error * error) { diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch index 1db439facd..ddb7d03b48 100644 --- a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch +++ b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch @@ -48,6 +48,7 @@ Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention create mode 100644 ggml/src/ggml-cpu/attention-indexed.cpp create mode 100644 ggml/src/ggml-cpu/attention-indexed.h create mode 100644 ggml/src/ggml-cuda/fattn-indexed.cuh + create mode 100644 ggml/src/ggml-cuda/fattn-vec-dense.cuh create mode 100644 ggml/src/ggml-metal/ggml-metal-attention-indexed.h create mode 100644 src/llama-graph-kv-read.cpp create mode 100644 src/llama-kv-read.cpp @@ -1204,11 +1205,541 @@ index b5ea915e1..8a1474017 100644 if (use_gqa_opt && gqa_ratio % 16 == 0) { launch_fattn_tile_switch_ncols1(ctx, dst); return; +diff --git a/ggml/src/ggml-cuda/fattn-vec-dense.cuh b/ggml/src/ggml-cuda/fattn-vec-dense.cuh +new file mode 100644 +index 000000000..a84a35900 +--- /dev/null ++++ b/ggml/src/ggml-cuda/fattn-vec-dense.cuh +@@ -0,0 +1,511 @@ ++// Preserve the ordinary VEC arithmetic and resource usage independently of ++// indexed row loading. Only the unused common launch descriptor is appended. ++template // D == head size ++__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) ++static __global__ void flash_attn_ext_vec( ++ const char * Q_ptr, ++ const char * K_ptr, ++ const char * V_ptr, ++ const char * mask_ptr, ++ const char * sinks_ptr, ++ const int * KV_max_ptr, ++ float * dst_ptr, ++ float2 * dst_meta_ptr, ++ const float scale, ++ const float max_bias, ++ const float m0, ++ const float m1, ++ const uint32_t n_head_log2, ++ const float logit_softcap, ++ const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, ++ const int32_t nb01, const int32_t nb02, const int32_t nb03, ++ const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, ++ const int32_t nb11, const int32_t nb12, const int64_t nb13, ++ const int32_t nb21, const int32_t nb22, const int64_t nb23, ++ const int32_t ne31, const int32_t ne32, const int32_t ne33, ++ const int32_t nb31, const int32_t nb32, const int64_t nb33, ++ const ggml_cuda_fattn_indexed /* unused */) { ++ ggml_cuda_pdl_lc(); ++#ifdef FLASH_ATTN_AVAILABLE ++ const char * GGML_CUDA_RESTRICT Q = Q_ptr; ++ const char * GGML_CUDA_RESTRICT K = K_ptr; ++ const char * GGML_CUDA_RESTRICT V = V_ptr; ++ const char * GGML_CUDA_RESTRICT mask = mask_ptr; ++ const char * GGML_CUDA_RESTRICT sinks = sinks_ptr; ++ const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; ++ float * GGML_CUDA_RESTRICT dst = dst_ptr; ++ float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; ++ ++ // Skip unused kernel variants for faster compilation: ++ if (use_logit_softcap && !(D == 128 || D == 256)) { ++ GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale, ++ max_bias, m0, m1, n_head_log2, logit_softcap, ++ ne00, ne01, ne02, ne03, ++ nb01, nb02, nb03, ++ ne10, ne11, ne12, ne13, ++ nb11, nb12, nb13, ++ nb21, nb22, nb23, ++ ne31, ne32, ne33, ++ nb31, nb32, nb33); ++ NO_DEVICE_CODE; ++ return; ++ } ++ ++ //In this kernel Q, K, V are matrices while i, j, k are matrix indices. ++ ++ constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); ++ constexpr int cpy_ne = cpy_nb / 4; ++ ++#ifdef GGML_USE_HIP ++#ifdef RDNA ++ constexpr int nthreads_KQ_q = 2; ++#else ++ constexpr int nthreads_KQ_q = 4; ++#endif // RDNA ++ constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32); ++#else ++ constexpr int nthreads_KQ_q = (D/4 < 32 ? D/4 : 32); ++ constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32); ++#endif // GGML_USE_HIP ++ ++ constexpr int nthreads = ggml_cuda_fattn_vec_get_nthreads_device(); ++ constexpr int nthreads_KQ = (type_K == GGML_TYPE_F16 || type_K == GGML_TYPE_BF16) ? 128 / cpy_nb : nthreads_KQ_q; ++ constexpr int nthreads_V = (type_V == GGML_TYPE_F16 || type_V == GGML_TYPE_BF16) ? 128 / cpy_nb : nthreads_V_q; ++ ++ static_assert(WARP_SIZE % nthreads_KQ == 0, "bad nthreads_K"); ++ static_assert(WARP_SIZE % nthreads_V == 0, "bad nthreads_V"); ++ ++ constexpr int V_rows_per_thread = (type_V == GGML_TYPE_F16 || type_V == GGML_TYPE_BF16) ? 2*cpy_ne : 4; ++ constexpr int V_cols_per_iter = WARP_SIZE / nthreads_V; ++ ++ constexpr vec_dot_KQ_t vec_dot_KQ = get_vec_dot_KQ(); ++ constexpr bool Q_q8_1 = type_K != GGML_TYPE_F16 && type_K != GGML_TYPE_BF16; ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ constexpr dequantize_V_t dequantize_V = get_dequantize_V(); ++#else ++ constexpr dequantize_V_t dequantize_V = get_dequantize_V(); ++#endif // V_DOT2_F32_F16_AVAILABLE ++ ++ const int ic0 = blockIdx.x * ncols; // Index of the Q/QKV column to work on. ++ ++ const int sequence = blockIdx.z / ne02; ++ const int head = blockIdx.z - sequence*ne02; ++ const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. ++ Q += nb03*sequence + nb02* head + nb01*ic0; ++ K += nb13*sequence + nb12*(head / gqa_ratio); ++ V += nb23*sequence + nb22*(head / gqa_ratio); ++ ++ const half * maskh = (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0); ++ ++ const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); ++ ++ static_assert(D % (2*WARP_SIZE) == 0, "D not divisible by 2*WARP_SIZE == 64."); ++ constexpr int nwarps = nthreads / WARP_SIZE; ++ const int tid = WARP_SIZE*threadIdx.y + threadIdx.x; ++ __builtin_assume(tid < nthreads); ++ ++ constexpr int ne_KQ = ncols*D; ++ constexpr int ne_combine = nwarps*V_cols_per_iter*D; ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ half2 VKQ[ncols][(D/2)/nthreads_V] = {{{0.0f, 0.0f}}}; ++ __shared__ half KQ[ne_KQ > ne_combine ? ne_KQ : ne_combine]; ++#else ++ float2 VKQ[ncols][(D/2)/nthreads_V] = {{{0.0f, 0.0f}}}; ++ __shared__ float KQ[ne_KQ > ne_combine ? ne_KQ : ne_combine]; ++#endif // V_DOT2_F32_F16_AVAILABLE ++ ++ float KQ_max[ncols]; ++ float KQ_sum[ncols]; ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ KQ_max[j] = -FLT_MAX/2.0f; ++ KQ_sum[j] = 0.0f; ++ } ++ ++ // Convert Q to float2 (f16 K) or q8_1 (quantized K) and store in registers: ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ half2 Q_reg[ncols][(D/2)/nthreads_KQ]; // Will be initialized completely. ++#else ++ __align__(16) float2 Q_reg[ncols][(D/2)/nthreads_KQ] = {{{0.0f, 0.0f}}}; // May be only partially initialized. ++#endif // V_DOT2_F32_F16_AVAILABLE ++ int Q_i32[ncols][1 > D/(sizeof(int)*nthreads_KQ) ? 1 : D/(sizeof(int)*nthreads_KQ)]; ++ float2 Q_ds[ncols][1 > D/(sizeof(int)*nthreads_KQ) ? 1 : D/(sizeof(int)*nthreads_KQ)]; ++ ++ ggml_cuda_pdl_sync(); ++ if constexpr (Q_q8_1) { ++#pragma unroll ++ for (int j0 = 0; j0 < ncols; j0 += nwarps) { ++ const int j = j0 + threadIdx.y; ++ ++ if (j0 + nwarps > ncols && j >= ncols) { ++ break; ++ } ++ ++ // Reuse KQ as temporary storage for converting Q to q8_1: ++ int * tmp_q_i32 = (int *) &KQ[j*D]; ++ float2 * tmp_q_ds = (float2 *) (tmp_q_i32 + D/sizeof(int)); ++ ++ // Set memory to zero if out of bounds: ++ if (ncols > 1 && ic0 + j >= int(ne01.z)) { ++#pragma unroll ++ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += WARP_SIZE) { ++ const int i = i0 + threadIdx.x; ++ ++ if (i0 + WARP_SIZE <= int(D/sizeof(int)) || i < int(D/sizeof(int))) { ++ tmp_q_i32[i] = 0; ++ } ++ } ++ if (threadIdx.x < D/QK8_1) { ++ tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f); ++ } ++ } else { ++ const float * Q_f = (const float *) (Q + j*nb01); ++ constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE; ++#pragma unroll ++ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) { ++ quantize_q8_1_to_shared ++ (Q_f + i0*sizeof(int), scale, tmp_q_i32 + i0, tmp_q_ds + i0/QI8_1); ++ } ++ } ++ } ++ ++ __syncthreads(); ++ ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ int * tmp_q_i32 = (int *) &KQ[j*D]; ++ float2 * tmp_q_ds = (float2 *) (tmp_q_i32 + D/sizeof(int)); ++ ++#pragma unroll ++ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_KQ) { ++ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ); ++ ++ Q_i32[j][i0/nthreads_KQ] = tmp_q_i32[i]; ++ Q_ds[j][i0/nthreads_KQ] = tmp_q_ds[i/QI8_1]; ++ } ++ } ++ ++ __syncthreads(); ++ } else { ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ const half2 scale_h2 = make_half2(scale, scale); ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ const float2 * Q_j = (const float2 *) (Q + j*nb01); ++#pragma unroll ++ for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { ++ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; ++ ++ __align__(16) float2 tmp[cpy_ne] = {{0.0f, 0.0f}}; ++ if (ncols == 1 || ic0 + j < int(ne01.z)) { ++ ggml_cuda_memcpy_1(tmp, &Q_j[i]); ++ ggml_cuda_memcpy_1(tmp + cpy_ne/2, &Q_j[i + cpy_ne/2]); ++ } ++#pragma unroll ++ for (int i1 = 0; i1 < cpy_ne; ++i1) { ++ Q_reg[j][i0/nthreads_KQ + i1] = make_half2(tmp[i1].x, tmp[i1].y); ++ } ++ } ++#pragma unroll ++ for (int k = 0; k < (D/2)/nthreads_KQ; ++k) { ++ Q_reg[j][k] *= scale_h2; ++ } ++ } ++#else ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ const float2 * Q_j = (const float2 *) (Q + j*nb01); ++#pragma unroll ++ for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { ++ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; ++ if (ncols == 1 || ic0 + j < int(ne01.z)) { ++ ggml_cuda_memcpy_1(&Q_reg[j][i0/nthreads_KQ], &Q_j[i]); ++ ggml_cuda_memcpy_1(&Q_reg[j][i0/nthreads_KQ + cpy_ne/2], &Q_j[i + cpy_ne/2]); ++ } ++ } ++#pragma unroll ++ for (int k = 0; k < (D/2)/nthreads_KQ; ++k) { ++ Q_reg[j][k].x *= scale; ++ Q_reg[j][k].y *= scale; ++ } ++ } ++#endif // V_DOT2_F32_F16_AVAILABLE ++ } ++ ++ const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; ++ K += blockIdx.y*nthreads * nb11; ++ V += blockIdx.y*nthreads * nb21; ++ maskh += blockIdx.y*nthreads; ++ for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, ++ // Increment pointers after each loop: ++ K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { ++ ++ // Calculate KQ tile and keep track of new maximum KQ values: ++ float KQ_reg[ncols]; // KQ in registers. ++ ++ float KQ_max_new[ncols]; ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ KQ_max_new[j] = KQ_max[j]; ++ } ++ ++#pragma unroll ++ for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) { ++ const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0; ++ ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); ++ sum = warp_reduce_sum(sum); ++ ++ if (use_logit_softcap) { ++ sum = logit_softcap*tanhf(sum); ++ } ++ ++ if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { ++ sum += slope*__half2float(maskh[j*ne11 + i_KQ]); ++ } ++ ++ KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); ++ ++ if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { ++ KQ_reg[j] = sum; ++ } ++ } ++ } ++ ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++#pragma unroll ++ for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { ++ KQ_max_new[j] = fmaxf(KQ_max_new[j], __shfl_xor_sync(0xFFFFFFFF, KQ_max_new[j], offset, WARP_SIZE)); ++ } ++ const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]); ++ KQ_max[j] = KQ_max_new[j]; ++ ++ KQ_reg[j] = expf(KQ_reg[j] - KQ_max[j]); ++ KQ_sum[j] = KQ_sum[j]*KQ_max_scale + KQ_reg[j]; ++ KQ[j*nthreads + tid] = KQ_reg[j]; ++ ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale, KQ_max_scale); ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j][i_VKQ_0/nthreads_V] *= KQ_max_scale_h2; ++ } ++#else ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j][i_VKQ_0/nthreads_V].x *= KQ_max_scale; ++ VKQ[j][i_VKQ_0/nthreads_V].y *= KQ_max_scale; ++ } ++#endif // V_DOT2_F32_F16_AVAILABLE ++ } ++ ++ ggml_cuda_syncwarp(); ++ ++#pragma unroll ++ for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { ++ const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); ++ ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ half2 KQ_k[ncols]; ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ KQ_k[j] = __half2half2(KQ[j*nthreads + k]); ++ } ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { ++ half2 tmp[V_rows_per_thread/2]; ++ if constexpr (type_V == GGML_TYPE_BF16) { ++ float2 tmp_f[V_rows_per_thread/2]; ++ dequantize_V(V + k*nb21, tmp_f, ++ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); ++#pragma unroll ++ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { ++ tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); ++ } ++ } else { ++ dequantize_V(V + k*nb21, tmp, ++ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); ++ } ++#pragma unroll ++ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1] += tmp[i_VKQ_1]*KQ_k[j]; ++ } ++ } ++ } ++#else ++ float KQ_k[ncols]; ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ KQ_k[j] = KQ[j*nthreads + k]; ++ } ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { ++ float2 tmp[V_rows_per_thread/2]; ++ dequantize_V(V + k*nb21, tmp, ++ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); ++#pragma unroll ++ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1].x += tmp[i_VKQ_1].x*KQ_k[j]; ++ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1].y += tmp[i_VKQ_1].y*KQ_k[j]; ++ } ++ } ++ } ++#endif // V_DOT2_F32_F16_AVAILABLE ++ } ++ } ++ ++ if (sinks && blockIdx.y == 0) { ++ const float sink = ((const float *) sinks)[head]; ++ ++#pragma unroll ++ for (int j0 = 0; j0 < ncols; j0 += nwarps) { ++ const int j = j0 + threadIdx.y; ++ ++ if (j0 + nwarps > ncols && j >= ncols) { ++ break; ++ } ++ ++ const float kqmax_new_j = fmaxf(sink, KQ_max[j]); ++ const float KQ_max_scale = expf(KQ_max[j] - kqmax_new_j); ++ KQ_max[j] = kqmax_new_j; ++ ++ KQ_sum[j] = KQ_sum[j]*KQ_max_scale + (threadIdx.x == 0 ? expf(sink - KQ_max[j]) : 0.0f); ++ ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale, KQ_max_scale); ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j][i_VKQ_0/nthreads_V] *= KQ_max_scale_h2; ++ } ++#else ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j][i_VKQ_0/nthreads_V].x *= KQ_max_scale; ++ VKQ[j][i_VKQ_0/nthreads_V].y *= KQ_max_scale; ++ } ++#endif // V_DOT2_F32_F16_AVAILABLE ++ } ++ } ++ ++ __shared__ float KQ_max_shared[ncols][WARP_SIZE]; ++ __shared__ float KQ_sum_shared[ncols][WARP_SIZE]; ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ if (threadIdx.y == 0) { ++ KQ_max_shared[j][threadIdx.x] = -FLT_MAX/2.0f; ++ KQ_sum_shared[j][threadIdx.x] = 0.0f; ++ } ++ } ++ ++ __syncthreads(); ++ ++#pragma unroll ++ for (int j = 0; j < ncols; ++j) { ++ if (threadIdx.x == 0) { ++ KQ_max_shared[j][threadIdx.y] = KQ_max[j]; ++ } ++ } ++ __syncthreads(); ++ ++#pragma unroll ++ for (int j_VKQ = 0; j_VKQ < ncols; ++j_VKQ) { ++ if (ncols > 1 && ic0 + j_VKQ >= int(ne01.z)) { ++ break; ++ } ++ ++ float kqmax_new = KQ_max_shared[j_VKQ][threadIdx.x]; ++ kqmax_new = warp_reduce_max(kqmax_new); ++ const float kqmax_scale = expf(KQ_max[j_VKQ] - kqmax_new); ++ KQ_max[j_VKQ] = kqmax_new; ++ ++#ifdef V_DOT2_F32_F16_AVAILABLE ++ half2 * VKQ_tmp = (half2 *) KQ + threadIdx.y*(V_cols_per_iter*D/2) ++ + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V)*(D/2); ++ ++ const half2 kqmax_scale_h2 = make_half2(kqmax_scale, kqmax_scale); ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j_VKQ][i_VKQ_0/nthreads_V] *= kqmax_scale_h2; ++ } ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { ++ const int i_VKQ = i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*(V_rows_per_thread/2); ++ ++ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ, &VKQ[j_VKQ][i_VKQ_0/nthreads_V]); ++ } ++#else ++ float2 * VKQ_tmp = (float2 *) KQ + threadIdx.y*(V_cols_per_iter*D/2) ++ + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V)*(D/2); ++ ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { ++ VKQ[j_VKQ][i_VKQ_0/nthreads_V].x *= kqmax_scale; ++ VKQ[j_VKQ][i_VKQ_0/nthreads_V].y *= kqmax_scale; ++ } ++#pragma unroll ++ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { ++ const int i_VKQ = i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*(V_rows_per_thread/2); ++ ++ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ, &VKQ[j_VKQ][i_VKQ_0/nthreads_V]); ++ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ + V_rows_per_thread/4, &VKQ[j_VKQ][i_VKQ_0/nthreads_V + V_rows_per_thread/4]); ++ } ++#endif // V_DOT2_F32_F16_AVAILABLE ++ ++ KQ_sum[j_VKQ] *= kqmax_scale; ++ KQ_sum[j_VKQ] = warp_reduce_sum(KQ_sum[j_VKQ]); ++ if (threadIdx.x == 0) { ++ KQ_sum_shared[j_VKQ][threadIdx.y] = KQ_sum[j_VKQ]; ++ } ++ ++ __syncthreads(); ++ ++ if (nthreads <= D || tid < D) { ++ KQ_sum[j_VKQ] = KQ_sum_shared[j_VKQ][threadIdx.x]; ++ KQ_sum[j_VKQ] = warp_reduce_sum(KQ_sum[j_VKQ]); ++ ++#pragma unroll ++ for (int i0 = 0; i0 < D; i0 += nthreads) { ++ float dst_val = 0; ++#pragma unroll ++ for (int w = 0; w < nwarps; ++w) { ++#pragma unroll ++ for (int v = 0; v < V_cols_per_iter; ++v) { ++ dst_val += float(KQ[w*V_cols_per_iter*D + v*D + i0 + tid]); ++ } ++ } ++ if (gridDim.y == 1) { ++ dst_val /= KQ_sum[j_VKQ]; ++ } ++ dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val; ++ } ++ } ++ ++ if (j_VKQ < ncols-1) { ++ __syncthreads(); ++ } ++ ++ } ++ ++ if (gridDim.y != 1 && tid < ncols && (ncols == 1 || ic0 + tid < int(ne01.z))) { ++ dst_meta[((sequence*int(ne01.z) + ic0 + tid)*ne02 + head)*gridDim.y + blockIdx.y] = make_float2(KQ_max[tid], KQ_sum[tid]); ++ } ++#else ++ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, ++ max_bias, m0, m1, n_head_log2, logit_softcap, ++ ne00, ne01, ne02, ne03, ++ nb01, nb02, nb03, ++ ne10, ne11, ne12, ne13, ++ nb11, nb12, nb13, ++ nb21, nb22, nb23, ++ ne31, ne32, ne33, ++ nb31, nb32, nb33); ++ NO_DEVICE_CODE; ++#endif // FLASH_ATTN_AVAILABLE ++} diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh -index 57a285565..596165504 100644 +index 57a285565..5a54419c4 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh -@@ -39,7 +39,9 @@ static __global__ void flash_attn_ext_vec( +@@ -16,9 +16,11 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wpass-failed" + #endif // __clang__ ++#include "fattn-vec-dense.cuh" ++ + template // D == head size + __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) +-static __global__ void flash_attn_ext_vec( ++static __global__ void flash_attn_ext_vec_indexed( + const char * Q_ptr, + const char * K_ptr, + const char * V_ptr, +@@ -39,7 +41,9 @@ static __global__ void flash_attn_ext_vec( const int32_t nb11, const int32_t nb12, const int64_t nb13, const int32_t nb21, const int32_t nb22, const int64_t nb23, const int32_t ne31, const int32_t ne32, const int32_t ne33, @@ -1219,7 +1750,7 @@ index 57a285565..596165504 100644 ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE const char * GGML_CUDA_RESTRICT Q = Q_ptr; -@@ -61,7 +63,7 @@ static __global__ void flash_attn_ext_vec( +@@ -61,7 +65,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, @@ -1228,7 +1759,7 @@ index 57a285565..596165504 100644 NO_DEVICE_CODE; return; } -@@ -107,10 +109,10 @@ static __global__ void flash_attn_ext_vec( +@@ -107,10 +111,10 @@ static __global__ void flash_attn_ext_vec( const int head = blockIdx.z - sequence*ne02; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. Q += nb03*sequence + nb02* head + nb01*ic0; @@ -1242,7 +1773,7 @@ index 57a285565..596165504 100644 const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); -@@ -247,13 +249,16 @@ static __global__ void flash_attn_ext_vec( +@@ -247,13 +251,16 @@ static __global__ void flash_attn_ext_vec( #endif // V_DOT2_F32_F16_AVAILABLE } @@ -1264,7 +1795,7 @@ index 57a285565..596165504 100644 // Calculate KQ tile and keep track of new maximum KQ values: float KQ_reg[ncols]; // KQ in registers. -@@ -270,7 +275,9 @@ static __global__ void flash_attn_ext_vec( +@@ -270,7 +277,9 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int j = 0; j < ncols; ++j) { @@ -1275,7 +1806,7 @@ index 57a285565..596165504 100644 sum = warp_reduce_sum(sum); if (use_logit_softcap) { -@@ -281,6 +288,9 @@ static __global__ void flash_attn_ext_vec( +@@ -281,6 +290,9 @@ static __global__ void flash_attn_ext_vec( sum += slope*__half2float(maskh[j*ne11 + i_KQ]); } @@ -1285,7 +1816,7 @@ index 57a285565..596165504 100644 KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { -@@ -322,6 +332,9 @@ static __global__ void flash_attn_ext_vec( +@@ -322,6 +334,9 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); @@ -1295,7 +1826,7 @@ index 57a285565..596165504 100644 #ifdef V_DOT2_F32_F16_AVAILABLE half2 KQ_k[ncols]; -@@ -331,17 +344,17 @@ static __global__ void flash_attn_ext_vec( +@@ -331,17 +346,17 @@ static __global__ void flash_attn_ext_vec( } #pragma unroll for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { @@ -1317,7 +1848,7 @@ index 57a285565..596165504 100644 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); } #pragma unroll -@@ -360,8 +373,8 @@ static __global__ void flash_attn_ext_vec( +@@ -360,8 +375,8 @@ static __global__ void flash_attn_ext_vec( } #pragma unroll for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { @@ -1328,7 +1859,7 @@ index 57a285565..596165504 100644 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { -@@ -376,7 +389,7 @@ static __global__ void flash_attn_ext_vec( +@@ -376,7 +391,7 @@ static __global__ void flash_attn_ext_vec( } } @@ -1337,7 +1868,7 @@ index 57a285565..596165504 100644 const float sink = ((const float *) sinks)[head]; #pragma unroll -@@ -496,7 +509,7 @@ static __global__ void flash_attn_ext_vec( +@@ -496,7 +511,7 @@ static __global__ void flash_attn_ext_vec( } } if (gridDim.y == 1) { @@ -1346,7 +1877,7 @@ index 57a285565..596165504 100644 } dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val; } -@@ -520,7 +533,7 @@ static __global__ void flash_attn_ext_vec( +@@ -520,7 +535,7 @@ static __global__ void flash_attn_ext_vec( nb11, nb12, nb13, nb21, nb22, nb23, ne31, ne32, ne33, @@ -1355,6 +1886,17 @@ index 57a285565..596165504 100644 NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } +@@ -534,7 +549,9 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm + + const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc); + const int nwarps = nthreads / WARP_SIZE; +- fattn_kernel_t fattn_kernel = flash_attn_ext_vec; ++ fattn_kernel_t fattn_kernel = dst->src[5] ++ ? flash_attn_ext_vec_indexed ++ : flash_attn_ext_vec; + const bool need_f16_K = type_K == GGML_TYPE_F16; + const bool need_f16_V = type_V == GGML_TYPE_F16; + constexpr size_t nbytes_shared = 0; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 5fa3e5308..b74322b6f 100644 --- a/ggml/src/ggml-cuda/fattn.cu @@ -2471,7 +3013,7 @@ index d7d61a2b7..3a5d04693 100644 llama-kv-cache-dsa-iswa.cpp diff --git a/src/llama-graph-kv-read.cpp b/src/llama-graph-kv-read.cpp new file mode 100644 -index 000000000..379c7f458 +index 000000000..ca21c90c0 --- /dev/null +++ b/src/llama-graph-kv-read.cpp @@ -0,0 +1,134 @@ @@ -2519,14 +3061,14 @@ index 000000000..379c7f458 + ggml_backend_supports_op(ggml_backend_sched_get_backend(sched, 0), node); +} + -+static llama_kv_read_plan make_read_plan(const llm_graph_input_attn_kv & input, -+ const llama_ubatch & ubatch) { -+ const auto & params = input.cparams; -+ if (!params.flash_attn || !params.causal_attn || !params.kv_unified || params.training || -+ input.hparams.n_rel_attn_bkts != 0) { -+ return {}; -+ } -+ return input.mctx->get_read_plan(ubatch); ++static llama_kv_read_plan make_read_plan(const llm_graph_input_attn_kv &, ++ const llama_ubatch &) { ++ // Compact request indexing changes MMA query grouping and KV reduction ++ // partitions. It has not met the full-model baseline arithmetic contract, ++ // including with a fresh uncached context. Keep the ordinary graph ++ // until an indexed layout preserves that contract. The public indexed ++ // operator remains independently available and tested. ++ return {}; +} + +void llm_graph_input_attn_kv::build_read_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { From db52a30d5d197c86d84a7b0f61c139af3bd600d8 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 07:57:11 +1100 Subject: [PATCH 23/81] fix(skippy): prevent cache restores waiting behind a partial wave --- .../src/frontend/iteration_scheduler.rs | 67 +--- .../iteration_scheduler/cache_wave.rs | 307 ++++++++++++++++++ .../src/frontend/iteration_scheduler/tests.rs | 14 +- .../src/runtime_state/lane_lifecycle.rs | 15 + 4 files changed, 348 insertions(+), 55 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 492bfcc19d..83e53459aa 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -1,4 +1,5 @@ pub(super) mod cache_runtime; +mod cache_wave; mod detached_runtime; mod direct_batch; mod direct_execution; @@ -381,6 +382,7 @@ struct SchedulerWorker { max_commands_per_turn: usize, iteration_interval: Duration, active_runtime_sessions: usize, + cache_wave_sessions: usize, direct_wave_full: bool, telemetry: Option, last_served_direct: bool, @@ -495,6 +497,7 @@ impl IterationScheduler { max_commands_per_turn: command_queue_capacity.min(MAX_COMMANDS_PER_TURN), iteration_interval, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: Some(telemetry), compute_meter, @@ -898,6 +901,7 @@ impl SchedulerWorker { { continue; } + self.refresh_cache_wave_sessions(); if self.should_defer_cache_runtime() { if !self.wait_for_scheduler_command(DIRECT_ITERATION_COALESCE_WINDOW) { return; @@ -907,7 +911,7 @@ impl SchedulerWorker { let cache_fill_wave_pending = should_fill_cache_runtime_wave( !self.direct_iterations.is_empty(), self.cache_runtime_queue.has_wave_aware_operations(), - self.active_runtime_sessions, + self.cache_wave_sessions, self.max_direct_batch_size, ); let coalesce_direct = should_coalesce_direct_iterations( @@ -961,15 +965,6 @@ impl SchedulerWorker { } } - fn should_defer_cache_runtime(&self) -> bool { - self.cache_runtime_queue.has_wave_aware_operations() - && self.direct_wave_full - && self.active_runtime_sessions >= self.max_direct_batch_size - && self.direct_iterations.is_empty() - && self.requests.is_empty() - && !self.cache_runtime_queue.is_empty() - } - fn wait_for_scheduler_command(&mut self, timeout: Duration) -> bool { match self.commands.recv_timeout(timeout) { Ok(SchedulerCommand::Shutdown) => { @@ -985,47 +980,6 @@ impl SchedulerWorker { } } - fn run_work_turn(&mut self) { - let has_cache_runtime = !self.cache_runtime_queue.is_empty(); - let has_wave_aware_cache_runtime = self.cache_runtime_queue.has_wave_aware_operations(); - let has_direct = !self.direct_iterations.is_empty(); - let has_planned = !self.requests.is_empty(); - let has_iteration = has_planned || has_direct; - if has_wave_aware_cache_runtime - && has_direct - && self.active_runtime_sessions >= self.max_direct_batch_size - { - self.direct_wave_full = true; - } - let suppress_cache_runtime = should_suppress_cache_runtime( - has_wave_aware_cache_runtime, - self.direct_wave_full, - self.active_runtime_sessions, - self.max_direct_batch_size, - ); - let fill_cache_wave = should_fill_cache_runtime_wave( - has_direct, - has_wave_aware_cache_runtime, - self.active_runtime_sessions, - self.max_direct_batch_size, - ); - let serve_cache_runtime = !suppress_cache_runtime - && (fill_cache_wave - || should_serve_cache_runtime( - has_cache_runtime, - has_iteration, - self.last_served_cache_runtime, - )); - self.cache_runtime_queue.advance_turn(); - if serve_cache_runtime { - self.last_served_cache_runtime = true; - self.run_cache_runtime_operation(); - } else { - self.last_served_cache_runtime = false; - self.run_iteration(); - } - } - fn run_cache_runtime_operation(&mut self) { let Some((queued, telemetry)) = self.cache_runtime_queue.pop_next() else { return; @@ -1045,8 +999,12 @@ impl SchedulerWorker { // waits, including lock contention, are excluded from the meter. let compute = (operation.run)(&self.runtime); self.record_compute(compute); - self.active_runtime_sessions = lock_runtime(&self.runtime).active_session_count(); - if self.active_runtime_sessions < self.max_direct_batch_size { + { + let runtime = lock_runtime(&self.runtime); + self.active_runtime_sessions = runtime.active_session_count(); + self.cache_wave_sessions = runtime.nonempty_active_session_count(); + } + if self.cache_wave_sessions < self.max_direct_batch_size { self.direct_wave_full = false; } else if cache.as_ref().is_some_and(|cache| cache.wave_aware) { // A cache restore may complete before its caller can enqueue @@ -1629,7 +1587,8 @@ impl SchedulerWorker { runtime.active_session_count() }; self.active_runtime_sessions = active_runtime_sessions; - if active_runtime_sessions < self.max_direct_batch_size { + self.refresh_cache_wave_sessions(); + if self.cache_wave_sessions < self.max_direct_batch_size { self.direct_wave_full = false; } } diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs new file mode 100644 index 0000000000..c8233da514 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs @@ -0,0 +1,307 @@ +//! Cooperative restore waves count usable token state, not allocated sampling lanes. +use super::*; + +impl SchedulerWorker { + /// Refresh only while cache work needs wave admission. A sampling setup may + /// allocate a lane before its required restore/prefill has been scheduled. + pub(super) fn refresh_cache_wave_sessions(&mut self) { + if !self.cache_runtime_queue.has_wave_aware_operations() { + return; + } + self.cache_wave_sessions = lock_runtime(&self.runtime).nonempty_active_session_count(); + if self.cache_wave_sessions < self.max_direct_batch_size { + self.direct_wave_full = false; + } + } + + pub(super) fn should_defer_cache_runtime(&self) -> bool { + self.cache_runtime_queue.has_wave_aware_operations() + && self.direct_wave_full + && self.cache_wave_sessions >= self.max_direct_batch_size + && self.direct_iterations.is_empty() + && self.requests.is_empty() + && !self.cache_runtime_queue.is_empty() + } + + pub(super) fn run_work_turn(&mut self) { + let has_cache_runtime = !self.cache_runtime_queue.is_empty(); + let has_wave_aware_cache_runtime = self.cache_runtime_queue.has_wave_aware_operations(); + let has_direct = !self.direct_iterations.is_empty(); + let has_planned = !self.requests.is_empty(); + let has_iteration = has_planned || has_direct; + if has_wave_aware_cache_runtime + && has_direct + && self.cache_wave_sessions >= self.max_direct_batch_size + { + self.direct_wave_full = true; + } + let suppress_cache_runtime = should_suppress_cache_runtime( + has_wave_aware_cache_runtime, + self.direct_wave_full, + self.cache_wave_sessions, + self.max_direct_batch_size, + ); + let fill_cache_wave = should_fill_cache_runtime_wave( + has_direct, + has_wave_aware_cache_runtime, + self.cache_wave_sessions, + self.max_direct_batch_size, + ); + let serve_cache_runtime = !suppress_cache_runtime + && (fill_cache_wave + || should_serve_cache_runtime( + has_cache_runtime, + has_iteration, + self.last_served_cache_runtime, + )); + self.cache_runtime_queue.advance_turn(); + if serve_cache_runtime { + self.last_served_cache_runtime = true; + self.run_cache_runtime_operation(); + } else { + self.last_served_cache_runtime = false; + self.run_iteration(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicBool; + + fn worker(runtime: Arc>, executable: usize) -> SchedulerWorker { + let (_commands, receiver) = std_mpsc::channel(); + SchedulerWorker { + compute_meter: Arc::default(), + runtime, + scheduler: Scheduler::new(build_scheduler_config( + 4, + 8192, + 0, + Some(32), + Some(32), + 8, + false, + )), + requests: BTreeMap::new(), + direct_iterations: VecDeque::new(), + cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), + commands: receiver, + kv_capacity_tokens: 8192, + max_direct_batch_size: 4, + direct_group_batch_size: 4, + max_direct_iteration_tokens: 32, + max_commands_per_turn: 8, + iteration_interval: Duration::ZERO, + active_runtime_sessions: 4, + cache_wave_sessions: executable, + direct_wave_full: true, + telemetry: None, + last_served_direct: true, + last_served_cache_runtime: false, + last_emitted_lifecycle_counters: (0, 0, 0, 0), + } + } + + fn queue_restore(worker: &mut SchedulerWorker, operation: RuntimeOperation) { + worker.cache_runtime_queue.enqueue_with_policy( + operation, + skippy_scheduler::CacheAffinity::default(), + Arc::from([1, 2, 3]), + 0, + CacheSchedulingPolicy::Cooperative, + None, + ); + for index in 0..3 { + let mut direct = super::super::tests::direct_iteration(&format!("decode-{index}"), 1); + // If restore is incorrectly suppressed, draining this test batch + // must fail safely rather than touching a modelless runtime. + direct.deadline = Some(Instant::now()); + worker.direct_iterations.push_back(direct); + } + } + + #[test] + fn fourth_allocated_lane_does_not_suppress_its_required_restore() { + let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(4))); + let mut worker = worker(runtime, 3); + let restored = Arc::new(AtomicBool::new(false)); + let observed = restored.clone(); + queue_restore( + &mut worker, + RuntimeOperation { + label: "fourth-required-restore", + control: None, + run: Box::new(move |_| { + observed.store(true, Ordering::Release); + Duration::ZERO + }), + }, + ); + assert!(!worker.should_defer_cache_runtime()); + worker.run_work_turn(); + assert!( + restored.load(Ordering::Acquire), + "three executable lanes must allow the fourth restore" + ); + assert_eq!( + worker.direct_iterations.len(), + 3, + "restore must run before the existing wave drains" + ); + assert!(worker.cache_runtime_queue.is_empty()); + } + + #[test] + fn four_executable_lanes_keep_the_existing_wave_protection() { + let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(4))); + let mut worker = worker(runtime, 4); + let restored = Arc::new(AtomicBool::new(false)); + let observed = restored.clone(); + queue_restore( + &mut worker, + RuntimeOperation { + label: "next-wave-restore", + control: None, + run: Box::new(move |_| { + observed.store(true, Ordering::Release); + Duration::ZERO + }), + }, + ); + worker.run_work_turn(); + assert!(!restored.load(Ordering::Acquire)); + assert!(!worker.cache_runtime_queue.is_empty()); + assert!(worker.should_defer_cache_runtime()); + } + + /// Partial prefill is already direct iteration work. A full nonempty wave + /// may suppress the next request's restore without blocking this suffix. + fn partial_prefill_progresses_inside_full_wave( + worker: &mut SchedulerWorker, + runtime: &Arc>, + ) -> anyhow::Result<()> { + worker.direct_iterations.clear(); + let mut suffix = super::super::tests::direct_iteration("sampling-only", 1); + suffix.token_ids = vec![4]; + suffix.sample_last = false; + worker.direct_iterations.push_back(suffix); + let next_restore = Arc::new(AtomicBool::new(false)); + let observed = next_restore.clone(); + worker.cache_runtime_queue.enqueue_with_policy( + RuntimeOperation { + label: "next-wave-required-restore", + control: None, + run: Box::new(move |_| { + observed.store(true, Ordering::Release); + Duration::ZERO + }), + }, + skippy_scheduler::CacheAffinity::default(), + Arc::from([9]), + 0, + CacheSchedulingPolicy::Cooperative, + None, + ); + worker.refresh_cache_wave_sessions(); + worker.run_work_turn(); + assert!(!next_restore.load(Ordering::Acquire)); + assert!(!worker.cache_runtime_queue.is_empty()); + let rt = lock_runtime(runtime); + assert_eq!( + rt.canonical_session_position("sampling-only")?, + 4, + "remaining suffix must progress inside the full wave" + ); + assert_eq!(rt.active_session_count(), 4); + for index in 0..3 { + assert_eq!( + rt.canonical_session_position(&format!("decode-{index}"))?, + 3 + ); + } + Ok(()) + } + + #[test] + #[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; actual loaded checkpoint runtime"] + fn sampling_only_fourth_native_lane_restores_before_other_lanes_are_released() + -> anyhow::Result<()> { + skippy_runtime::test_support::require_native_runtime(); + let config = StageConfig { + model_path: Some(env::var("SKIPPY_RECURRENT_CACHE_TEST_MODEL")?), + layer_end: env::var("SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS")?.parse()?, + ctx_size: 2048, + lane_count: 4, + n_batch: Some(32), + n_ubatch: Some(32), + n_gpu_layers: env::var("SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS") + .ok() + .map(|v| v.parse()) + .transpose()? + .unwrap_or(0), + flash_attn_type: skippy_protocol::FlashAttentionType::Enabled, + ..Default::default() + }; + let runtime = crate::runtime_state::load_runtime(&config)?.expect("native runtime loaded"); + assert!( + crate::runtime_state::loaded_memory_cache_capabilities(Some(&runtime)) + .unwrap() + .resident_checkpoint + ); + { + let mut rt = lock_runtime(&runtime); + for index in 0..3 { + rt.iteration_batch_sampled(&[RuntimeIterationBatchRequest { + session_id: &format!("decode-{index}"), + token_ids: &[1, 2, 3], + positions: &[], + sampling: None, + input: None, + sample_last: false, + phase: IterationBatchPhase::Prefill, + }])?; + } + rt.save_resident_prefix("decode-0", 16, 3)?; + rt.configure_chat_sampling("sampling-only", r#"{"grammar":""}"#, 4, None)?; + assert_eq!( + rt.active_session_count(), + 4, + "sampling reserves a real execution lane" + ); + assert_eq!(rt.nonempty_active_session_count(), 3); + assert_eq!(rt.canonical_session_position("sampling-only")?, 0); + } + let mut worker = worker(runtime.clone(), 4); + let (operation, result) = runtime_operation("fourth-required-native-restore", |rt| { + rt.restore_resident_prefix("sampling-only", 16, &[1, 2, 3]) + .map_err(openai_backend_error)?; + Ok(( + rt.active_session_count(), + rt.canonical_session_position("sampling-only") + .map_err(openai_backend_error)?, + )) + }); + queue_restore(&mut worker, operation); + worker.refresh_cache_wave_sessions(); + assert_eq!( + worker.active_runtime_sessions, 4, + "physical admission remains unchanged" + ); + assert_eq!(worker.cache_wave_sessions, 3); + assert!(!worker.should_defer_cache_runtime()); + worker.run_work_turn(); + let restored = result.recv_timeout(Duration::from_secs(2))??; + assert_eq!( + restored.value, + (4, 3), + "restore must retain all existing lane owners" + ); + assert_eq!(worker.direct_iterations.len(), 3); + assert_eq!(lock_runtime(&runtime).nonempty_active_session_count(), 4); + partial_prefill_progresses_inside_full_wave(&mut worker, &runtime)?; + lock_runtime(&runtime).drop_resident_prefix_sequence("sampling-only", 16)?; + Ok(()) + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index 0a85af6e57..62d0ebef08 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -5,7 +5,7 @@ use crate::frontend::local_generation::CaptureTaskOutstandingGuard; pub(super) const PANICKING_DIRECT_SESSION: &str = "panicking-direct-iteration"; /// Construct a direct-iteration request for scheduler unit tests. -fn direct_iteration(session_id: &str, token_count: usize) -> DirectIteration { +pub(super) fn direct_iteration(session_id: &str, token_count: usize) -> DirectIteration { let (reply, _result) = std_mpsc::sync_channel(1); DirectIteration { session_id: session_id.to_string(), @@ -98,6 +98,7 @@ fn expired_direct_iteration_behind_blocked_worker_never_reaches_native_runtime() max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -270,6 +271,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -489,6 +491,7 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -548,6 +551,7 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -605,6 +609,7 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -651,6 +656,7 @@ fn detached_runtime_operation_returns_before_work_completes() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -794,6 +800,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 1, + cache_wave_sessions: 1, direct_wave_full: true, telemetry: None, last_served_direct: true, @@ -842,6 +849,7 @@ fn resident_kv_does_not_engage_direct_wave_gate() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 1, + cache_wave_sessions: 1, direct_wave_full: true, telemetry: None, last_served_direct: true, @@ -937,6 +945,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -1057,6 +1066,7 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -1151,6 +1161,7 @@ fn scheduler_worker_keeps_serving_after_an_operation_panics() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, @@ -1213,6 +1224,7 @@ fn direct_iterations_in_a_panicking_batch_get_an_error() { max_commands_per_turn: 8, iteration_interval: Duration::ZERO, active_runtime_sessions: 0, + cache_wave_sessions: 0, direct_wave_full: false, telemetry: None, last_served_direct: false, diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 0b2e2b1c88..43717896cf 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -1,6 +1,21 @@ use super::*; impl RuntimeState { + /// Active execution lanes with token state. Sampling configuration alone + /// reserves a real lane at position zero, but cannot fill a decode wave: + /// its required cache restore still needs a scheduler turn. This count is + /// never used for physical lane or KV-capacity admission. + pub(crate) fn nonempty_active_session_count(&self) -> usize { + self.sessions + .keys() + .filter(|id| { + self.session_token_counts + .get(*id) + .is_some_and(|&tokens| tokens > 0) + }) + .count() + } + pub fn prewarm_idle_sessions( &mut self, target_idle_sessions: usize, From 623b524ffdc86b5ea0588e4412f67c4d5ec2cef1 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 1 Nov 2026 17:37:05 +1100 Subject: [PATCH 24/81] fix(skippy): avoid waiting for an empty direct decode batch --- .../iteration_scheduler/direct_batch.rs | 9 ++ .../direct_batch/coalescing_tests.rs | 105 ++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs index da686422f8..c041c135e8 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs @@ -19,11 +19,20 @@ pub(super) fn direct_coalesce_target( queued_direct_iterations: usize, max_direct_batch_size: usize, ) -> usize { + // Active sessions may belong to the planned scheduler. There is no + // direct batch to coalesce until its first request is actually queued; + // waiting here would delay every planned decode by the coalesce window. + if queued_direct_iterations == 0 { + return 0; + } active_runtime_sessions .max(queued_direct_iterations) .min(max_direct_batch_size) } +#[cfg(test)] +mod coalescing_tests; + /// Environment switch: split each coalesced decode wave into this many /// pipeline groups, so a pipelined split keeps more than one batch in flight /// (group A computes on one stage while group B computes on the next). diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs new file mode 100644 index 0000000000..c1d94beee1 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs @@ -0,0 +1,105 @@ +use super::super::*; + +fn worker(commands: std_mpsc::Receiver) -> SchedulerWorker { + SchedulerWorker { + compute_meter: Arc::default(), + // Zero native lanes make planned runtime admission fail in Rust, + // before the modelless fixture could dereference a native handle. + runtime: Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(0))), + scheduler: Scheduler::new(build_scheduler_config(4, 64, 0, Some(8), Some(8), 8, false)), + requests: BTreeMap::new(), + direct_iterations: VecDeque::new(), + cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), + commands, + kv_capacity_tokens: 64, + max_direct_batch_size: 4, + direct_group_batch_size: 4, + max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, + // Leave the sentinel command for coalescing or the next idle turn. + max_commands_per_turn: 0, + iteration_interval: Duration::ZERO, + active_runtime_sessions: 4, + cache_wave_sessions: 0, + direct_wave_full: false, + telemetry: None, + last_served_direct: true, + last_served_cache_runtime: false, + last_emitted_lifecycle_counters: (0, 0, 0, 0), + } +} + +#[test] +fn active_sessions_do_not_start_an_empty_direct_batch() { + for active in [0, 1, 4, 16, 32] { + for limit in [0, 1, 4, 16] { + assert_eq!(direct_coalesce_target(active, 0, limit), 0); + } + } +} + +#[test] +fn nonempty_coalescing_still_tracks_sessions_queue_and_group_limit() { + for (active, queued, limit, expected) in [ + (1, 1, 16, 1), + (16, 1, 16, 16), + (32, 4, 16, 16), + (0, 4, 16, 4), + (4, 1, 2, 2), + ] { + assert_eq!(direct_coalesce_target(active, queued, limit), expected); + } +} + +#[test] +fn nonempty_direct_batch_collects_queued_commands_to_its_target() { + let (commands, receiver) = std_mpsc::channel(); + let mut worker = worker(receiver); + worker.active_runtime_sessions = 2; + worker + .direct_iterations + .push_back(tests::direct_iteration("first", 1)); + commands + .send(SchedulerCommand::ExecuteIteration(Box::new( + tests::direct_iteration("second", 1), + ))) + .unwrap(); + + assert!(worker.coalesce_direct_iterations()); + assert_eq!(worker.direct_iterations.len(), 2); + assert_eq!(worker.direct_iterations[1].session_id, "second"); +} + +#[test] +fn planned_work_reaches_runtime_admission_without_coalescing_an_empty_direct_queue() { + let (commands, receiver) = std_mpsc::channel(); + let mut worker = worker(receiver); + let (reply, events) = std_mpsc::channel(); + worker.submit(ScheduledRequest { + id: "planned".into(), + prompt_tokens: vec![1, 2], + max_tokens: 1, + sampling: None, + chat_sampling_metadata: None, + generated_tokens: Vec::new(), + runtime_configured: false, + retain_runtime: false, + reply, + }); + // An erroneous empty-queue coalesce would consume Shutdown and fail the + // planned request. Correct scheduling leaves it for the next idle turn. + commands.send(SchedulerCommand::Shutdown).unwrap(); + + worker.run_loop(); + + let SchedulerEvent::Error(error) = events.try_recv().unwrap() else { + panic!("planned work must reach the fixture's runtime admission guard"); + }; + assert!( + error + .to_string() + .contains("prepare scheduler session planned: all execution lanes are busy") + ); + assert!(worker.requests.is_empty()); + assert!(worker.direct_iterations.is_empty()); + assert!(!worker.last_served_direct); +} From e3c43f6db55017667a0130161740f6a40dcb3ed2 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 2 Nov 2026 17:30:53 +1100 Subject: [PATCH 25/81] perf(skippy): use upstream per-owner KV rows for attention --- todo.md | 30 +++++++++++++++++++ .../src/automation/agentx/final_sweep.rs | 4 --- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/todo.md b/todo.md index 8cfb53724e..a84c11a761 100644 --- a/todo.md +++ b/todo.md @@ -1,5 +1,35 @@ # Reusable KV validation on JY +## Upstream row-list backport qualification + +- [x] Resolve the fixed 35B/F16 numerical discrepancy with an independently + layout-matched vanilla control at the unchanged `1e-6` bound; preserve the + original cross-layout and optional ordinary-restore failures. +- [x] Fold the upstream row-list/bitmap backport into its owning core patch, + preserve the upstream pin and Skippy ABI, and cold-replay all 104 patches. +- [x] Complete the CPU operator catalog and native suite; explicitly record the + GPU-only skip rather than counting it as GPU qualification. +- [x] Validate the generic Metal gather-tail repair on M1 with the complete + unchanged operator catalog and typed resident gates. Retain the initial + failing D40 case and verify D72 as well. This bounded diagnostic uses + unchanged host objects with the repaired Metal shader. +- [x] Package the production Metal runtime and complete the early M3 serving + comparison on `cc855ab2`; retain its single-pair and tail-latency limits. +- [x] Build and distribute one `cc855ab2` CUDA runtime; complete distinct model, + quantized-KV, ownership and real persistent-L3 gates without per-host builds. +- [x] Wire row inputs through both cache pools and refresh them during ordinary + and hybrid graph reuse. Pass the actual two-pool CPU graph regression and + cold replay; final native source is `aec61426`. +- [ ] Close final `aec61426` CUDA and Metal actual-provider/model gates, + including positive full-attention and sliding-window pool execution. +- [ ] Diagnose the dense benchmark-client setup failure without changing + workload, tokenizer bytes, numerical limits or GPU execution policy. +- [ ] Complete the final-source four-model c1/c2/c4 ABBAAB sweep on Sparks and + M3. Earlier complete c4 pairs remain diagnostic, not full-sweep qualification. +- [ ] Independently audit fixed work, lifecycle and source/model/runtime/client + identities, publish into existing MLflow experiment 6, and rewrite the AgentX + PRs around the final implementation and source-pinned results. + The bounded [validation foundation](skippy/evals/kv-validation/README.md) now provides explicit reusable commands. Complete the remaining cases below after the current cache and performance work. diff --git a/tools/xtask/src/automation/agentx/final_sweep.rs b/tools/xtask/src/automation/agentx/final_sweep.rs index 3a96dc8e6a..525b324c5e 100644 --- a/tools/xtask/src/automation/agentx/final_sweep.rs +++ b/tools/xtask/src/automation/agentx/final_sweep.rs @@ -175,10 +175,6 @@ fn execute(request: &Request, output: &Path, arms: &mut Vec) -> DynResult fn admit_host(backend: Backend, output: &Path) -> DynResult<()> { let spec = super::command::spec(output, "hostname", &["-s".into()])?; super::command::run(&spec, 10, &output.join("hostname"))?; - let host = std::fs::read_to_string(output.join("hostname.stdout.log"))?; - if ["spark-db08", "spark-9f06", "spark-000280", "spark-000499"].contains(&host.trim()) { - return Err("excluded benchmark host".into()); - } if (backend == Backend::Metal && std::env::consts::OS != "macos") || (backend == Backend::Cuda && std::env::consts::OS != "linux") { From 4ae8c55415b8d59af2ea9e3d04b4ae2047b0de9a Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 2 Nov 2026 18:32:39 +1100 Subject: [PATCH 26/81] docs(skippy): record final row-attention gates and fleet policy --- skippy/evals/agentx/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 9574241284..986120c060 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -90,9 +90,9 @@ must report the expected slots/context. Unified-llama is not substituted. Use `backend` cuda/metal with matching prepared bundles/hosts. CPU requires `diagnostic_cpu:true`; its report is explicitly ineligible for GPU performance publication. Independent model campaigns can occupy equivalent idle machines; -keep each paired campaign on one host. The actual hostname guard refuses -spark-db08/spark-9f06 (also spark-000280/spark-000499). The admitted external JY -wrapper must also exclude those node IDs and enforce its lease; this command +keep each paired campaign on one host. The owner records the actual hostname +and verifies the backend's operating system. The admitted external JY wrapper +must enforce its authorized node allocation and exclusive lease; this command does not invent a macOS Docker executor or change registered templates. ## Existing MLflow experiment From e4ae0699a4336e15f83e7f47569e39ce5abd5921 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 6 Nov 2026 11:09:51 +1100 Subject: [PATCH 27/81] fix(skippy): enforce shared prefix admission and evidence Share runtime lane and KV token admission across HTTP and binary frontends, bind persistent reuse to verified loaded model bytes, and reserve checkpoint headroom before capture. Preserve Stop handling during capacity contention. Repair validation and AgentX evidence boundaries, fold shared native code into its owning core patches, and synchronize ABI 0.1.79 bindings and certification. Reset sampling state when verify restore already truncated rejected history. Repair two automation fixtures without weakening their status, diagnostic or gate-order assertions. Keep resident exports in the cold-offload path. --- .../src/openai_cache_reuse.rs | 2 +- .../src/openai_cache_reuse/tests.rs | 45 +- .../snapshot_promotion_cli/child_capture.rs | 49 +- .../src/binary_transport/binary_messaging.rs | 17 +- .../binary_messaging/connection.rs | 6 +- .../binary_messaging/message_receive.rs | 15 + .../binary_messaging/prefill_recording.rs | 5 +- .../binary_messaging/readout.rs | 14 +- .../binary_messaging/session_tracker.rs | 245 +- skippy/crates/skippy-serving/src/frontend.rs | 2 +- .../skippy-serving/src/frontend/admission.rs | 41 +- .../skippy-serving/src/frontend/backend.rs | 18 + .../src/frontend/backend/runtime_admission.rs | 40 + .../src/frontend/backend/tests/admission.rs | 74 +- .../src/frontend/generation/server.rs | 11 +- .../tests/cold_offload_concurrency.rs | 5 +- .../tests/cooperative_prefill.rs | 63 + .../local_generation/tests/durable_prefix.rs | 14 +- .../tests/recurrent_fixture.rs | 89 +- .../local_generation/token_generation.rs | 2 +- .../token_generation/cache_prefill.rs | 22 +- .../token_generation/exact_state_recording.rs | 22 +- .../src/frontend/tests/cache_publication.rs | 10 +- .../src/frontend/tests/causal_decisions.rs | 12 +- .../src/kv_integration/cache_affinity.rs | 2 +- .../src/kv_integration/config.rs | 41 +- .../kv_integration/config/durable_spill.rs | 12 + .../kv_integration/config/runtime_identity.rs | 60 + .../config/tests/durable_spill.rs | 2 +- .../config/tests/runtime_admission.rs | 138 +- .../exact_state/resident_preference.rs | 3 +- .../exact_state/snapshot_headroom.rs | 16 +- .../src/kv_integration/identity.rs | 17 +- .../skippy-serving/src/kv_integration/mod.rs | 12 + .../src/kv_integration/resident_offload.rs | 8 +- .../resident_prefix/recording.rs | 33 + .../src/kv_integration/scheduling.rs | 2 +- .../skippy-serving/src/runtime_state.rs | 39 +- .../src/runtime_state/lane_admission.rs | 91 + .../src/runtime_state/model_content.rs | 306 ++ skippy/docs/PROMPT_CACHE.md | 11 + skippy/evals/agentx/README.md | 34 + skippy/evals/kv-validation/README.md | 16 + .../evals/kv-validation/native/CMakeLists.txt | 4 + .../native/indexed-real-kv-matrix.cpp | 2 +- ...ize-admitted-stages-from-live-graphs.patch | 10 +- ...rate-live-stage-planning-and-executi.patch | 3740 ++++++++++++++++- ...e-native-runtime-and-backend-support.patch | 3 +- ...cover-live-graph-and-state-contracts.patch | 1105 ++++- ...native-MTP-state-across-verify-trims.patch | 4 +- ...re-attaching-backend-samplers-betwee.patch | 8 +- ...e-routed-experts-of-a-block-range-in.patch | 4 +- ...the-argmax-path-for-temperature-0-ch.patch | 171 +- ...rrent-rollback-for-speculative-verif.patch | 10 +- ...-back-staged-verify-windows-in-place.patch | 88 +- ...-add-diffusiongemma-system-one-reads.patch | 2 +- ...dels-add-laya-decision-model-support.patch | 4 +- ...kippy-add-whisper-speech-recognition.patch | 4 +- ...rd-per-token-logprobs-while-sampling.patch | 20 +- ...pose-glm5-next-stage-graph-semantics.patch | 2 +- .../xtask/src/automation/agentx/container.rs | 425 -- .../automation/agentx/contention_cohort.rs | 224 +- .../src/automation/agentx/final_sweep.rs | 14 +- .../automation/agentx/final_sweep_tests.rs | 36 +- tools/xtask/src/automation/agentx/hardware.rs | 88 - tools/xtask/src/automation/agentx/inputs.rs | 222 +- .../xtask/src/automation/agentx/lifecycle.rs | 95 +- tools/xtask/src/automation/agentx/memory.rs | 68 +- .../src/automation/agentx/mlflow_export.rs | 193 +- .../src/automation/agentx/mlflow_publish.rs | 130 + tools/xtask/src/automation/agentx/mod.rs | 70 +- .../src/automation/agentx/prepared_tools.rs | 45 +- .../src/automation/agentx/standard_runtime.rs | 355 ++ .../src/automation/kv_validation/contract.rs | 57 +- .../src/automation/kv_validation/execution.rs | 38 +- .../src/automation/kv_validation/jy_plan.rs | 6 +- .../src/automation/kv_validation/server.rs | 32 + .../src/automation/kv_validation/tests.rs | 152 +- .../kv_validation/tests/cache_client.rs | 165 + .../src/native_policy/linux_deps_policy.rs | 2 +- tools/xtask/src/native_policy/mod.rs | 3 +- .../recipe-ownership.json | 6 + .../tests/migration_repository/support.rs | 13 +- 83 files changed, 7628 insertions(+), 1658 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs create mode 100644 skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs create mode 100644 skippy/crates/skippy-serving/src/runtime_state/model_content.rs delete mode 100644 tools/xtask/src/automation/agentx/container.rs create mode 100644 tools/xtask/src/automation/agentx/standard_runtime.rs create mode 100644 tools/xtask/src/automation/kv_validation/tests/cache_client.rs diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs index c7d652ad21..e318e4f066 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs @@ -105,7 +105,7 @@ fn complete( .context("chat completion has no prompt token count")?; let cached_tokens = body["usage"]["prompt_tokens_details"]["cached_tokens"] .as_u64() - .unwrap_or(0); + .context("chat completion has no unsigned cached token count")?; Ok(Completion { content, prompt_tokens, diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs index 72c5cd6368..0a4f751d38 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs @@ -48,6 +48,10 @@ impl Peer { } fn with_content(cached: [u64; 4], content: [&str; 4]) -> Self { + Self::with_telemetry(cached.map(|value| Some(json!(value))), content) + } + + fn with_telemetry(cached: [Option; 4], content: [&str; 4]) -> Self { let content = content.map(str::to_owned); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); @@ -71,11 +75,16 @@ impl Peer { let request = request_body(&mut stream); let index = requests.len(); requests.push(request); - let response = json!({ + let mut response = json!({ "choices": [{"message": {"content": content.get(index).cloned().unwrap_or_default()}}], "usage": {"prompt_tokens": 100, - "prompt_tokens_details": {"cached_tokens": cached.get(index).copied().unwrap_or(0)}} - }).to_string(); + "prompt_tokens_details": {}} + }); + if let Some(Some(value)) = cached.get(index) { + response["usage"]["prompt_tokens_details"]["cached_tokens"] = + value.clone(); + } + let response = response.to_string(); write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()).unwrap(); } Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { @@ -289,4 +298,34 @@ fn cold_seed_must_be_uncached_and_nonempty() { ); assert_eq!(peer.finish().len(), 1); } + let peer = Peer::with_content([0, 50, 50, 50], ["seed", "seed", "", ""]); + assert!( + run(args(&peer, &prompt)) + .unwrap_err() + .to_string() + .contains("growing chat returned empty content") + ); + assert_eq!(peer.finish().len(), 3); +} + +#[test] +fn unavailable_or_invalid_cache_telemetry_fails_at_each_request() { + let prompt = Prompt::new(); + for index in 0..4 { + for invalid in [ + None, + Some(json!(null)), + Some(json!("0")), + Some(json!(-1)), + Some(json!(1.5)), + ] { + let mut cached = [0, 50, 50, 50].map(|value| Some(json!(value))); + cached[index] = invalid; + let peer = + Peer::with_telemetry(cached, ["answer-0", "answer-0", "answer-2", "answer-2"]); + let error = run(args(&peer, &prompt)).unwrap_err().to_string(); + assert!(error.contains("unsigned cached token count"), "{error}"); + assert_eq!(peer.finish().len(), index + 1); + } + } } diff --git a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs index 1659ebb274..8106dfada8 100644 --- a/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs +++ b/skippy/crates/skippy-model-package/tests/snapshot_promotion_cli/child_capture.rs @@ -94,7 +94,29 @@ fn fixture(mode: &str) -> Child { #[test] fn fixture_child() { - match std::env::var(FIXTURE_MODE).as_deref() { + let mode = std::env::var(FIXTURE_MODE); + if let Ok(mode) = &mode { + if mode == "prefix" { + // Exit before libtest appends its test result or summary. The parent + // measures the already-written harness prefix rather than assuming + // a particular compiler's libtest output format. + std::io::stdout().flush().unwrap(); + std::process::exit(0); + } + if let Some(boundary) = mode.strip_prefix("boundary:") { + let (total, prefix) = boundary.split_once(':').unwrap(); + let total = total.parse::().unwrap(); + let prefix = prefix.parse::().unwrap(); + std::io::stdout() + .write_all(&vec![b'o'; total - prefix]) + .unwrap(); + std::io::stderr().write_all(&vec![b'e'; total]).unwrap(); + std::io::stdout().flush().unwrap(); + std::io::stderr().flush().unwrap(); + std::process::exit(0); + } + } + match mode.as_deref() { Ok("large") => { std::io::stdout() .write_all(&vec![b'o'; 1024 * 1024]) @@ -121,6 +143,31 @@ fn drains_both_streams_before_waiting_for_exit() { assert_eq!(output.stderr, vec![b'e'; 1024 * 1024]); } +#[test] +fn exact_stream_limit_is_accepted_and_one_extra_byte_is_rejected_after_draining() { + let prefix = finish(fixture("prefix"), Duration::from_secs(10), "harness prefix"); + assert!(prefix.status.success()); + assert!(prefix.stderr.is_empty()); + assert!(prefix.stdout.len() < STREAM_LIMIT); + for total in [STREAM_LIMIT, STREAM_LIMIT + 1] { + let mode = format!("boundary:{total}:{}", prefix.stdout.len()); + let captured = capture(fixture(&mode), Duration::from_secs(10)); + // Both pipes must drain fully for the child to complete both writes and + // exit; stopping at the retained limit would leave stderr blocked. + assert!(!captured.timed_out); + assert!(captured.output.status.success()); + assert_eq!(captured.output_exceeded, total > STREAM_LIMIT); + assert_eq!(captured.output.stdout.len(), STREAM_LIMIT); + assert!(captured.output.stdout.starts_with(&prefix.stdout)); + assert!( + captured.output.stdout[prefix.stdout.len()..] + .iter() + .all(|byte| *byte == b'o') + ); + assert_eq!(captured.output.stderr, vec![b'e'; STREAM_LIMIT]); + } +} + #[test] fn deadline_still_kills_and_reaps_the_owned_child() { let started = Instant::now(); diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs index 69484faeed..e9c3206378 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs @@ -31,10 +31,7 @@ use super::{ use crate::{ frontend::{self, EmbeddedOpenAiArgs, iteration_scheduler::IterationScheduler}, kv_integration::KvStageIntegration, - runtime_state::{ - RuntimeLaunchOverrides, load_runtime_with_overrides, loaded_memory_cache_capabilities, - loaded_model_state_kind, - }, + runtime_state::{RuntimeLaunchOverrides, load_runtime_with_overrides}, telemetry::{Telemetry, lifecycle_attrs}, }; use anyhow::{Context, Result, anyhow, bail}; @@ -584,10 +581,9 @@ fn run_binary_stage( telemetry.clone(), ) .map_err(|error| anyhow!("create binary iteration scheduler: {error}"))?; - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_runtime_with_l3_manager( &config, - loaded_model_state_kind(Some(&runtime)), - loaded_memory_cache_capabilities(Some(&runtime)), + &runtime, l3_manager.clone(), None, )? @@ -603,7 +599,12 @@ fn run_binary_stage( } let prediction_returns = Arc::new(PredictionReturnHub::default()); let prediction_return_sinks = Arc::new(PredictionReturnSinks::default()); - let session_ownership = Arc::new(ConnectionSessionOwnership::default()); + // Connections may outnumber native lanes. Reserve each logical session + // globally before its first runtime operation, without holding the runtime + // lock while another connection finishes and releases its lane. + let session_ownership = Arc::new(ConnectionSessionOwnership::with_runtime_lanes( + lock_runtime(&runtime).lane_admission(), + )); let mut connection_workers = ConnectionWorkers::default(); let listener = TcpListener::bind(bind_addr)?; listener.set_nonblocking(true)?; diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs index 70fefee641..75fbdc5a1c 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs @@ -172,7 +172,7 @@ fn handle_binary_connection_messages( config.activation_codec_policy, max_inflight.max(1), discard_registry.clone(), - worker_control, + worker_control.clone(), )?; let mut async_forwarder = if async_prefill_forward || max_inflight > 1 { downstream @@ -208,7 +208,9 @@ fn handle_binary_connection_messages( let message_started = Instant::now(); let session_id = binary_message_session_id(connection_session_id, &message); let session_key = session_id.to_string(); - session_tracker.touch(&session_key)?; + session_tracker.touch_interruptible(&session_key, || { + worker_control.is_shutting_down() || inbound_reader.is_finished() + })?; emit_binary_message_received( telemetry, config, diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/message_receive.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/message_receive.rs index 60de55713a..3a4d702e4a 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/message_receive.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/message_receive.rs @@ -134,6 +134,7 @@ pub(super) struct InboundMessageReader { stopped: Arc, worker_control: Arc, holding_message: AtomicBool, + finished: Arc, } impl Drop for InboundMessageReader { @@ -177,7 +178,16 @@ pub(super) fn spawn_message_reader( let reader_queued_bytes = queued_bytes.clone(); let stopped = Arc::new(AtomicBool::new(false)); let reader_stopped = stopped.clone(); + let finished = Arc::new(AtomicBool::new(false)); + let reader_finished = finished.clone(); let thread = thread::spawn(move || { + struct FinishOnExit(Arc); + impl Drop for FinishOnExit { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } + } + let _finished = FinishOnExit(reader_finished); loop { // Back off while the parsed backlog is over the byte ceiling; the // executor decrements as it takes messages off the queue. @@ -253,10 +263,15 @@ pub(super) fn spawn_message_reader( stopped, worker_control: handle_control, holding_message: AtomicBool::new(false), + finished, }) } impl InboundMessageReader { + pub(super) fn is_finished(&self) -> bool { + self.finished.load(Ordering::Acquire) + } + /// EOF classification: a clean EOF before any traffic is a normal /// connection close, anything else is an error. pub(super) fn next( diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs index 662fd4758a..b6b3a3bb80 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs @@ -254,8 +254,9 @@ mod tests { skippy_cache::StoreLimits::new(1 << 20, 0), ) .unwrap(); - let config = prefix_cache_test_config(); - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let mut config = prefix_cache_test_config(); + config.source_model_sha256 = Some("ab".repeat(32)); + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/readout.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/readout.rs index 22db8570d7..c4d73a25e6 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/readout.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/readout.rs @@ -229,22 +229,14 @@ mod tests { #[test] #[ignore = "requires SKIPPY_DECISION_MODEL: a real resident-cache-capable GGUF"] fn readout_reply_preserves_prefix_recording_evidence() -> Result<()> { - use crate::runtime_state::{ - load_runtime, loaded_memory_cache_capabilities, loaded_model_state_kind, - }; + use crate::runtime_state::load_runtime; use skippy_protocol::binary::{StageStateHeader, WireMessageKind}; let config = cache_runtime_config()?; let runtime = load_runtime(&config)?.context("loaded runtime")?; let kv = Arc::new( - KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - loaded_model_state_kind(Some(&runtime)), - loaded_memory_cache_capabilities(Some(&runtime)), - None, - None, - )? - .context("resident prefix cache")?, + KvStageIntegration::from_runtime_with_l3_manager(&config, &runtime, None, None)? + .context("resident prefix cache")?, ); let telemetry = Telemetry::new( None, diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/session_tracker.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/session_tracker.rs index 24c73f0e28..1654f67cd5 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/session_tracker.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/session_tracker.rs @@ -17,6 +17,8 @@ use std::{ pub(super) struct ConnectionSessionOwnership { sessions: Mutex>, release_completed: Condvar, + capacity: Option, + runtime_lanes: Option>, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -29,6 +31,7 @@ pub(super) struct SessionLease { ownership: Arc, session_key: String, connection_id: u64, + runtime_lane: Mutex>, } pub(super) struct SessionRelease<'a> { @@ -40,6 +43,11 @@ impl Drop for SessionRelease<'_> { self.lease .ownership .finish_release(&self.lease.session_key, self.lease.connection_id); + self.lease + .runtime_lane + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); } } @@ -69,21 +77,71 @@ impl SessionLease { } impl ConnectionSessionOwnership { + pub(super) fn with_runtime_lanes( + lanes: Arc, + ) -> Self { + Self { + capacity: Some(lanes.capacity()), + runtime_lanes: Some(lanes), + ..Self::default() + } + } + + #[cfg(test)] + pub(super) fn with_capacity(capacity: usize) -> Self { + Self { + capacity: Some(capacity.max(1)), + ..Self::default() + } + } + + #[cfg(test)] pub(super) fn claim( self: &Arc, session_key: &str, connection_id: u64, ) -> Result { - let sessions = self + self.claim_interruptible(session_key, connection_id, || false) + } + + fn claim_interruptible( + self: &Arc, + session_key: &str, + connection_id: u64, + cancelled: impl Fn() -> bool, + ) -> Result { + let mut sessions = self .sessions .lock() .expect("binary session ownership registry lock poisoned"); - let mut sessions = self - .release_completed - .wait_while(sessions, |sessions| { - matches!(sessions.get(session_key), Some(SessionState::Releasing(_))) - }) - .expect("binary session ownership registry lock poisoned"); + loop { + if cancelled() { + bail!("binary session admission cancelled"); + } + let releasing = matches!(sessions.get(session_key), Some(SessionState::Releasing(_))); + let capacity_full = !sessions.contains_key(session_key) + && self + .capacity + .is_some_and(|capacity| sessions.len() >= capacity); + if capacity_full + && sessions + .values() + .any(|state| *state == SessionState::Owned(connection_id)) + { + // This connection must remain able to consume Stop for its + // existing sessions; waiting would hide that Stop behind the + // new session's admission indefinitely. + bail!("stop an active session before opening another beyond stage capacity"); + } + if !releasing && !capacity_full { + break; + } + sessions = self + .release_completed + .wait_timeout(sessions, std::time::Duration::from_millis(50)) + .expect("binary session ownership registry lock poisoned") + .0; + } // Never seize ownership from another live connection. Nonzero wire // session ids become session keys, so an observing peer could // otherwise replay a victim's live session id on its own connection @@ -97,13 +155,40 @@ impl ConnectionSessionOwnership { if seized_live_owner { bail!("stage session is owned by another live connection"); } + // HTTP can occupy lanes without an entry in this binary registry. A + // connection that already owns a session may only add another when a + // real runtime permit is immediately available: blocking here would + // prevent it from consuming Stop for its existing session. + let runtime_lane = if let Some(lanes) = &self.runtime_lanes + && sessions + .values() + .any(|state| *state == SessionState::Owned(connection_id)) + { + Some(lanes.try_acquire()?.ok_or_else(|| { + anyhow::anyhow!( + "stop an active session before opening another beyond stage capacity" + ) + })?) + } else { + None + }; + let needs_runtime_lane = runtime_lane.is_none(); sessions.insert(session_key.to_string(), SessionState::Owned(connection_id)); drop(sessions); - Ok(SessionLease { + let lease = SessionLease { ownership: self.clone(), session_key: session_key.to_string(), connection_id, - }) + runtime_lane: Mutex::new(runtime_lane), + }; + if needs_runtime_lane && let Some(lanes) = &self.runtime_lanes { + let permit = lanes.acquire_blocking(cancelled)?; + *lease + .runtime_lane + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(permit); + } + Ok(lease) } fn begin_release(&self, session_key: &str, connection_id: u64) -> bool { @@ -143,6 +228,8 @@ impl ConnectionSessionOwnership { if sessions.get(session_key) == Some(&SessionState::Owned(connection_id)) { sessions.remove(session_key); } + drop(sessions); + self.release_completed.notify_all(); } #[cfg(test)] @@ -182,11 +269,22 @@ impl ConnectionSessionTracker { } } + #[cfg(test)] pub(super) fn touch(&mut self, session_key: &str) -> Result<()> { + self.touch_interruptible(session_key, || false) + } + + pub(super) fn touch_interruptible( + &mut self, + session_key: &str, + cancelled: impl Fn() -> bool, + ) -> Result<()> { if self.active.contains_key(session_key) { return Ok(()); } - let lease = self.ownership.claim(session_key, self.connection_id)?; + let lease = + self.ownership + .claim_interruptible(session_key, self.connection_id, cancelled)?; self.active.insert(session_key.to_string(), lease); Ok(()) } @@ -312,6 +410,133 @@ mod tests { sync::{Arc, Mutex}, }; + #[test] + fn global_lane_admission_waits_for_another_connections_session_release() { + use std::{ + sync::atomic::{AtomicBool, Ordering}, + sync::mpsc, + time::Duration, + }; + let ownership = Arc::new(ConnectionSessionOwnership::with_capacity(1)); + let first = ownership.claim("first", 1).unwrap(); + let (waiting_tx, waiting_rx) = mpsc::channel(); + let (admitted_tx, admitted_rx) = mpsc::channel(); + let queued_owner = ownership.clone(); + let queued = std::thread::spawn(move || { + let notified = AtomicBool::new(false); + let second = queued_owner + .claim_interruptible("second", 2, || { + if !notified.swap(true, Ordering::AcqRel) { + waiting_tx.send(()).unwrap(); + } + false + }) + .unwrap(); + admitted_tx.send(()).unwrap(); + second + }); + waiting_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(admitted_rx.try_recv().is_err()); + // Native Stop/cleanup marks the ownership released only after the + // actual runtime session has been dropped. + drop(first.begin_release().unwrap()); + admitted_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + drop(queued.join().unwrap()); + drop(first); + assert_eq!(ownership.owner_count(), 0); + } + + #[test] + fn shutdown_cancels_capacity_wait_without_claiming_a_lane() { + let ownership = Arc::new(ConnectionSessionOwnership::with_capacity(1)); + let first = ownership.claim("first", 1).unwrap(); + assert!(ownership.claim_interruptible("second", 2, || true).is_err()); + assert!(first.still_owns()); + assert_eq!(ownership.owner_count(), 1); + } + + #[test] + fn same_connection_over_capacity_does_not_hide_its_queued_stop() { + let ownership = Arc::new(ConnectionSessionOwnership::with_capacity(1)); + let first = ownership.claim("first", 1).unwrap(); + let error = ownership + .claim("second", 1) + .err() + .expect("multiplexed session must not block its own Stop"); + assert!(error.to_string().contains("stop an active session")); + assert!(first.still_owns()); + drop(first.begin_release().unwrap()); + assert!(ownership.claim("second", 1).is_ok()); + } + + #[tokio::test] + async fn http_occupancy_cannot_make_a_second_binary_session_hide_stop() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let lanes = crate::runtime_state::lane_admission::RuntimeLaneAdmission::new(2); + let _http = lanes.acquire().await.unwrap(); + let ownership = Arc::new(ConnectionSessionOwnership::with_runtime_lanes(lanes)); + let first = ownership.claim("first", 1).unwrap(); + let checks = AtomicUsize::new(0); + // A regressed blocking claim is cancelled on its second poll so this + // regression fails deterministically instead of hanging the suite. + let error = ownership + .claim_interruptible("second", 1, || checks.fetch_add(1, Ordering::AcqRel) > 0) + .err() + .expect("an occupied runtime must refuse same-connection multiplexing"); + assert!(error.to_string().contains("stop an active session")); + assert_eq!(checks.load(Ordering::Acquire), 1); + assert_eq!(ownership.owner_count(), 1); + assert!(first.still_owns()); + } + + #[test] + fn same_binary_connection_can_use_an_available_second_runtime_lane() { + let lanes = crate::runtime_state::lane_admission::RuntimeLaneAdmission::new(2); + let ownership = Arc::new(ConnectionSessionOwnership::with_runtime_lanes(lanes)); + let first = ownership.claim("first", 1).unwrap(); + let second = ownership.claim("second", 1).unwrap(); + assert!(first.still_owns()); + assert!(second.still_owns()); + assert_eq!(ownership.owner_count(), 2); + } + + #[tokio::test] + async fn binary_session_waits_for_http_runtime_reservation() { + use std::{ + sync::atomic::{AtomicBool, Ordering}, + sync::mpsc, + time::Duration, + }; + let runtime = crate::runtime_state::RuntimeState::new_modelless_for_test(1); + let lanes = runtime.lane_admission(); + let http = lanes.acquire().await.unwrap(); + let ownership = Arc::new(ConnectionSessionOwnership::with_runtime_lanes(lanes)); + let queued_owner = ownership.clone(); + let (waiting_tx, waiting_rx) = mpsc::channel(); + let (admitted_tx, admitted_rx) = mpsc::channel(); + let queued = std::thread::spawn(move || { + let notified = AtomicBool::new(false); + let lease = queued_owner + .claim_interruptible("binary", 7, || { + if !notified.swap(true, Ordering::AcqRel) { + waiting_tx.send(()).unwrap(); + } + false + }) + .unwrap(); + admitted_tx.send(()).unwrap(); + lease + }); + waiting_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(admitted_rx.try_recv().is_err()); + drop(http); + admitted_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + let lease = queued.join().unwrap(); + drop(lease.begin_release().unwrap()); + drop(lease); + assert_eq!(ownership.owner_count(), 0); + } + fn tracker( connection_id: u64, ownership: &Arc, diff --git a/skippy/crates/skippy-serving/src/frontend.rs b/skippy/crates/skippy-serving/src/frontend.rs index 95ef391d20..5b07ca0618 100644 --- a/skippy/crates/skippy-serving/src/frontend.rs +++ b/skippy/crates/skippy-serving/src/frontend.rs @@ -1,6 +1,6 @@ use skippy_protocol::binary::StageSamplingConfig as WireSamplingConfig; -mod admission; +pub(crate) mod admission; mod backend; mod decode_scheduler; mod embedded_execution; diff --git a/skippy/crates/skippy-serving/src/frontend/admission.rs b/skippy/crates/skippy-serving/src/frontend/admission.rs index 6196ee3c43..7515380b61 100644 --- a/skippy/crates/skippy-serving/src/frontend/admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/admission.rs @@ -30,7 +30,7 @@ use std::time::Instant; pub const DECODE_BATCH_HEADROOM_TOKENS: usize = 512; #[derive(Debug)] -pub(super) struct GenerationTokenBudget { +pub(crate) struct GenerationTokenBudget { capacity_tokens: usize, state: Mutex, #[cfg(test)] @@ -57,6 +57,19 @@ pub(super) struct GenerationTokenReservation { } impl GenerationTokenBudget { + /// All frontends sharing a runtime reserve against one aggregate pool. + pub(crate) fn shared_for_runtime( + runtime: &mut crate::runtime_state::RuntimeState, + configured_tokens: usize, + ) -> Arc { + if let Some(budget) = runtime.generation_token_budget.as_ref() { + return Arc::clone(budget); + } + let budget = Arc::new(Self::for_runtime(runtime, configured_tokens)); + runtime.generation_token_budget = Some(Arc::clone(&budget)); + budget + } + /// Admission shares the loaded context's aggregate pool across its lanes. /// Modelless runtimes may leave capacity unknown; retain the caller's /// configured budget in that case without inferring a native allocation. @@ -340,6 +353,32 @@ mod tests { ); } + #[test] + fn multiple_frontends_share_one_runtime_token_reservation_pool() { + let mut runtime = + crate::runtime_state::RuntimeState::new_modelless_with_capacity_for_test(2, 1024); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512); + assert!(Arc::ptr_eq(&first, &second)); + let reservation = first + .try_reserve(GenerationTokenBudgetRequest::new(768, 0)) + .unwrap() + .unwrap(); + assert!( + second + .try_reserve(GenerationTokenBudgetRequest::new(512, 0)) + .unwrap() + .is_none() + ); + drop(reservation); + assert!( + second + .try_reserve(GenerationTokenBudgetRequest::new(512, 0)) + .unwrap() + .is_some() + ); + } + #[test] fn generation_token_budget_reserves_and_releases_tokens() { let budget = Arc::new(GenerationTokenBudget::new(1_024)); diff --git a/skippy/crates/skippy-serving/src/frontend/backend.rs b/skippy/crates/skippy-serving/src/frontend/backend.rs index 1bf7edaf8c..6d22130678 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend.rs @@ -4,6 +4,7 @@ mod inference; mod prepared_exchange; #[cfg(test)] mod prepared_exchange_tests; +mod runtime_admission; use crate::frontend::admission::GenerationTokenBudget; use crate::frontend::admission::GenerationTokenBudgetRequest; use crate::frontend::admission::GenerationTokenReservation; @@ -563,6 +564,7 @@ impl GenerationAdmissionController { )?; match claim { GenerationAdmissionClaim::Acquired(resources) => Ok(GenerationAdmissionPermit { + _runtime_lane: None, _lane: self.generation_limit.wrap_permit(resources.lane), token_budget: resources.token_budget, _active_work: self.generation_service_estimator.start_active(work), @@ -588,6 +590,7 @@ impl GenerationAdmissionController { ) .await?; Ok(GenerationAdmissionPermit { + _runtime_lane: None, _lane: self.generation_limit.wrap_permit(resources.lane), token_budget: resources.token_budget, _active_work: queued_work.promote(), @@ -604,6 +607,7 @@ impl GenerationAdmissionController { } pub(in crate::frontend) struct GenerationAdmissionPermit { + _runtime_lane: Option, token_budget: GenerationTokenReservation, _lane: GenerationConcurrencyPermit, _active_work: GenerationActiveWorkReservation, @@ -895,6 +899,7 @@ impl StageOpenAiBackend { work: GenerationAdmissionWork, scheduling: GenerationAdmissionScheduling, ) -> InferenceResult<(GenerationAdmissionPermit, Option)> { + let admission_started = Instant::now(); let result = GenerationAdmissionController::for_backend(self) .acquire_scheduled_work( ids, @@ -904,6 +909,19 @@ impl StageOpenAiBackend { scheduling, ) .await; + let result = match result { + Ok((mut permit, session)) => match self + .acquire_runtime_lane(admission_started, cancellation) + .await + { + Ok(runtime_lane) => { + permit._runtime_lane = Some(runtime_lane); + Ok((permit, session)) + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + }; if let Err(error) = &result { let mut attrs = self.openai_attrs(ids); attrs.insert( diff --git a/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs b/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs new file mode 100644 index 0000000000..0bf24d0bc9 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs @@ -0,0 +1,40 @@ +//! Bound frontend work by the execution lanes shared with binary stage clients. +use super::{StageOpenAiBackend, generation_queue_timeout_error, request_cancelled_error}; +use crate::runtime_state::lane_admission::RuntimeLanePermit; +use crate::runtime_state::panic_recovery::lock_runtime; +use skippy_inference_api::{CancellationToken, InferenceError, InferenceResult}; +use std::time::Instant; + +impl StageOpenAiBackend { + pub(super) async fn acquire_runtime_lane( + &self, + admission_started: Instant, + cancellation: &CancellationToken, + ) -> InferenceResult { + let lanes = lock_runtime(&self.runtime).lane_admission(); + let deadline = if self.generation_admission_timeout.is_zero() { + None + } else { + Some( + admission_started + .checked_add(self.generation_admission_timeout) + .ok_or_else(|| { + InferenceError::backend("runtime lane admission deadline overflow") + })?, + ) + }; + let timeout = async { + if let Some(deadline) = deadline { + tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await; + } else { + std::future::pending::<()>().await; + } + }; + tokio::select! { + biased; + () = cancellation.cancelled() => Err(request_cancelled_error()), + () = timeout => Err(generation_queue_timeout_error(self.generation_admission_timeout)), + permit = lanes.acquire() => permit.map_err(|error| InferenceError::backend(format!("{error:#}"))), + } + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs index d702b919a2..3fad40b42e 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests/admission.rs @@ -2,6 +2,54 @@ use super::*; use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS; +#[tokio::test] +async fn http_admission_waits_for_binary_work_on_the_same_runtime() { + let backend = super::hooks_test_backend(None); + let lanes = backend.runtime.lock().unwrap().lane_admission(); + let binary = lanes.acquire_blocking(|| false).unwrap(); + let ids = trusted_ids("http-waiting-for-binary"); + let cancellation = skippy_inference_api::CancellationToken::new(); + let mut waiting = Box::pin(backend.acquire_generation_admission( + &ids, + &cancellation, + GenerationAdmissionWork::default(), + GenerationAdmissionScheduling::default(), + )); + assert!(futures_util::poll!(&mut waiting).is_pending()); + assert!( + backend.runtime.try_lock().is_ok(), + "capacity wait must not hold the runtime lock" + ); + drop(binary); + let admitted = tokio::time::timeout(Duration::from_secs(5), waiting) + .await + .unwrap() + .unwrap(); + assert_eq!(backend.generation_limit.available_permits(), 0); + drop(admitted); + assert_eq!(backend.generation_limit.available_permits(), 1); +} + +#[tokio::test] +async fn cancelled_http_runtime_lane_wait_releases_frontend_reservations() { + let backend = super::hooks_test_backend(None); + let lanes = backend.runtime.lock().unwrap().lane_admission(); + let _binary = lanes.acquire_blocking(|| false).unwrap(); + let ids = trusted_ids("cancelled-http-runtime-wait"); + let cancellation = skippy_inference_api::CancellationToken::new(); + let mut waiting = Box::pin(backend.acquire_generation_admission( + &ids, + &cancellation, + GenerationAdmissionWork::default(), + GenerationAdmissionScheduling::default(), + )); + assert!(futures_util::poll!(&mut waiting).is_pending()); + cancellation.cancel(); + assert!(waiting.await.is_err()); + assert_eq!(backend.generation_limit.available_permits(), 1); + assert!(backend.generation_session_locks.lock().unwrap().is_empty()); +} + fn trusted_ids(session_id: &str) -> InferenceGenerationIds { InferenceGenerationIds::new_with_trust( InferenceCacheHints::default(), @@ -895,6 +943,13 @@ async fn blocking_worker_holds_global_and_session_permits_until_work_finishes() let worker_context = InferenceRequestContext::new(); let worker_started = Arc::new(std::sync::atomic::AtomicBool::new(false)); let release_worker = Arc::new(std::sync::atomic::AtomicBool::new(false)); + struct ReleaseWorker(Arc); + impl Drop for ReleaseWorker { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } + } + let _release_on_unwind = ReleaseWorker(release_worker.clone()); let started = worker_started.clone(); let release = release_worker.clone(); @@ -945,8 +1000,8 @@ async fn blocking_worker_holds_global_and_session_permits_until_work_finishes() ); } -#[test] -fn untrusted_conversation_affinity_bypasses_session_registry() { +#[tokio::test] +async fn untrusted_conversation_affinity_bypasses_session_registry() { let registry = Arc::new(Mutex::new(BTreeMap::new())); let untrusted = InferenceGenerationIds::new_with_trust( InferenceCacheHints::default(), @@ -957,6 +1012,21 @@ fn untrusted_conversation_affinity_bypasses_session_registry() { assert!(trusted_generation_session_key(&untrusted).is_none()); assert!(registry.lock().expect("session registry lock").is_empty()); + let controller = admission_controller(1, 1); + let cancellation = skippy_inference_api::CancellationToken::new(); + let (_generation_permit, session_permit) = controller + .acquire(&untrusted, &cancellation, Duration::from_secs(1)) + .await + .expect("untrusted request still obtains global admission"); + assert!(session_permit.is_none()); + assert!( + controller + .generation_session_locks + .lock() + .unwrap() + .is_empty() + ); + let trusted = trusted_ids("agent-7"); let key = trusted_generation_session_key(&trusted).expect("trusted session key"); assert_eq!(key, trusted.session_id_string()); diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index f290ac8ae6..07772d0cb7 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -27,7 +27,7 @@ use crate::frontend::speculative::{SpeculativeDecodeConfig, standalone_ngram_pro use crate::kv_integration::KvStageIntegration; use crate::listener::bind_serve_listener; use crate::runtime_state::RuntimeState; -use crate::runtime_state::{loaded_memory_cache_capabilities, loaded_model_state_kind}; +use crate::runtime_state::loaded_model_state_kind; use crate::telemetry::Telemetry; use crate::telemetry::lifecycle_attrs; use crate::telemetry::now_unix_nanos; @@ -410,10 +410,9 @@ fn embedded_openai_backend_with_state_kind( "stage.openai_runtime_prewarm", ) .context("prewarm embedded OpenAI runtime sessions")?; - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_runtime_with_l3_manager( &args.config, - loaded_model_state_kind(Some(&args.runtime)), - loaded_memory_cache_capabilities(Some(&args.runtime)), + &args.runtime, args.l3_manager.clone(), args.kv_lifecycle_observer.clone(), )? @@ -429,8 +428,8 @@ fn embedded_openai_backend_with_state_kind( } let ctx_size = usize::try_from(args.config.ctx_size).unwrap_or(usize::MAX); let generation_token_budget = { - let runtime = crate::runtime_state::panic_recovery::lock_runtime(&args.runtime); - Arc::new(GenerationTokenBudget::for_runtime(&runtime, ctx_size)) + let mut runtime = crate::runtime_state::panic_recovery::lock_runtime(&args.runtime); + GenerationTokenBudget::shared_for_runtime(&mut runtime, ctx_size) }; let iteration_scheduler = match iteration_scheduler { Some(iteration_scheduler) => iteration_scheduler, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs index e3222c7852..2f199fb279 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs @@ -76,10 +76,9 @@ fn backend(root: &Path) -> Result { 2, )?; let manager = L3CacheManager::acquire(root, StoreLimits::new(4 << 30, 0))?; - backend.kv = KvStageIntegration::from_loaded_model_with_l3_manager( + backend.kv = KvStageIntegration::from_runtime_with_l3_manager( &backend.config, - crate::runtime_state::loaded_model_state_kind(Some(&backend.runtime)), - crate::runtime_state::loaded_memory_cache_capabilities(Some(&backend.runtime)), + &backend.runtime, Some(manager), None, )? diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs index 9ef8005682..d617ede612 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs @@ -24,6 +24,69 @@ impl Drop for PendingPrefill { } } +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn prefill_only_resident_recurrent_request_retains_shared_grid_checkpoint() -> Result<()> { + let (backend, speculative) = recurrent_test_backend_with_lanes( + "prefill-only-checkpoint", + "prefill-only-checkpoint", + 1024, + 64, + 0, + 1024, + 1, + )?; + let kv = backend.kv.as_ref().unwrap(); + let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(16); + let boundary = kv + .exact_shared_checkpoint_token_count((tokens.len() - 1) as u64) + .unwrap() as usize; + let ids = InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("prefill-only-checkpoint"), + true, + None, + ); + let sampling = SamplingConfig { + enabled: false, + ..Default::default() + }; + let mut emitted = 0; + backend.generate_local_tokens( + LocalGeneration { + prompt_token_ids: &tokens, + recurrent_cache_prefix_token_ids: None, + max_tokens: 0, + sampling: &sampling, + chat_sampling_metadata: None, + speculative: &speculative, + native_mtp_enabled: false, + hook_request: None, + hook_runtime: None, + cancellation: None, + ids: &ids, + }, + |_| { + emitted += 1; + Ok(TokenControl::Continue) + }, + )?; + assert_eq!(emitted, 0); + kv.wait_for_exact_state_captures_idle(Duration::from_secs(30)) + .map_err(anyhow::Error::msg)?; + let base = backend.local_kv_message_base(&ids.session_label, &ids); + let checkpoint = kv.prefill_identity(&backend.config, &base, 0, &tokens[..boundary]); + let mut divergent = tokens[..boundary].to_vec(); + divergent.extend([11, 12]); + let probe = kv.prefill_identity(&backend.config, &base, 0, &divergent); + assert_eq!( + kv.probe_resident_prefix(&probe).unwrap().token_count, + boundary + ); + assert!(kv.retained_exact_identity(&checkpoint.namespace, &tokens[..boundary])); + Ok(()) +} + #[test] #[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] fn resident_checkpoint_prefill_yields_to_decode_and_cancels_without_losing_checkpoint() -> Result<()> diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index c5717f6855..dcbc05dbff 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -14,10 +14,9 @@ fn backend_with_disk(root: &Path, disk_bytes: u64) -> Result 512, )?; let manager = L3CacheManager::acquire(root, StoreLimits::new(disk_bytes, 0))?; - backend.kv = KvStageIntegration::from_loaded_model_with_l3_manager( + backend.kv = KvStageIntegration::from_runtime_with_l3_manager( &backend.config, - crate::runtime_state::loaded_model_state_kind(Some(&backend.runtime)), - crate::runtime_state::loaded_memory_cache_capabilities(Some(&backend.runtime)), + &backend.runtime, Some(manager), None, )? @@ -73,6 +72,15 @@ fn native_cold_prefix_survives_runtime_restart() -> Result<()> { .record_resident_prefix(&mut runtime, "source", &stored, &tokens)? .expect("native checkpoint captured"); assert!(record.stored); + assert!(kv.probe_resident_prefix(&stored).is_some()); + assert!( + kv.l3 + .as_ref() + .unwrap() + .locate_longest(&stored.namespace, &tokens, 1)? + .is_none(), + "recording a resident prefix must not eagerly export it to L3" + ); let output = inputs .iter() .map(|&token| runtime.decode("source", token)) diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index ab983c010f..2d346be75d 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -3,6 +3,22 @@ use super::*; const RECURRENT_TEST_CHECKPOINT_RAM_BYTES: u64 = 8 * 1024 * 1024 * 1024; +#[test] +#[ignore = "requires a packaged native runtime; run alone in a fresh test process"] +fn kv_validation_dynamic_runtime_identity() { + #[cfg(not(feature = "dynamic-native-runtime"))] + panic!("KV validation requires dynamically linked serving tests"); + #[cfg(feature = "dynamic-native-runtime")] + { + assert!( + !skippy_runtime::native_runtime_loaded(), + "runtime identity probe must run alone in a fresh process" + ); + skippy_runtime::test_support::require_native_runtime(); + assert!(skippy_runtime::native_runtime_loaded()); + } +} + pub(super) fn recurrent_test_backend( run_id: &str, backend_model_id: &str, @@ -53,7 +69,7 @@ pub(super) fn recurrent_test_backend_with_lanes( package_ref: None, manifest_sha256: None, source_model_path: None, - source_model_sha256: None, + source_model_sha256: Some(model_digest(std::path::Path::new(&model_path))?), source_model_bytes: None, materialized_path: None, materialized_pinned: false, @@ -173,3 +189,74 @@ pub(super) fn recurrent_test_backend_with_lanes( }; Ok((backend, speculative)) } + +fn model_digest(path: &std::path::Path) -> Result { + use sha2::{Digest, Sha256}; + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut digest = Sha256::new(); + let mut buffer = [0_u8; 64 * 1024]; + loop { + let read = file.read(&mut buffer)?; + if read == 0 { + return Ok(digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()); + } + digest.update(&buffer[..read]); + } +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn loaded_runtime_admission_uses_aggregate_pool_across_frontends() -> Result<()> { + use crate::frontend::admission::{GenerationTokenBudget, GenerationTokenBudgetRequest}; + let (backend, _) = recurrent_test_backend_with_lanes( + "aggregate-admission", + "aggregate-admission", + 512, + 64, + 1, + 1024, + 2, + )?; + let mut runtime = backend.runtime.lock().unwrap(); + let per_lane = runtime.context_tokens_per_lane() as usize; + assert_eq!(runtime.kv_pool_tokens() as usize, per_lane * 2); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane); + assert!(Arc::ptr_eq(&first, &second)); + let _reservation = first + .try_reserve(GenerationTokenBudgetRequest::new(per_lane + 1, 0))? + .expect("aggregate pool admits more than one lane's capacity"); + assert!( + second + .try_reserve(GenerationTokenBudgetRequest::new(per_lane, 0))? + .is_none() + ); + Ok(()) +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn prewarmed_http_idle_lane_is_reused_by_binary_work() -> Result<()> { + let (backend, _) = + recurrent_test_backend("shared-idle-lane", "shared-idle-lane", 512, 64, 1, 512)?; + let lanes = backend.runtime.lock().unwrap().lane_admission(); + { + let mut runtime = backend.runtime.lock().unwrap(); + let warm = runtime.prewarm_idle_sessions(1)?; + assert_eq!(warm.active_sessions, 0); + assert_eq!(warm.idle_sessions, 1); + } + let _binary = lanes.acquire_blocking(|| false)?; + let mut runtime = backend.runtime.lock().unwrap(); + runtime.prefill("binary-after-http-prewarm", &[1, 2, 3, 4])?; + assert_eq!(runtime.session_stats().active_sessions, 1); + assert_eq!(runtime.session_stats().idle_sessions, 0); + runtime.drop_session_timed("binary-after-http-prewarm")?; + assert_eq!(runtime.session_stats().idle_sessions, 1); + Ok(()) +} diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index 4b8d6f526a..eee0edc7bb 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -933,7 +933,7 @@ impl StageOpenAiBackend { let recurrent_checkpoint_required = self .kv .as_ref() - .is_some_and(|kv| kv.payload == StagePrefixCachePayload::KvRecurrent); + .is_some_and(|kv| kv.retains_recurrent_checkpoints()); let resume_scheduler_decode = prompt_prefill_sample.is_some() && !state.stopped && state.decoded_tokens < request.max_tokens as usize diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index a11800ca6e..b35aa2247b 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -3,9 +3,9 @@ use super::*; pub(super) fn deferred_suffix_prefill_enabled( scheduling: Option, - max_tokens: u32, + _max_tokens: u32, ) -> bool { - max_tokens > 0 && scheduling.is_some_and(CacheSchedulingPolicy::cooperative) + scheduling.is_some_and(CacheSchedulingPolicy::cooperative) } fn deferred_suffix_split( @@ -199,13 +199,17 @@ impl StageOpenAiBackend { session_id, &request.prompt_token_ids[suffix_start..], request.sampling.enabled.then_some(request.sampling), - true, + max_tokens > 0, cache_operation_deadline, request.cancellation, )?; - prompt_prefill_sample = Some(suffix_outcome.predicted.ok_or_else(|| { - InferenceError::backend("deferred suffix prefill was not sampled") - })?); + prompt_prefill_sample = if max_tokens > 0 { + Some(suffix_outcome.predicted.ok_or_else(|| { + InferenceError::backend("deferred suffix prefill was not sampled") + })?) + } else { + None + }; prefill_chunk_count = if prefill_chunk_count == 1 { suffix_outcome.chunk_count } else { @@ -651,16 +655,12 @@ fn resident_kv_suffix_prefill_stays_inside_the_cache_operation() { #[cfg(test)] #[test] -fn recurrent_suffix_prefill_requires_a_nonzero_generation_budget() { +fn recurrent_suffix_prefill_includes_prefill_only_requests() { assert!(deferred_suffix_prefill_enabled( Some(CacheSchedulingPolicy::Cooperative), 1, )); assert!(deferred_suffix_prefill_enabled( - Some(CacheSchedulingPolicy::Cooperative), - 1, - )); - assert!(!deferred_suffix_prefill_enabled( Some(CacheSchedulingPolicy::Cooperative), 0, )); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index b1c8d766ec..d0856ee9e2 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -231,9 +231,25 @@ impl StageOpenAiBackend { let base = self.local_kv_message_base(session_id, ids); let identity = kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens); if kv.records_resident_prefixes() { - let recorded = kv - .record_resident_prefix(runtime, session_id, &identity, checkpoint_tokens) - .is_ok_and(|record| record.is_some()); + let recorded = match kv.record_resident_prefix( + runtime, + session_id, + &identity, + checkpoint_tokens, + ) { + Ok(record) => record.is_some(), + Err(error) => { + let mut attrs = self.openai_attrs(ids); + attrs.insert( + "skippy.kv.decision".to_string(), + json!(format!("{decision_prefix}_error")), + ); + attrs.insert("skippy.kv.error".to_string(), json!(format!("{error:#}"))); + self.telemetry + .emit("stage.openai_kv_record_decision", attrs); + false + } + }; #[cfg(test)] { if recorded && decision_prefix == "post_decode_checkpoint" { diff --git a/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs b/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs index 86dfb072bc..f7d76ae050 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs @@ -49,14 +49,8 @@ async fn loaded_runtime_selects_cache_and_reuses_immediate_repeat() -> Result<() let model = config.model_id.clone(); let mut backend = support::local_openai_backend(config.clone(), model.clone())?; let kv = Arc::new( - KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - loaded_model_state_kind(Some(&backend.runtime)), - loaded_memory_cache_capabilities(Some(&backend.runtime)), - None, - None, - )? - .context("fixture must enable cache recording")?, + KvStageIntegration::from_runtime_with_l3_manager(&config, &backend.runtime, None, None)? + .context("fixture must enable cache recording")?, ); assert_eq!( kv.payload, diff --git a/skippy/crates/skippy-serving/src/frontend/tests/causal_decisions.rs b/skippy/crates/skippy-serving/src/frontend/tests/causal_decisions.rs index 843744e802..01231fb8be 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/causal_decisions.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/causal_decisions.rs @@ -1,7 +1,6 @@ //! Explicit real-model HTTP proof; no synthetic fixture can certify readout scores. use super::*; -use crate::runtime_state::{loaded_memory_cache_capabilities, loaded_model_state_kind}; use axum::body::{Body, to_bytes}; use axum::http::Request; use tower::ServiceExt; @@ -89,14 +88,9 @@ fn backend_with_config(config: StageConfig) -> Result { None, backend.telemetry.clone(), )?; - backend.kv = KvStageIntegration::from_loaded_model_with_l3_manager( - &config, - loaded_model_state_kind(Some(&backend.runtime)), - loaded_memory_cache_capabilities(Some(&backend.runtime)), - None, - None, - )? - .map(Arc::new); + backend.kv = + KvStageIntegration::from_runtime_with_l3_manager(&config, &backend.runtime, None, None)? + .map(Arc::new); if config .kv_cache .as_ref() diff --git a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs index ab85d3b7f2..6a75e53da7 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -177,7 +177,7 @@ mod checkpoint_matching_tests { ..StageConfig::default() }; // An arbitrary state-kind label cannot override the loaded memory contract. - let integration = KvStageIntegration::from_loaded_model_with_l3_manager( + let integration = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(skippy_runtime::ModelStateKind::Dense), Some(MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 7854d4203a..f747198f91 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -24,6 +24,7 @@ use super::cache_payload::{durable_cache_payload, effective_cache_payload}; pub(super) mod durable_spill; mod exact_state_limits; mod resident_policy; +mod runtime_identity; use durable_spill::{ DurableRecordTarget, PendingDurableSpill, spill_exact_record_to_l3, start_durable_spill_worker, }; @@ -72,6 +73,7 @@ impl KvStageIntegration { config, model_state_kind, memory_cache, + None, || l3_manager_from_env(config), observer, ) @@ -91,6 +93,7 @@ impl KvStageIntegration { config, model_state_kind, memory_cache, + None, || Ok(manager), observer, ) @@ -100,6 +103,9 @@ impl KvStageIntegration { config: &StageConfig, model_state_kind: Option, memory_cache: Option, + loaded_model_content: Option< + Arc, + >, manager: impl FnOnce() -> Result>, observer: Option>, ) -> Result> { @@ -133,7 +139,11 @@ impl KvStageIntegration { }; let payload_selection_reason = "loaded_graph_and_memory"; let dense_without_recurrent = admitted.resident && !admitted.resident_checkpoint; - let l3_manager = manager()?; + let l3_manager = if loaded_model_content.is_some() { + manager()? + } else { + None + }; if !admitted.resident && cache_config.l2_max_bytes > 0 && l3_manager.is_none() { let _ = skippy_events::diagnostics::emit( skippy_events::diagnostics::ServingDiagnostic::Warning { @@ -150,7 +160,9 @@ impl KvStageIntegration { .and_then(|_| durable_cache_payload(admitted)); let l3 = l3_manager .zip(durable_payload) - .map(|(manager, payload)| l3_tier_for_manager(config, payload, manager)) + .map(|(manager, payload)| { + l3_tier_for_manager(config, payload, manager, loaded_model_content.as_deref()) + }) .transpose()?; let l2 = l3 .as_ref() @@ -160,7 +172,10 @@ impl KvStageIntegration { super::l2_serving::StageL2::new( cache_config.l2_max_bytes, numerical_model_identity_for_stage(config), - exact_state_identity_for_stage(config, l3_payload_kind(payload)), + bind_model_content( + loaded_model_content.as_deref(), + exact_state_identity_for_stage(config, l3_payload_kind(payload)), + ), ) }); // Complete exporters are admitted by the native graph and memory; state @@ -338,6 +353,7 @@ impl KvStageIntegration { durable_spill_tx, )); Ok(Some(Self { + loaded_model_content, mode, payload, payload_selection_reason, @@ -488,8 +504,12 @@ fn l3_tier_for_manager( config: &StageConfig, payload: StagePrefixCachePayload, manager: L3CacheManager, + content: Option<&crate::runtime_state::model_content::VerifiedModelContent>, ) -> Result> { - let identity = exact_state_identity_for_stage(config, l3_payload_kind(payload)); + let identity = bind_model_content( + content, + exact_state_identity_for_stage(config, l3_payload_kind(payload)), + ); let model_identity = numerical_model_identity_for_stage(config); let root = manager.root().display().to_string(); let tier = manager.tier_for_model(model_identity, identity, L3_SEGMENT_BYTES); @@ -523,6 +543,16 @@ fn l3_tier_for_manager( Ok(Arc::new(tier)) } +fn bind_model_content( + content: Option<&crate::runtime_state::model_content::VerifiedModelContent>, + identity: String, +) -> String { + match content { + Some(proof) => proof.bind(&identity), + None => identity, + } +} + fn l3_payload_kind(payload: StagePrefixCachePayload) -> &'static str { match payload { StagePrefixCachePayload::KvRecurrent => "kv-recurrent", @@ -912,7 +942,7 @@ fn cache_disabled_by_env(kv_cache: Option<&str>, prefix_cache: Option<&str>) -> .any(|value| parse_cache_mode(value) == Some(StageKvCacheMode::Disabled)) } -fn effective_cache_config(config: &StageConfig) -> Option { +pub(super) fn effective_cache_config(config: &StageConfig) -> Option { // An explicit environment kill-switch beats the planned stage config so // benches and incident response can turn the prefix cache off without // replanning the topology. @@ -1614,6 +1644,7 @@ mod tests { fn enabled_auto_config(model_id: &str) -> StageConfig { let mut config = test_config(model_id); + config.source_model_sha256 = Some("ab".repeat(32)); config.kv_cache = Some(StageKvCacheConfig { exact_max_bytes: None, mode: StageKvCacheMode::LookupRecord, diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs index afdcc5366b..ae9e4c0921 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/durable_spill.rs @@ -182,6 +182,18 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( l3_cost, native_raw, } = pending; + // Native eviction already owns the runtime and resident index. Resolve + // committed disk entries here on the durable worker, never under either + // scheduler lock. The in-flight claim remains held across this lookup. + if native_raw + && l3 + .locate_longest(&namespace, &token_ids, 1) + .is_ok_and(|entry| { + entry.is_some_and(|entry| entry.token_count == token_ids.len() as u64) + }) + { + return; + } let kv_desc_json = extra .kv_desc .as_ref() diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs new file mode 100644 index 0000000000..540cbcede7 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs @@ -0,0 +1,60 @@ +//! Bind cache construction to proof of the runtime's loaded model inputs. +use super::*; + +impl KvStageIntegration { + /// Construct durable reuse only from proof of the runtime's actual inputs. + /// Raw StageConfig constructors retain in-memory caching without disk reuse. + pub fn from_runtime_with_l3_manager( + config: &StageConfig, + runtime: &Arc>, + manager: Option, + observer: Option>, + ) -> Result> { + let (kind, memory, content) = { + let runtime = crate::runtime_state::panic_recovery::lock_runtime(runtime); + let capability = runtime.model.capability(); + ( + capability.as_ref().map(|value| value.state_kind), + capability.as_ref().map(|value| value.cache_capabilities), + runtime.verified_model_content.clone(), + ) + }; + // Verification stays outside the runtime lock. Unix can reuse the + // load-time digest through a strong file fingerprint; other platforms + // recheck bytes when equivalent identity/change-time evidence is absent. + let content = content.filter(|proof| proof.still_matches(config)); + Self::from_loaded_model_with_l3(config, kind, memory, content, || Ok(manager), observer) + } + + #[cfg(test)] + pub(crate) fn from_test_model_with_l3_manager( + config: &StageConfig, + model_state_kind: Option, + memory_cache: Option, + manager: Option, + observer: Option>, + ) -> Result> { + // Unit fixtures have no native model. Supply actual deterministic file + // content through the same verifier rather than authorizing a declared + // digest or creating a production escape hatch. + let root = tempfile::tempdir()?; + let path = root.path().join("model.gguf"); + std::fs::write(&path, config.model_id.as_bytes())?; + let mut proof_config = config.clone(); + proof_config.model_path = Some(path.to_string_lossy().into_owned()); + proof_config.model_part_paths.clear(); + proof_config.projector_path = None; + proof_config.checkpoint_imatrix = None; + let content = + crate::runtime_state::model_content::VerifiedModelContent::observe(&proof_config)? + .map(Arc::new); + Self::from_loaded_model_with_l3( + config, + model_state_kind, + memory_cache, + content, + || Ok(manager), + observer, + ) + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs index ff385f3920..40da18eb11 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs @@ -155,7 +155,7 @@ fn blocked_l3_spill_does_not_head_of_line_block_later_l1_records() { let _ = std::fs::remove_dir_all(&root); let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); let config = enabled_auto_config("future/model"); - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs index 5e6691f462..5c3407d6ce 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs @@ -2,6 +2,134 @@ use super::*; use skippy_protocol::StageDevice; +#[test] +fn absent_weight_identity_disables_disk_without_disabling_native_cache() { + let root = tempfile::tempdir().unwrap(); + let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1_000_000, 0)).unwrap(); + let mut config = enabled_auto_config("mutable-model-id"); + config.source_model_sha256 = None; + config.manifest_sha256 = None; + config.package_ref = Some("mutable/package".into()); + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident: true, + resident_attention: true, + resident_checkpoint: false, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .unwrap(); + assert_eq!(kv.payload, StagePrefixCachePayload::ResidentKv); + assert!(kv.l3.is_none()); + assert!(kv.l2.is_none()); + assert!(kv.durable_payload.is_none()); +} + +#[test] +fn well_formed_declared_hashes_do_not_authorize_raw_config_disk_reuse() { + let root = tempfile::tempdir().unwrap(); + let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1_000_000, 0)).unwrap(); + let mut config = enabled_auto_config("forged-weight-identity"); + config.source_model_sha256 = Some("ab".repeat(32)); + config.manifest_sha256 = Some("cd".repeat(32)); + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident: true, + resident_attention: true, + resident_checkpoint: false, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .unwrap(); + assert!(kv.records_resident_prefixes()); + assert!(kv.l3.is_none()); + assert!(kv.durable_payload.is_none()); +} + +#[test] +fn actual_weight_content_separates_disk_and_prefix_keys_under_one_claimed_identity() { + use crate::runtime_state::model_content::VerifiedModelContent; + let root = tempfile::tempdir().unwrap(); + let model = root.path().join("model.gguf"); + let disk = root.path().join("cache"); + let manager = L3CacheManager::acquire(&disk, StoreLimits::new(1_000_000, 0)).unwrap(); + let mut config = enabled_auto_config("same-model-name"); + config.model_path = Some(model.to_string_lossy().into_owned()); + config.source_model_sha256 = Some("ab".repeat(32)); + config.manifest_sha256 = Some("cd".repeat(32)); + let create = || { + let content = VerifiedModelContent::observe(&config) + .unwrap() + .map(Arc::new); + KvStageIntegration::from_loaded_model_with_l3( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident: true, + resident_attention: true, + resident_checkpoint: false, + kv_recurrent: true, + full_state: true, + }), + content, + || Ok(Some(manager.clone())), + None, + ) + .unwrap() + .unwrap() + }; + std::fs::write(&model, b"first numerical weights").unwrap(); + let first = create(); + let same = create(); + assert_eq!( + first.l3.as_ref().unwrap().state_identity(), + same.l3.as_ref().unwrap().state_identity() + ); + std::fs::write(&model, b"other numerical weights").unwrap(); + let changed = create(); + let first_l3 = first.l3.as_ref().unwrap(); + let changed_l3 = changed.l3.as_ref().unwrap(); + assert_eq!( + first_l3.model_identity(), + changed_l3.model_identity(), + "canonical model lifecycle remains shared" + ); + assert_ne!(first_l3.state_identity(), changed_l3.state_identity()); + let base = skippy_protocol::MessageBase { + schema_version: skippy_protocol::SCHEMA_VERSION, + run_id: "run".into(), + request_id: "request".into(), + session_id: "session".into(), + stage_id: "stage-0".into(), + stage_index: 0, + topology_id: "topology".into(), + model_id: Some(config.model_id.clone()), + tokenizer_id: None, + chat_template_id: None, + seq: None, + }; + let old_prefix = first.prefill_identity(&config, &base, 0, &[1, 2, 3]); + let changed_prefix = changed.prefill_identity(&config, &base, 0, &[1, 2, 3]); + assert_ne!(old_prefix.namespace, changed_prefix.namespace); + assert_ne!(old_prefix.page_id, changed_prefix.page_id); + assert_ne!( + old_prefix.identity.prefix_hash, + changed_prefix.identity.prefix_hash + ); +} + #[test] fn either_cache_kill_switch_disables_the_cache() { assert!(!cache_disabled_by_env(None, None)); @@ -28,7 +156,7 @@ fn injected_manager_is_shared_across_placement_equivalent_stages() { ..first.clone() }; - let first = KvStageIntegration::from_loaded_model_with_l3_manager( + let first = KvStageIntegration::from_test_model_with_l3_manager( &first, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -43,7 +171,7 @@ fn injected_manager_is_shared_across_placement_equivalent_stages() { ) .unwrap() .unwrap(); - let second = KvStageIntegration::from_loaded_model_with_l3_manager( + let second = KvStageIntegration::from_test_model_with_l3_manager( &second, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -88,7 +216,7 @@ fn native_resident_cache_does_not_materialize_a_duplicate_disk_payload() { let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); let config = enabled_auto_config("future/model"); - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -133,7 +261,7 @@ fn cache_ram_budget_enables_stage_l2_with_disk_authority() { let root = tempfile::tempdir().unwrap(); let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 30, 0)).unwrap(); - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -168,7 +296,7 @@ fn native_checkpoint_ram_budget_works_without_disk() { .expect("enabled cache config") .l2_max_bytes = 64 * 1024 * 1024; - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Hybrid), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs index dcaacd88d1..7cc38c3da3 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -81,6 +81,7 @@ mod tests { let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 20, 0)).unwrap(); let config = StageConfig { layer_end: 1, + source_model_sha256: Some("ab".repeat(32)), kv_cache: Some(StageKvCacheConfig { mode: StageKvCacheMode::LookupRecord, min_tokens: 1, @@ -94,7 +95,7 @@ mod tests { }), ..StageConfig::default() }; - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/snapshot_headroom.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/snapshot_headroom.rs index ac3ee6fabe..7186c44b37 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/snapshot_headroom.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/snapshot_headroom.rs @@ -22,7 +22,7 @@ pub(crate) const HOST_RESERVE_DIVISOR: u64 = 16; static RESERVED_BYTES: Mutex = Mutex::new(0); #[derive(Debug)] -pub(super) struct SnapshotReservation { +pub(in crate::kv_integration) struct SnapshotReservation { bytes: u64, counter: &'static Mutex, } @@ -118,9 +118,9 @@ fn warn(message: &str, context: String) { impl KvStageIntegration { /// Sizes the snapshot through the native size-only queries, then checks it /// against host memory read now, before any state is copied. A size probe - /// that fails admits the record (the export reports its own error), and - /// says so once per stage so a host without admission is noticeable. - pub(super) fn reserve_snapshot_host_memory( + /// that fails declines resident checkpoint copies. Legacy exported-state + /// records retain their warning-and-export behavior on a failed size probe. + pub(in crate::kv_integration) fn reserve_snapshot_host_memory( &self, runtime: &mut RuntimeState, session_id: &str, @@ -129,6 +129,11 @@ impl KvStageIntegration { ) -> Option> { let snapshot_bytes = match self.snapshot_size(runtime, session_id, payload, token_count) { Ok(snapshot_bytes) => snapshot_bytes, + Err(_) if payload == StagePrefixCachePayload::ResidentKv => { + self.exact_state_records_dropped + .fetch_add(1, Ordering::Relaxed); + return None; + } Err(_) => { if self .snapshot_size_probe_failures @@ -199,6 +204,9 @@ impl KvStageIntegration { }; Ok(kv.saturating_add(recurrent)) } + StagePrefixCachePayload::ResidentKv if self.resident_requires_checkpoint() => { + runtime.recurrent_state_size(session_id) + } StagePrefixCachePayload::Disabled | StagePrefixCachePayload::ResidentKv => Ok(0), } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/identity.rs b/skippy/crates/skippy-serving/src/kv_integration/identity.rs index 8ef3fad76c..6083781c8d 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/identity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/identity.rs @@ -31,7 +31,7 @@ impl KvStageIntegration { stage_index: config.stage_index, layer_start: config.layer_start, layer_end: config.layer_end, - prefix_hash: prefix.prefix_hash.clone(), + prefix_hash: self.bind_model_content(prefix.prefix_hash.clone()), session_id: base.session_id.clone(), token_start, token_count: prefix.token_count, @@ -48,12 +48,23 @@ impl KvStageIntegration { }; PrefillKvIdentity { identity, - page_id: prefix.page_id, - namespace: prefix_namespace_hash(config, token_start, base.chat_template_id.as_deref()), + page_id: self.bind_model_content(prefix.page_id), + namespace: self.bind_model_content(prefix_namespace_hash( + config, + token_start, + base.chat_template_id.as_deref(), + )), token_ids: token_ids.to_vec(), } } + fn bind_model_content(&self, identity: String) -> String { + match self.loaded_model_content.as_ref() { + Some(proof) => proof.bind(&identity), + None => identity, + } + } + pub fn lookup_identities( &self, config: &StageConfig, diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 7bd405351e..ac0ce819f4 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -158,6 +158,8 @@ pub(crate) struct ExactStateByteLimits { #[derive(Clone)] pub struct KvStageIntegration { pub(crate) mode: StageKvMode, + pub(crate) loaded_model_content: + Option>, /// The in-process cache representation. Dense models keep native resident /// KV here even when a durable tier is configured, so enabling disk does /// not replace the fast warm path with serialized state import. @@ -612,6 +614,16 @@ fn verify_resident_ownership( } impl KvStageIntegration { + pub(crate) fn cache_enabled_for_stage(config: &skippy_protocol::StageConfig) -> bool { + config::effective_cache_config(config).is_some_and(|cache| { + matches!( + cache.mode, + skippy_protocol::StageKvCacheMode::Record + | skippy_protocol::StageKvCacheMode::LookupRecord + ) + }) + } + /// Attaches an optional resident-prefix cache lifecycle observer. /// Never required; a stage with no observer behaves identically. #[must_use] diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs index 813a48017b..85f74f4aa4 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -115,13 +115,7 @@ impl KvStageIntegration { let Some(capabilities) = self.loaded_memory_cache else { return Ok(false); }; - let Some(l3) = self.l3.as_ref() else { - return Ok(false); - }; - if l3 - .locate_longest(&victim.namespace, &victim.tokens, 1)? - .is_some_and(|entry| entry.token_count == victim.tokens.len() as u64) - { + if self.l3.is_none() { return Ok(false); } let Some(claim) = diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs index b23e3ba6c0..900d77a647 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -28,6 +28,39 @@ impl KvStageIntegration { ))); } let mut evicted = (0_usize, 0_u64); + // Attention cells are shared; recurrent state is copied. Evict against + // the measured checkpoint size and reserve host headroom before that + // copy, rather than relying on a post-allocation size check. + let checkpoint_bytes = if self.resident_requires_checkpoint() { + runtime.recurrent_state_size(session_id)? + } else { + 0 + }; + if checkpoint_bytes > self.resident_checkpoint_max_bytes + || !make_record_room( + self.resident_config, + &mut radix, + &mut sequences, + checkpoint_bytes, + &mut evicted, + |victim| self.release_native_prefix(runtime, session_id, victim), + )? + { + return Ok(None); + } + let _host_reservation = if self.resident_requires_checkpoint() { + let Some(reservation) = self.reserve_snapshot_host_memory( + runtime, + session_id, + StagePrefixCachePayload::ResidentKv, + token_count as u64, + ) else { + return Ok(None); + }; + reservation + } else { + None + }; let seq_id = match sequences.allocate() { Ok(sequence) => sequence, Err(error) => { diff --git a/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs index c259274331..ab08223888 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs @@ -47,7 +47,7 @@ mod tests { }), ..StageConfig::default() }; - let kv = KvStageIntegration::from_loaded_model_with_l3_manager( + let kv = KvStageIntegration::from_test_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(MemoryCacheCapabilities { diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index e90b7c119b..ad17680747 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -22,6 +22,7 @@ mod frame_operations; pub(crate) use frame_operations::slice_activation_frame; mod lane_lifecycle; pub mod lifecycle; +pub(crate) mod model_content; pub mod panic_recovery; mod resident_prefix; mod restore_transaction; @@ -45,6 +46,10 @@ pub struct RuntimeLaunchOverrides { pub struct RuntimeState { pub model: StageModel, + runtime_lane_admission: Arc, + pub(crate) verified_model_content: Option>, + pub(crate) generation_token_budget: + Option>, compute_meter: Arc, layer_start: u32, layer_end: u32, @@ -259,6 +264,9 @@ impl RuntimeState { pub(crate) fn new_modelless_with_capacity_for_test(lane_count: u32, ctx_size: u32) -> Self { Self { model: StageModel::new_dummy(), + runtime_lane_admission: lane_admission::RuntimeLaneAdmission::new(lane_count), + verified_model_content: None, + generation_token_budget: None, layer_start: 0, layer_end: 1, lane_count, @@ -371,6 +379,9 @@ pub fn load_runtime_with_overrides( ) -> Result>>> { reject_legacy_serving_package(config)?; let runtime_config = runtime_config_from_stage_config(config, overrides)?; + let content = model_content::VerifiedModelContent::observe(config) + .ok() + .flatten(); let admitted_model_parts = config .model_part_paths @@ -388,13 +399,30 @@ pub fn load_runtime_with_overrides( open_stage_model(model_path, &runtime_config)? } }; - Ok(Some(runtime_from_loaded_model( + Ok(Some(runtime_from_verified_model( config, model, session_lifecycle_observer, + content, )?)) } +fn runtime_from_verified_model( + config: &StageConfig, + model: StageModel, + observer: Option>, + content: Option, +) -> Result>> { + // Re-stat after open before publishing proof. No filesystem work takes the + // runtime lock, and frontends reuse this proof without rehashing weights. + let content = content + .filter(|proof| proof.still_matches(config)) + .map(Arc::new); + let runtime = runtime_from_loaded_model(config, model, observer)?; + panic_recovery::lock_runtime(&runtime).verified_model_content = content; + Ok(runtime) +} + /// Apply workload admission and retain the host's session-lifecycle observer. fn runtime_from_loaded_model( config: &StageConfig, @@ -407,6 +435,9 @@ fn runtime_from_loaded_model( ContextCapacity::for_loaded_model(config.ctx_size, lane_count, model.has_native_model())?; Ok(Arc::new(Mutex::new(RuntimeState { model, + runtime_lane_admission: lane_admission::RuntimeLaneAdmission::new(lane_count), + verified_model_content: None, + generation_token_budget: None, layer_start: config.layer_start, layer_end: config.layer_end, lane_count, @@ -437,6 +468,9 @@ pub fn load_runtime_with_overrides_and_open_events( ) -> Result>>> { reject_legacy_serving_package(config)?; let runtime_config = runtime_config_from_stage_config(config, overrides)?; + let content = model_content::VerifiedModelContent::observe(config) + .ok() + .flatten(); let admitted_model_parts = config .model_part_paths @@ -456,10 +490,11 @@ pub fn load_runtime_with_overrides_and_open_events( open_stage_model_with_events(model_path, &runtime_config, model_open_events)? } }; - Ok(Some(runtime_from_loaded_model( + Ok(Some(runtime_from_verified_model( config, model, session_lifecycle_observer, + content, )?)) } diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs new file mode 100644 index 0000000000..4390c63b2f --- /dev/null +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs @@ -0,0 +1,91 @@ +//! One execution-lane reservation owner shared by HTTP and binary frontends. +use anyhow::{Result, bail}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; +use tokio::sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError}; + +#[derive(Debug)] +pub(crate) struct RuntimeLaneAdmission { + permits: Arc, + changed: Condvar, + waiting: Mutex<()>, + capacity: usize, +} + +#[derive(Debug)] +pub(crate) struct RuntimeLanePermit { + permit: Option, + owner: Arc, +} + +impl Drop for RuntimeLanePermit { + fn drop(&mut self) { + drop(self.permit.take()); + self.owner.changed.notify_all(); + } +} + +impl RuntimeLaneAdmission { + pub(crate) fn new(capacity: u32) -> Arc { + let capacity = usize::try_from(capacity).unwrap_or(usize::MAX).max(1); + Arc::new(Self { + permits: Arc::new(Semaphore::new(capacity)), + changed: Condvar::new(), + waiting: Mutex::new(()), + capacity, + }) + } + + pub(crate) fn capacity(&self) -> usize { + self.capacity + } + + pub(crate) async fn acquire(self: &Arc) -> Result { + let permit = self.permits.clone().acquire_owned().await?; + Ok(RuntimeLanePermit { + permit: Some(permit), + owner: self.clone(), + }) + } + + pub(crate) fn try_acquire(self: &Arc) -> Result> { + match self.permits.clone().try_acquire_owned() { + Ok(permit) => Ok(Some(RuntimeLanePermit { + permit: Some(permit), + owner: self.clone(), + })), + Err(TryAcquireError::NoPermits) => Ok(None), + Err(TryAcquireError::Closed) => bail!("runtime lane admission closed"), + } + } + + /// Never called while holding the native runtime or ownership-registry lock. + pub(crate) fn acquire_blocking( + self: &Arc, + cancelled: impl Fn() -> bool, + ) -> Result { + let mut waiting = self + .waiting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + loop { + if cancelled() { + bail!("binary runtime lane admission cancelled"); + } + if let Some(permit) = self.try_acquire()? { + return Ok(permit); + } + waiting = self + .changed + .wait_timeout(waiting, Duration::from_millis(50)) + .unwrap_or_else(std::sync::PoisonError::into_inner) + .0; + } + } +} + +impl super::RuntimeState { + pub(crate) fn lane_admission(&self) -> Arc { + Arc::clone(&self.runtime_lane_admission) + } +} diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs new file mode 100644 index 0000000000..885c4f0b3c --- /dev/null +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -0,0 +1,306 @@ +//! Content proof captured once around model open, outside runtime locks. +use anyhow::{Context, Result, ensure}; +use sha2::{Digest, Sha256}; +use skippy_protocol::StageConfig; +use std::{ + fs::{File, Metadata}, + io::{BufReader, Read}, + path::{Path, PathBuf}, + time::SystemTime, +}; + +#[derive(Clone)] +pub(crate) struct VerifiedModelContent { + digest: String, + files: Vec<(String, PathBuf, FileStamp)>, +} + +#[derive(Clone, PartialEq, Eq)] +struct FileStamp { + bytes: u64, + modified: Option, + created: Option, + #[cfg(unix)] + identity: (u64, u64, i64, i64), +} + +impl FileStamp { + fn read(metadata: &Metadata) -> Self { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + Self { + bytes: metadata.len(), + modified: metadata.modified().ok(), + created: metadata.created().ok(), + #[cfg(unix)] + identity: ( + metadata.dev(), + metadata.ino(), + metadata.ctime(), + metadata.ctime_nsec(), + ), + } + } +} + +impl VerifiedModelContent { + pub(crate) fn observe(config: &StageConfig) -> Result> { + if !crate::kv_integration::KvStageIntegration::cache_enabled_for_stage(config) { + return Ok(None); + } + let files = source_files(config)?; + if files.is_empty() { + return Ok(None); + } + Self::from_files(files).map(Some) + } + + fn from_files(files: Vec<(String, PathBuf)>) -> Result { + let mut digest = Sha256::new(); + digest.update(b"skippy-loaded-model-content-v1\0"); + let mut observed = Vec::with_capacity(files.len()); + let mut buffer = vec![0; 1024 * 1024]; + for (name, path) in files { + let file = File::open(&path) + .with_context(|| format!("open model content {}", path.display()))?; + let before = file.metadata()?; + ensure!( + before.is_file(), + "model content proof requires regular files" + ); + let stamp = FileStamp::read(&before); + digest.update((name.len() as u64).to_le_bytes()); + digest.update(name.as_bytes()); + digest.update(stamp.bytes.to_le_bytes()); + let mut reader = BufReader::new(file); + loop { + let count = reader.read(&mut buffer)?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + ensure!( + FileStamp::read(&reader.get_ref().metadata()?) == stamp, + "model content changed during verification" + ); + observed.push((name, path, stamp)); + } + let digest = digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + Ok(Self { + digest, + files: observed, + }) + } + + /// Reject a proof if model input selection or bytes changed while opening. + pub(crate) fn still_matches(&self, config: &StageConfig) -> bool { + let Ok(files) = source_files(config) else { + return false; + }; + let unchanged = files.len() == self.files.len() + && files.iter().zip(&self.files).all( + |((name, path), (expected_name, expected_path, stamp))| { + name == expected_name + && path == expected_path + && std::fs::metadata(path).is_ok_and(|metadata| { + metadata.is_file() && FileStamp::read(&metadata) == *stamp + }) + }, + ); + if !unchanged { + return false; + } + #[cfg(unix)] + { + true + } + #[cfg(not(unix))] + { + // Size and last-write timestamps are not a strong file identity on + // these platforms. Recheck actual content after model open and at + // backend construction rather than trusting preserved timestamps. + Self::from_files(files).is_ok_and(|current| current.digest == self.digest) + } + } + + pub(crate) fn bind(&self, identity: &str) -> String { + let mut digest = blake3::Hasher::new(); + digest.update(b"skippy-cache-loaded-content-v1\0"); + digest.update(self.digest.as_bytes()); + digest.update(identity.as_bytes()); + format!("blake3:{}", digest.finalize().to_hex()) + } +} + +fn source_files(config: &StageConfig) -> Result> { + let mut files = if config.model_part_paths.is_empty() { + let Some(path) = config.model_path.as_deref().map(Path::new) else { + return Ok(Vec::new()); + }; + if skippy_runtime::is_safetensors_checkpoint(path) { + let root = if path.is_dir() { + path + } else { + path.parent().context("checkpoint has no parent")? + }; + checkpoint_files(root)? + } else { + skippy_runtime::gguf_shard_paths(path)? + .into_iter() + .enumerate() + .map(|(index, path)| (format!("part-{index}"), path)) + .collect() + } + } else { + config + .model_part_paths + .iter() + .enumerate() + .map(|(index, path)| (format!("part-{index}"), PathBuf::from(path))) + .collect() + }; + for (role, path) in [ + ("projector", config.projector_path.as_deref()), + ("imatrix", config.checkpoint_imatrix.as_deref()), + ] { + if let Some(path) = path { + files.push((role.into(), PathBuf::from(path))); + } + } + files + .into_iter() + .map(|(role, path)| Ok((role, path.canonicalize()?))) + .collect() +} + +fn checkpoint_files(root: &Path) -> Result> { + let mut files = Vec::new(); + let mut pending = vec![(root.to_path_buf(), 0)]; + while let Some((directory, depth)) = pending.pop() { + ensure!(depth < 16, "checkpoint content tree is too deep"); + for entry in std::fs::read_dir(directory)? { + let path = entry?.path(); + let metadata = path.metadata()?; + if metadata.is_dir() { + pending.push((path, depth + 1)); + } else { + ensure!( + metadata.is_file(), + "checkpoint content contains a special file" + ); + files.push(( + path.strip_prefix(root)? + .to_string_lossy() + .replace('\\', "/"), + path.canonicalize()?, + )); + ensure!( + files.len() <= 100_000, + "checkpoint content has too many files" + ); + } + } + } + files.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(files) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unchanged_declared_digest_cannot_hide_changed_weight_bytes() { + let root = tempfile::tempdir().unwrap(); + let model = root.path().join("model.gguf"); + std::fs::write(&model, b"first weights").unwrap(); + let mut config = StageConfig { + model_path: Some(model.to_string_lossy().into_owned()), + source_model_sha256: Some("ab".repeat(32)), + ..StageConfig::default() + }; + let first = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); + assert!(first.still_matches(&config)); + let modified = model.metadata().unwrap().modified().unwrap(); + std::fs::write(&model, b"other weights").unwrap(); + File::options() + .write(true) + .open(&model) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(modified)) + .unwrap(); + assert!(!first.still_matches(&config)); + let second = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); + assert_ne!(first.bind("same namespace"), second.bind("same namespace")); + config.model_path = Some( + root.path() + .join("different.gguf") + .to_string_lossy() + .into_owned(), + ); + assert!(!second.still_matches(&config)); + } + + #[test] + fn content_binding_is_stable_across_relocation_and_includes_every_part() { + let first = tempfile::tempdir().unwrap(); + let second = tempfile::tempdir().unwrap(); + let files = |root: &Path| { + ["one", "two"] + .into_iter() + .enumerate() + .map(|(index, name)| { + let path = root.join(name); + std::fs::write(&path, name).unwrap(); + (format!("part-{index}"), path) + }) + .collect() + }; + let one = VerifiedModelContent::from_files(files(first.path())).unwrap(); + let relocated = VerifiedModelContent::from_files(files(second.path())).unwrap(); + assert_eq!(one.bind("namespace"), relocated.bind("namespace")); + std::fs::write(second.path().join("two"), b"changed").unwrap(); + let changed = VerifiedModelContent::from_files(vec![ + ("part-0".into(), second.path().join("one")), + ("part-1".into(), second.path().join("two")), + ]) + .unwrap(); + assert_ne!(one.bind("namespace"), changed.bind("namespace")); + } + + #[test] + fn environment_enabled_cache_captures_model_proof() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "runtime_state::model_content::tests::environment_enabled_cache_captures_model_proof_fixture", "--test-threads=1"]) + .env("SKIPPY_CONTENT_PROOF_ENV_FIXTURE", "1") + .env_remove("SKIPPY_KV_CACHE") + .env("SKIPPY_PREFIX_CACHE", "on") + .output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + + #[test] + fn environment_enabled_cache_captures_model_proof_fixture() { + if std::env::var_os("SKIPPY_CONTENT_PROOF_ENV_FIXTURE").is_none() { + return; + } + let root = tempfile::tempdir().unwrap(); + let model = root.path().join("model.gguf"); + std::fs::write(&model, b"actual model bytes").unwrap(); + let config = StageConfig { + model_path: Some(model.to_string_lossy().into_owned()), + kv_cache: None, + ..StageConfig::default() + }; + assert!(VerifiedModelContent::observe(&config).unwrap().is_some()); + } +} diff --git a/skippy/docs/PROMPT_CACHE.md b/skippy/docs/PROMPT_CACHE.md index 257bfab922..95ea3b9d0a 100644 --- a/skippy/docs/PROMPT_CACHE.md +++ b/skippy/docs/PROMPT_CACHE.md @@ -42,6 +42,17 @@ without a key share the default namespace. Run and topology instance IDs do not fragment the namespace. Equivalent placements can reuse state when the numerical model and state layout match. +Persistent reuse also binds its cache keys to verified bytes of the model inputs +actually opened by the runtime. Serving hashes those files once around model +loading, including every shard and any checkpoint, projector or importance +matrix inputs. File fingerprints must remain unchanged through the load. Unix +frontends reuse that strong fingerprint proof. Platforms without equivalent +file identity and change-time evidence recheck bytes after load and at backend +construction; requests do not rehash weights. Declared model or +manifest digests alone cannot authorize disk reuse. Integrations constructed +from a raw stage configuration without loaded-content proof keep their native +in-memory cache, but disable L3 and the L3-backed host tier. + A saved native prefix remains usable after the originating session is freed. Eviction drops the cache's native attention references and recurrent checkpoint. The attention pool releases cells once no cache entry or request references diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 986120c060..00b01a4f1b 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -114,6 +114,14 @@ just automation-run automation agentx mlflow-publish --input /abs/new-plan.json Export does not write MLflow. Explicit publication uses existing operator `MLFLOW_TRACKING_URI`, `MLFLOW_TRACKING_USERNAME`, `MLFLOW_TRACKING_PASSWORD` through a private temporary curl config, never job payloads or source. It first +requires `AGENTX_MLFLOW_LOCK_DIR` to name an existing absolute directory on a +filesystem shared by **every publishing host**, with working cross-host advisory +file locks. All publishers must use the same mount. The lock is keyed by tracking +URI and campaign root, held through the complete group publication, and retained +on disk after release. A concurrent publication fails before API writes; retry +after the current publisher finishes. A host-local directory cannot coordinate +publications from different hosts and is not a supported configuration. MLflow +tag values alone do not enforce run-key uniqueness. The publisher then GETs existing experiment6 and requires exact name `agentx-skippy-vs-llama` and active state. There is no experiment-create call. A new idempotent campaign root contains model/backend groups and their six arm children through @@ -127,5 +135,31 @@ metrics are read back, artifacts uploaded/downloaded with matching SHA, then publication receipt is written. A publishing failure is nonzero and retains API evidence for retry. Publication is not a numerical-correctness certificate. +Export and publication verify that the evidence archive contains exactly one +`agentx/result.json` with the same bytes as the supplied report. TTFT p50/p95 and +ITL p50 are required for every completed cell. Explicit generation-lane overrides +use a diagnostic scope and distinct MLflow run keys and capacity tags, so they +cannot replace an automatic-capacity comparison. Prepared environments reject +executable `.pth` hooks and path entries outside the pinned environment; remove +unsupported hooks while preparing the offline environment before pinning it. +The prepared llama executable and every non-system native dependency are inspected +as ELF or Mach-O before a baseline is admitted. Loader search paths and resolved +libraries must stay inside `standard_runtime`; ELF shared objects need their own +search paths. The existing Linux host/driver library exceptions and macOS system +libraries remain host-owned. Package backend libraries in the same pinned tree; +an unresolved or external dependency rejects preparation. +The baseline executable itself must resolve inside that tree and launches from +its canonical executable directory, so ggml's executable-directory and working- +directory plugin searches cannot inspect the repository or an external binary +directory. Ambient `GGML_BACKEND_PATH`, `LD_LIBRARY_PATH` and `DYLD_LIBRARY_PATH` +are not inherited. Admitted baseline builds must retain the pinned unpatched +source's empty `GGML_BACKEND_DIR` default, or set that compile-time directory +inside the same pinned tree. Custom builds with an external compiled backend +directory are unsupported. + +After the workload finishes, the supervisor deliberately sends the server +SIGTERM. A zero exit or a Unix wait status recording that SIGTERM is accepted; +an explicit nonzero exit, another signal, or forced cleanup fails the campaign. + The ordinary CI/GPU suite and registered JY templates are unchanged. This benchmark owner does not mark the long-prefix/cancellation/L3 TODO complete. diff --git a/skippy/evals/kv-validation/README.md b/skippy/evals/kv-validation/README.md index 6b953cab8c..689ba3ba5d 100644 --- a/skippy/evals/kv-validation/README.md +++ b/skippy/evals/kv-validation/README.md @@ -44,6 +44,9 @@ runtime dependency feature. The producer image must contain those exact tools, the prepared native source, the workspace and this automation executable. Prepare once **inside that immutable image**, preserving paths across workers. No worker rebuilds native code, Rust or the model matrix executable. +This harness supports Linux and macOS only. Preparation rejects Windows because +packaged Windows runtimes do not export the private graph inspection helpers; +the harness does not replace the packaged runtime with a different static build. Copy [producer.example.json](producer.example.json), replace its absolute paths and source commit, and observe byte pins. Empty SHA fields are allowed only as @@ -61,6 +64,10 @@ test harness, and emits `/absolute/kv-prepared/prepared.json`. It uses shared libraries and matching private graph headers, without modifying the native patch queue. Source declarations are provenance; artifact hashes and the trusted producer image bind the executable bytes actually consumed. +Verification also launches an exact serving-test identity probe in a fresh +process, with only the verified runtime leaf available for discovery. The probe +rejects static test builds and requires successful dynamic runtime loading. +The native matrix loads packaged backends from that runtime's `lib` directory. Copy [cell.example.json](cell.example.json), supply the prepared receipt SHA (`shasum -a 256 /absolute/kv-prepared/prepared.json`) and the actual model path. @@ -86,6 +93,11 @@ fails the command. Preserve both the failed receipt and evidence archive. The cache receipt is a closed typed projection observed before log sanitization; it preserves only the declared content, counters and status, never arbitrary child payloads, protocol headers or environment data. +The archive contains the raw evidence available before the final status decision. +`result.json` is a separate post-archive sidecar: traversal, compression and +hashing count against the execution deadline before it can report success. +Directory suffixes are preserved (`trial.1` produces `trial.1.tar.gz` and +`trial.1.archive.json`). ## Explicit JY jobs @@ -95,6 +107,10 @@ eligible Sparks. The planner rejects both excluded node IDs (`spark-000280`, `spark-000499`) and hostnames (`spark-db08`, `spark-9f06`). Each worker also checks its actual hostname. Jobs are independent per model and reuse the prepared image; JY's node lease queues jobs rather than stacking GPU measurements. +Run the planner where the pinned prepared JSON is available. It verifies that +receipt's digest, schema and declared backend before writing any jobs; each +worker subsequently re-verifies the prepared tool and runtime artifacts inside +the immutable image. ```sh just skippy-kv-jy-plan /absolute/fleet.json /absolute/new-jobs diff --git a/skippy/evals/kv-validation/native/CMakeLists.txt b/skippy/evals/kv-validation/native/CMakeLists.txt index d31901236d..b03101331f 100644 --- a/skippy/evals/kv-validation/native/CMakeLists.txt +++ b/skippy/evals/kv-validation/native/CMakeLists.txt @@ -1,4 +1,7 @@ cmake_minimum_required(VERSION 3.20) +if(CMAKE_HOST_WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Windows") + message(FATAL_ERROR "KV validation supports Linux and macOS only: packaged Windows runtimes do not export the private graph inspection helpers") +endif() project(indexed_real_kv_matrix LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(NATIVE_SOURCE "" CACHE PATH "Matching prepared native source checkout") @@ -10,6 +13,7 @@ foreach(component llama ggml ggml-base) find_library(NATIVE_${component} NAMES ${component} PATHS "${NATIVE_LIB_DIR}" NO_DEFAULT_PATH REQUIRED) endforeach() add_executable(indexed-real-kv-matrix indexed-real-kv-matrix.cpp) +target_compile_definitions(indexed-real-kv-matrix PRIVATE KV_NATIVE_LIB_DIR="${NATIVE_LIB_DIR}") target_include_directories(indexed-real-kv-matrix PRIVATE "${NATIVE_SOURCE}/include" "${NATIVE_SOURCE}/src" "${NATIVE_SOURCE}/ggml/include" "${NATIVE_SOURCE}/ggml/src") target_link_libraries(indexed-real-kv-matrix PRIVATE ${NATIVE_llama} ${NATIVE_ggml} ${NATIVE_ggml-base}) diff --git a/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp index 9df6e1b243..6537737b5c 100644 --- a/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp +++ b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp @@ -138,7 +138,7 @@ int main(int argc, char ** argv) { const bool cpu = std::strcmp(backend, "CPU") == 0; const bool metal = std::strcmp(backend, "MTL0") == 0; require(cpu || metal || std::strcmp(backend, "CUDA0") == 0, "select CPU, MTL0 or CUDA0 explicitly"); - ggml_backend_load_all(); + ggml_backend_load_all_from_path(KV_NATIVE_LIB_DIR); const auto device = ggml_backend_dev_by_name(backend); require(device != nullptr, "selected backend unavailable"); ggml_backend_dev_t devices[] = {device, nullptr}; diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 99f31feee8..20889cd287 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -74,7 +74,7 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/stage_realization.h | 21 + src/skippy/stage_slice_plan.cpp | 907 +++++++++++++++++ src/skippy/stage_slice_plan.h | 136 +++ - src/skippy/state.cpp | 1189 +++++++++++++++++++++++ + src/skippy/state.cpp | 743 ++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ src/skippy/state_memory.cpp | 125 +++ @@ -15642,10 +15642,10 @@ index 000000000..1cb24c7cb + std::string & error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp new file mode 100644 -index 000000000..f035ea13f +index 000000000..cf0838051 --- /dev/null +++ b/src/skippy/state.cpp -@@ -0,0 +1,1189 @@ +@@ -0,0 +1,743 @@ +#include "skippy/state.h" +#include "skippy/state_memory.h" +#include "skippy/errors.h" @@ -16377,10 +16377,6 @@ index 000000000..f035ea13f + if (session->token_history.size() > token_count) { + session->token_history.resize(static_cast(token_count)); + skippy_clear_chat_sampling(session); -+ } else if (session->sampling_accepted_token_count > token_count) { -+ // A verify restore to the start of its window leaves the history at -+ // token_count, but the sampler already accepted the window's first row. -+ skippy_clear_chat_sampling(session); + } + if (session->signal_history.size() > token_count) { + session->signal_history.resize(static_cast(token_count)); diff --git a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index 15a85b31f3..e8e334bb0a 100644 --- a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -33,6 +33,1393 @@ Subject: [PATCH 03/15] feat(llama): integrate live stage planning and 25 files changed, 3050 insertions(+), 340 deletions(-) create mode 100644 src/skippy-verify-checkpoint.h +diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h +index c37ba9471..00ba30d6a 100644 +--- a/ggml/include/ggml.h ++++ b/ggml/include/ggml.h +@@ -2499,6 +2499,28 @@ extern "C" { + float max_bias, + float logit_softcap); + ++ // same as ggml_flash_attn_ext, but each q slice attends to its own list of K/V rows ++ // q: [n_embd_k, n_batch, n_head, ne3] ++ // k: [n_embd_k, n_rows, n_head_kv, 1 ] shared by all q slices ++ // v: [n_embd_v, n_rows, n_head_kv, 1 ] ++ // mask: [n_kv, n_batch, ne32, ne3] ++ // kv_rows: [n_kv, ne3] I32, mask column i of slice i3 uses row kv_rows[i, i3] of k and v ++ // negative rows are padding, their mask entries must be -inf ++ // kv_rows: contiguous I32 [padded_rows, q->ne[3], 1, 1], src[5]. ++ // Nonnegative entries must index both shared K/V pools; negative padding ++ // entries must have -INFINITY mask values for every corresponding query. ++ // Backends may require padded_rows alignment; query supports_op first. ++ GGML_API struct ggml_tensor * ggml_flash_attn_ext_rows( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, ++ struct ggml_tensor * k, ++ struct ggml_tensor * v, ++ struct ggml_tensor * mask, ++ struct ggml_tensor * kv_rows, ++ float scale, ++ float max_bias, ++ float logit_softcap); ++ + GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( + struct ggml_tensor * a, + enum ggml_prec prec), +diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp +index 679d5216d..e94b39e4c 100644 +--- a/ggml/src/ggml-backend-meta.cpp ++++ b/ggml/src/ggml-backend-meta.cpp +@@ -153,6 +153,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type( + + static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + GGML_ASSERT(ggml_backend_dev_is_meta(dev)); ++ // The split-state planner does not partition row lists with head-sharded inputs. ++ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { ++ return false; ++ } + const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; + return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), + [op](ggml_backend_dev_t simple_dev) { return ggml_backend_dev_supports_op(simple_dev, op); }); +diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp +index 28e17f3f7..c6429b13b 100644 +--- a/ggml/src/ggml-cann/ggml-cann.cpp ++++ b/ggml/src/ggml-cann/ggml-cann.cpp +@@ -2664,6 +2664,10 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten + return true; + case GGML_OP_FLASH_ATTN_EXT: + { ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ if (op->src[5] != nullptr) { ++ return false; ++ } + #ifdef ASCEND_310P + // FA not support on 310p device + return false; +diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp +index 7a73e138e..1645e954f 100644 +--- a/ggml/src/ggml-cpu/ops.cpp ++++ b/ggml/src/ggml-cpu/ops.cpp +@@ -8930,6 +8930,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; ++ const ggml_tensor * kv_rows = dst->src[5]; + + GGML_TENSOR_LOCALS(int64_t, neq, q, ne) + GGML_TENSOR_LOCALS(size_t, nbq, q, nb) +@@ -9037,6 +9038,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( + const float * pq = (const float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)); + q_to_vec_dot(pq, Q_q, DK); + ++ const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; ++ + // online softmax / attention + // loop over n_kv and n_head_kv + // ref: https://arxiv.org/pdf/2112.05682.pdf +@@ -9047,9 +9050,14 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( + continue; + } + ++ const int64_t ik1 = rows ? rows[ic] : ic; ++ if (ik1 < 0) { ++ continue; ++ } ++ + float s; // KQ value + +- const char * k_data = (const char *) k->data + ( ic*nbk1 + ik2*nbk2 + ik3*nbk3); ++ const char * k_data = (const char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3); + kq_vec_dot(DK, &s, 0, k_data, 0, Q_q, 0, 1); + + s = s*scale; // scale KQ value +@@ -9065,7 +9073,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( + float ms = 1.0f; // upon new higher max val, scale VKQ and KQ sum with this value + float vs = 1.0f; // post-softmax KQ value, expf(s - M) + +- const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3)); ++ const char * v_data = ((const char *) v->data + (ik1*nbv1 + iv2*nbv2 + iv3*nbv3)); + + if (v->type == GGML_TYPE_F16) { + if (s > M) { +@@ -9232,6 +9240,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( + static constexpr int Q_TILE_SZ = ggml_fa_tile_config::Q; + static constexpr int KV_TILE_SZ = ggml_fa_tile_config::KV; + ++ // with kv_rows the loop runs over the mask columns and reads K/V rows through kv_rows ++ const ggml_tensor * kv_rows = dst->src[5]; ++ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; ++ + int ir = ir0; + while (ir < ir1) { + // q indices for the start of this tile +@@ -9239,6 +9251,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( + const int iq2 = (ir - iq3*neq2*neq1)/neq1; + const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1); + ++ // padding rows are masked, read row 0 for them ++ const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; ++ auto kv_row = [rows](int64_t i) -> int64_t { return rows ? std::max(rows[i], 0) : i; }; ++ + // Number of valid rows in this tile: + // - limited by tile size (Q_TILE_SZ) + // - limited by chunk boundary (ir1 - ir) +@@ -9298,8 +9314,8 @@ static void ggml_compute_forward_flash_attn_ext_tiled( + memset(K_f32, 0, DK * KV_TILE_SZ * sizeof(float)); + memset(V32, 0, KV_TILE_SZ * DV * sizeof(float)); + +- for (int64_t ic = 0; ic < nek1; ic += KV_TILE_SZ) { +- const int kv_tile = (int)std::min((int64_t)KV_TILE_SZ, nek1 - ic); ++ for (int64_t ic = 0; ic < n_kv_cols; ic += KV_TILE_SZ) { ++ const int kv_tile = (int)std::min((int64_t)KV_TILE_SZ, n_kv_cols - ic); + + // skip the tile entirely if all the masks are -inf + if (mask) { +@@ -9326,7 +9342,7 @@ static void ggml_compute_forward_flash_attn_ext_tiled( + // Pack K tile transposed: K_f32[dk][kv] so KV_TILE is contiguous (SIMD dim) + // Zero-pad the last tile so the GEMM always operates on KV_TILE_SZ columns + for (int tk = 0; tk < kv_tile; tk++) { +- const char * k_data = (const char *)k->data + (ic + tk)*nbk1 + ik2*nbk2 + ik3*nbk3; ++ const char * k_data = (const char *)k->data + kv_row(ic + tk)*nbk1 + ik2*nbk2 + ik3*nbk3; + if (kv_type == GGML_TYPE_F16) { + const ggml_fp16_t * k_f16 = (const ggml_fp16_t *)k_data; + for (int64_t dk = 0; dk < DK; dk++) { +@@ -9391,7 +9407,7 @@ static void ggml_compute_forward_flash_attn_ext_tiled( + // V accumulation: VKQ32 += softmax(KQ) * V + // Pack V tile to contiguous F32, zero-padded + for (int tk = 0; tk < kv_tile; tk++) { +- const char * v_data = (const char *)v->data + (ic + tk)*nbv1 + iv2*nbv2 + iv3*nbv3; ++ const char * v_data = (const char *)v->data + kv_row(ic + tk)*nbv1 + iv2*nbv2 + iv3*nbv3; + if (kv_type == GGML_TYPE_F16) { + ggml_cpu_fp16_to_fp32((const ggml_fp16_t *)v_data, V32 + tk * DV, DV); + } else { +@@ -9563,8 +9579,12 @@ static void ggml_compute_forward_flash_attn_ext_f16( + // When use_ref is set, force the vec-only reference implementation (no tiling, no KV-chunking) + const bool use_ref = params->use_ref; + ++ // with kv_rows the loops run over the mask columns, the split KV path does not support it ++ const ggml_tensor * kv_rows = dst->src[5]; ++ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; ++ + const bool kv_is_f32_or_f16 = (k->type == GGML_TYPE_F32 || k->type == GGML_TYPE_F16); +- const bool use_split_kv_path = !use_ref && (neq1 == 1 && neq3 == 1) && kv_is_f32_or_f16 && (k->type == v->type) && q->type == GGML_TYPE_F32 && nek1 >= 512; ++ const bool use_split_kv_path = !use_ref && !kv_rows && (neq1 == 1 && neq3 == 1) && kv_is_f32_or_f16 && (k->type == v->type) && q->type == GGML_TYPE_F32 && nek1 >= 512; + + if (use_split_kv_path) { + const int64_t chunk_size = (nek1 + nth - 1) / nth; +@@ -9643,7 +9663,7 @@ static void ggml_compute_forward_flash_attn_ext_f16( + if (use_tiled) { + ggml_compute_forward_flash_attn_ext_tiled(params, dst, ir0, ir1); + } else { +- ggml_compute_forward_flash_attn_ext_f16_one_chunk(params, dst, ir0, ir1, 0, nek1, nullptr, 0); ++ ggml_compute_forward_flash_attn_ext_f16_one_chunk(params, dst, ir0, ir1, 0, n_kv_cols, nullptr, 0); + } + + current_chunk = ggml_threadpool_chunk_add(params->threadpool, 1); +diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp +index 81e86b9dd..2071a15c1 100644 +--- a/ggml/src/ggml-cpu/spacemit/ime.cpp ++++ b/ggml/src/ggml-cpu/spacemit/ime.cpp +@@ -1041,6 +1041,10 @@ class tensor_traits_common : public tensor_traits_base { + return true; + } + case GGML_OP_FLASH_ATTN_EXT: ++ // K/V row lists are handled by the generic CPU path ++ if (op->src[5] != nullptr) { ++ return false; ++ } + forward_flash_attn_ext_f16(params, op); + return true; + case GGML_OP_CONT: +diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh +index 41d948335..beb877941 100644 +--- a/ggml/src/ggml-cuda/fattn-common.cuh ++++ b/ggml/src/ggml-cuda/fattn-common.cuh +@@ -25,6 +25,7 @@ typedef void (* fattn_kernel_t)( + const char * __restrict__ mask, + const char * __restrict__ sinks, + const int * __restrict__ KV_max, ++ const int * __restrict__ KV_rows, + float * __restrict__ dst, + float2 * __restrict__ dst_meta, + const float scale, +@@ -991,8 +992,13 @@ void launch_fattn( + + const bool V_is_K_view = V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs)); + +- const ggml_tensor * mask = dst->src[3]; +- const ggml_tensor * sinks = dst->src[4]; ++ const ggml_tensor * mask = dst->src[3]; ++ const ggml_tensor * sinks = dst->src[4]; ++ const ggml_tensor * kv_rows = dst->src[5]; ++ ++ // with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows ++ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1]; ++ GGML_ASSERT(!kv_rows || !use_sparse); + + ggml_tensor * KQV = dst; + +@@ -1113,8 +1119,8 @@ void launch_fattn( + + // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. + // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or +- // multiple sequences of possibly different lengths. +- const bool scan_mask = !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); ++ // multiple sequences of possibly different lengths, or kv_rows lists that end with padding. ++ const bool scan_mask = !use_sparse && mask && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); + if (scan_mask) { + const int64_t s31 = mask->nb[1] / sizeof(half2); + const int64_t s33 = mask->nb[3] / sizeof(half2); +@@ -1123,7 +1129,7 @@ void launch_fattn( + const dim3 block_dim_KV_max(FATTN_KQ_STRIDE/2, 1, 1); + + const int ne_KV_max = blocks_num_KV_max.x*blocks_num_KV_max.y; +- const int iter_k = K->ne[1] / FATTN_KQ_STRIDE; ++ const int iter_k = n_kv_cols / FATTN_KQ_STRIDE; + + KV_max.alloc(ne_KV_max); + ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_KV_max, block_dim_KV_max, 0, main_stream); +@@ -1132,13 +1138,19 @@ void launch_fattn( + CUDA_CHECK(cudaGetLastError()); + } + ++ // K/V are shared by all slices when read through kv_rows ++ if (kv_rows) { ++ nb13 = 0; ++ nb23 = 0; ++ } ++ + const dim3 block_dim(warp_size, nwarps, 1); + int max_blocks_per_sm = 1; // Max. number of active blocks limited by occupancy. + CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, fattn_kernel, block_dim.x * block_dim.y * block_dim.z, nbytes_shared)); + GGML_ASSERT(max_blocks_per_sm > 0); + int parallel_blocks = max_blocks_per_sm; + +- const int64_t n_kv = use_sparse ? n_kv_max : K->ne[1]; ++ const int64_t n_kv = use_sparse ? n_kv_max : n_kv_cols; + const int ntiles_KV = (n_kv + nbatch_fa - 1) / nbatch_fa; // Max. number of parallel blocks limited by KV cache length. + + dim3 blocks_num; +@@ -1255,6 +1267,7 @@ void launch_fattn( + mask ? ((const char *) mask->data) : nullptr, + sinks ? ((const char *) sinks->data) : nullptr, + KV_max.ptr, ++ kv_rows ? (const int *) kv_rows->data : nullptr, + !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, + scale, max_bias, m0, m1, n_head_log2, logit_softcap, + Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3], +diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh +index 296aa2b34..f37b5de88 100644 +--- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh ++++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh +@@ -420,6 +420,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + // padded slots gather row 0, the -inf mask removes their contribution + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; + i_KV = index >= 0 ? index : 0; ++ } else if (indices) { ++ // K/V rows given per mask column, negative rows are padding ++ i_KV = max(indices[k_VKQ_0 + i], 0); + } else { + i_KV = k_VKQ_0 + i; + } +@@ -467,8 +470,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( + if constexpr (use_sparse) { + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; + src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; ++ } else if (!oob_check || i < i_sup) { ++ const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i; ++ src = KV + i_KV*stride_KV + k*h2_per_chunk; + } else { +- src = !oob_check || i < i_sup ? KV + int64_t(k_VKQ_0 + i)*stride_KV + k*h2_per_chunk : zero; ++ src = zero; + } + ggml_cuda_memcpy_1<16>(swizzle(tile_KV, i*stride_tile + k*h2_per_chunk, i), src); + } +@@ -634,7 +640,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + cp_async_wait_all(); + __syncthreads(); + flash_attn_ext_f16_load_tile +- (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, nullptr); ++ (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, indices); + } else { + // the sparse mask values are gathered per element, always load them synchronously + constexpr bool use_cp_async = nstages == 1 && !use_sparse; +@@ -991,7 +997,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( + (mask_h, tile_mask, stride_mask, k_VKQ_0 + nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); + } + flash_attn_ext_f16_load_tile +- (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, nullptr); ++ (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, indices); + } + } + +@@ -1343,7 +1349,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( + (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); + } + flash_attn_ext_f16_load_tile +- (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, nullptr); ++ (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, indices); + } + + // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. +@@ -1802,6 +1808,7 @@ static __global__ void flash_attn_ext_f16( + const char * mask_ptr, + const char * sinks_ptr, + const int * KV_max_ptr, ++ const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, + const float scale, +@@ -1924,7 +1931,8 @@ static __global__ void flash_attn_ext_f16( + + const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); + const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; +- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; ++ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : ++ KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; + + const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + +@@ -1973,7 +1981,8 @@ static __global__ void flash_attn_ext_f16( + + const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); + const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; +- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; ++ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : ++ KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; + + const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + +@@ -1989,7 +1998,7 @@ static __global__ void flash_attn_ext_f16( + (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, + ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); + #else +- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, ++ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, + max_bias, m0, m1, n_head_log2, logit_softcap, + ne00, ne01, ne02, ne03, + nb01, nb02, nb03, +diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh +index b5ea915e1..6cb30022e 100644 +--- a/ggml/src/ggml-cuda/fattn-tile.cuh ++++ b/ggml/src/ggml-cuda/fattn-tile.cuh +@@ -797,6 +797,7 @@ static __global__ void flash_attn_tile( + const char * mask_ptr, + const char * sinks_ptr, + const int * KV_max_ptr, ++ const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, + const float scale, +@@ -821,6 +822,7 @@ static __global__ void flash_attn_tile( + const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; + float * GGML_CUDA_RESTRICT dst = dst_ptr; + float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; ++ GGML_UNUSED(KV_rows_ptr); + + // Skip unused kernel variants for faster compilation: + +@@ -1132,7 +1134,7 @@ static __global__ void flash_attn_tile( + } + } + #else +- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, ++ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, + max_bias, m0, m1, n_head_log2, logit_softcap, + ne00, ne01, ne02, ne03, + nb01, nb02, nb03, +diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh +index 57a285565..8eb29ef80 100644 +--- a/ggml/src/ggml-cuda/fattn-vec.cuh ++++ b/ggml/src/ggml-cuda/fattn-vec.cuh +@@ -25,6 +25,7 @@ static __global__ void flash_attn_ext_vec( + const char * mask_ptr, + const char * sinks_ptr, + const int * KV_max_ptr, ++ const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, + const float scale, +@@ -50,6 +51,7 @@ static __global__ void flash_attn_ext_vec( + const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; + float * GGML_CUDA_RESTRICT dst = dst_ptr; + float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; ++ GGML_UNUSED(KV_rows_ptr); + + // Skip unused kernel variants for faster compilation: + if (use_logit_softcap && !(D == 128 || D == 256)) { +@@ -512,7 +514,7 @@ static __global__ void flash_attn_ext_vec( + dst_meta[((sequence*int(ne01.z) + ic0 + tid)*ne02 + head)*gridDim.y + blockIdx.y] = make_float2(KQ_max[tid], KQ_sum[tid]); + } + #else +- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, ++ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, + max_bias, m0, m1, n_head_log2, logit_softcap, + ne00, ne01, ne02, ne03, + nb01, nb02, nb03, +diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu +index 5fa3e5308..79eb3cccf 100644 +--- a/ggml/src/ggml-cuda/fattn.cu ++++ b/ggml/src/ggml-cuda/fattn.cu +@@ -144,7 +144,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ + // the dense kernel handles up to 64/ncols2 queries per K/V pass, the single-query gather has to beat that + const int64_t n_gather = (ncols1 == 1 ? std::min(Q->ne[1], 64/ncols2) : ncols1) * (int64_t) n_kv_max; + +- return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && ++ return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && dst->src[5] == nullptr && + mask != nullptr && n_kv_max > 0 && max_bias == 0.0f && logit_softcap == 0.0f && + mask->ne[0] == K->ne[1] && mask->ne[1] >= Q->ne[1] && mask->ne[2] == 1 && + K->ne[1] >= std::max(4096, 2*n_gather); +@@ -199,12 +199,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con + const ggml_tensor * V = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + ++ // with kv_rows the kernel iterates over the mask columns ++ const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; ++ + float max_bias = 0.0f; + memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); + + // Edge cases like no mask, ALiBi, unpadded K/V, or misaligned addresses for large data transfers + // are put into the template specialization without GQA optimizations. +- bool use_gqa_opt = mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ bool use_gqa_opt = mask && max_bias == 0.0f && n_kv % FATTN_KQ_STRIDE == 0; + for (const ggml_tensor * t : {Q, K, V, mask}) { + if (t == nullptr || ggml_is_quantized(t->type)) { + continue; +@@ -537,6 +540,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { + } + } + ++// The 576/512 MMA specialization reuses K for V; dimensions alone do not ++// establish the required alias for independently allocated K/V caches. ++static bool ggml_cuda_fattn_v_aliases_k(const ggml_tensor * K, const ggml_tensor * V) { ++ const bool same_view = V->view_src && ++ ((V->view_src == K && V->view_offs == 0) || ++ (K->view_src && V->view_src == K->view_src && V->view_offs == K->view_offs)); ++ const bool same_data = K->data && V->data && K->data == V->data; ++ if (K->data && V->data && !same_data) { ++ return false; ++ } ++ if ((!same_view && !same_data) || K->type != V->type || V->ne[0] > K->ne[0]) { ++ return false; ++ } ++ for (int i = 0; i < GGML_MAX_DIMS; ++i) { ++ if (K->nb[i] != V->nb[i] || (i != 0 && K->ne[i] != V->ne[i])) { ++ return false; ++ } ++ } ++ return true; ++} ++ + static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { + #ifndef FLASH_ATTN_AVAILABLE + GGML_UNUSED(device); GGML_UNUSED(dst); +@@ -549,15 +573,22 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const + const ggml_tensor * V = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + ++ const ggml_tensor * kv_rows = dst->src[5]; ++ ++ // with kv_rows the kernel iterates over the mask columns ++ const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1]; ++ + const int gqa_ratio = Q->ne[2] / K->ne[2]; + GGML_ASSERT(Q->ne[2] % K->ne[2] == 0); + + float max_bias = 0.0f; + memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); ++ float logit_softcap = 0.0f; ++ memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float)); + + // The effective batch size for the kernel can be increased by gqa_ratio. + // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded, +- bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; ++ bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && n_kv % FATTN_KQ_STRIDE == 0; + for (const ggml_tensor * t : {Q, K, V, mask}) { + if (t == nullptr || ggml_is_quantized(t->type)) { + continue; +@@ -629,6 +660,38 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const + return BEST_FATTN_KERNEL_NONE; + } + ++ // Match the actually compiled softcap variants before selecting a kernel. ++ const bool softcap_mma = K->ne[0] == 128 || K->ne[0] == 256 || K->ne[0] == 512; ++ if (logit_softcap != 0.0f && V->ne[0] != 128 && V->ne[0] != 256 && V->ne[0] != 512) { ++ return BEST_FATTN_KERNEL_NONE; ++ } ++ ++ // only the MMA kernel reads K/V through kv_rows ++ if (kv_rows) { ++ if (kv_rows->type != GGML_TYPE_I32 || !ggml_is_contiguous(kv_rows) || ++ kv_rows->ne[0] <= 0 || kv_rows->ne[0] > INT32_MAX || ++ kv_rows->ne[0] % FATTN_KQ_STRIDE != 0 || ++ kv_rows->ne[1] != Q->ne[3] || kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 || ++ !mask || mask->ne[0] != kv_rows->ne[0] || mask->ne[1] < Q->ne[1] || ++ K->ne[1] > INT32_MAX || K->ne[1] != V->ne[1] || K->ne[3] != 1 || V->ne[3] != 1 || ++ (logit_softcap != 0.0f && !softcap_mma) || ++ (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V))) { ++ return BEST_FATTN_KERNEL_NONE; ++ } ++ return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ? ++ BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE; ++ } ++ ++ if ((logit_softcap != 0.0f && !softcap_mma) || ++ (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V))) { ++ // The ordinary wide tile path has GQA4/GQA16 variants and reads V ++ // independently. Rows have no corresponding tile reader. ++ if (K->ne[0] == 576 && gqa_ratio % 4 != 0) { ++ return BEST_FATTN_KERNEL_NONE; ++ } ++ return BEST_FATTN_KERNEL_TILE; ++ } ++ + // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes: + // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. + const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; +diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp +index 54a6d166d..276bd007f 100644 +--- a/ggml/src/ggml-et/ggml-et.cpp ++++ b/ggml/src/ggml-et/ggml-et.cpp +@@ -1270,7 +1270,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm + case GGML_OP_FLASH_ATTN_EXT: + if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && + (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && +- (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && ++ (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr && + ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) { + float max_bias = 0.0f; + float logit_softcap = 0.0f; +diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp +index 08c15ff78..2b8cfb5e8 100644 +--- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp ++++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp +@@ -5180,6 +5180,11 @@ static bool ggml_hexagon_precompute_flash_attn_params( + return false; + } + ++ // K/V row lists are not supported by Hexagon. ++ if (op->src[5] != nullptr) { ++ return false; ++ } ++ + memset(kparams, 0, sizeof(*kparams)); + + const struct ggml_tensor * q = op->src[0]; +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index 2c7972b0a..e94fae132 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -1955,6 +1955,23 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( + return res; + } + ++ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( ++ ggml_metal_library_t lib, ++ const ggml_tensor * op) { ++ assert(op->op == GGML_OP_FLASH_ATTN_EXT); ++ ++ const char * base = "kernel_flash_attn_ext_rows"; ++ ++ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, base); ++ if (!res.pipeline) { ++ res = ggml_metal_library_compile_pipeline(lib, base, base, nullptr); ++ } ++ ++ GGML_UNUSED(op); ++ ++ return res; ++} ++ + ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx( + ggml_metal_library_t lib, + const ggml_tensor * op) { +@@ -1984,6 +2001,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + bool has_scap, + bool has_kvpad, + bool has_sparse, ++ bool has_rows, + int32_t nqpsg, + int32_t ne, + int32_t nsg, +@@ -2013,7 +2031,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + dv, + qne_suffix); + +- snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", ++ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", + base, + has_mask, + has_sinks, +@@ -2021,6 +2039,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + has_scap, + has_kvpad, + has_sparse, ++ has_rows, + ns10, + ns20, + nsg, nwg); +@@ -2035,6 +2054,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_VEC + 3); + ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); + ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); ++ ggml_metal_cv_set_bool(cv, has_rows, FC_FLASH_ATTN_EXT_VEC + 6); + + ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); + ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); +diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h +index 4012b9d5f..7569a598f 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.h ++++ b/ggml/src/ggml-metal/ggml-metal-device.h +@@ -217,6 +217,10 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att + int32_t ns10, + int32_t ns20); + ++struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( ++ ggml_metal_library_t lib, ++ const struct ggml_tensor * op); ++ + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx( + ggml_metal_library_t lib, + const struct ggml_tensor * op); +@@ -230,6 +234,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att + bool has_scap, + bool has_kvpad, + bool has_sparse, ++ bool has_rows, + int32_t nqpsg, + int32_t ne, + int32_t nsg, +diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m +index d1bce8bad..15a3ccb06 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.m ++++ b/ggml/src/ggml-metal/ggml-metal-device.m +@@ -1725,6 +1725,45 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te + case GGML_OP_ROLL: + return ggml_is_contiguous(op->src[0]); + case GGML_OP_FLASH_ATTN_EXT: ++ // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice ++ if (op->src[5] != NULL) { ++ const struct ggml_tensor * kv_rows = op->src[5]; ++ ++ if (kv_rows->type != GGML_TYPE_I32 || ++ !ggml_is_contiguous(kv_rows) || ++ kv_rows->ne[0] <= 0 || kv_rows->ne[0] > INT32_MAX || ++ kv_rows->ne[0] % OP_FLASH_ATTN_EXT_NCPSG != 0 || ++ kv_rows->ne[0] % OP_FLASH_ATTN_EXT_VEC_NCPSG != 0 || ++ kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 || ++ kv_rows->ne[1] != op->src[0]->ne[3] || ++ !op->src[3] || op->src[3]->ne[0] != kv_rows->ne[0] || ++ op->src[3]->ne[1] < op->src[0]->ne[1] || ++ op->src[1]->ne[1] > INT32_MAX || op->src[1]->ne[1] != op->src[2]->ne[1] || ++ op->src[1]->ne[3] != 1 || op->src[2]->ne[3] != 1) { ++ return false; ++ } ++ ++ // the non-vec kernels attend over a contiguous F16 copy of the referenced rows: ++ // - F16 K/V is gathered directly ++ // - quantized K/V is first dequantized with kernel_flash_attn_ext_kv_*_f16 ++ // - other types keep attending to the whole cache (dense mask) ++ switch (op->src[1]->type) { ++ case GGML_TYPE_F16: ++ case GGML_TYPE_Q4_0: ++ case GGML_TYPE_Q4_1: ++ case GGML_TYPE_Q5_0: ++ case GGML_TYPE_Q5_1: ++ case GGML_TYPE_Q8_0: ++ break; ++ default: ++ return false; ++ } ++ ++ // the row gather copies F16 values in groups of 4 ++ if (op->src[2]->ne[0] % 4 != 0) { ++ return false; ++ } ++ } + // for new head sizes, add checks here + if (op->src[0]->ne[0] != 32 && + op->src[0]->ne[0] != 40 && +diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h +index 4ffb5a77d..479c722d3 100644 +--- a/ggml/src/ggml-metal/ggml-metal-impl.h ++++ b/ggml/src/ggml-metal/ggml-metal-impl.h +@@ -383,6 +383,19 @@ typedef struct { + int32_t nblocks; + } ggml_metal_kargs_flash_attn_ext_kv_f16; + ++// gather the K/V cache rows referenced by the kv_rows lists into contiguous F16 buffers ++typedef struct { ++ int32_t ne11; // number of rows per list (n_kv_rows) ++ int32_t ne_12_2; // number of K/V heads ++ int32_t ne10; // DK ++ int32_t ne20; // DV, set to 0 to skip gathering V (V is a view of K) ++ uint64_t v_off; // byte offset of the gathered V region in dst ++ uint64_t nb11; // K source strides (ne13 = 1: the cache is shared by all streams) ++ uint64_t nb12; ++ uint64_t nb21; // V source strides (ne23 = 1) ++ uint64_t nb22; ++} ggml_metal_kargs_flash_attn_ext_rows; ++ + typedef struct { + int32_t ne11; + int32_t ne_12_2; // assume K and V are same shape +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index 53c981618..55a9c5873 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -3165,7 +3165,10 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool + return false; + } + +- return op->src[1]->ne[1] % OP_FLASH_ATTN_EXT_TENSOR_NCPSG == 0; ++ // with kv_rows, the attention runs over the compacted row lists (padded to 256), not over the cache ++ const int64_t ne11_attn = op->src[5] ? op->src[5]->ne[0] : op->src[1]->ne[1]; ++ ++ return ne11_attn % OP_FLASH_ATTN_EXT_TENSOR_NCPSG == 0; + } + + // returns the n_kv_max hint if the sparse path is available for this op, or 0 otherwise +@@ -3174,6 +3177,11 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool + static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + ++ // K/V row lists are handled by the dense kernels, not by the sparse path ++ if (op->src[5] != nullptr) { ++ return 0; ++ } ++ + int32_t n_kv_max = 0; + memcpy(&n_kv_max, ((const int32_t *) op->op_params) + 4, sizeof(n_kv_max)); + +@@ -3417,6 +3425,32 @@ size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { + return GGML_PAD(sizeof(int32_t)*(size_t) n_kv_max_padded*ne31*ne32*ne33, 16); + } + ++// size of the contiguous F16 buffers holding the K/V rows referenced by the kv_rows lists ++// the attention over these buffers is a standard dense op (no per-tile gather in the main kernel) ++size_t ggml_metal_op_flash_attn_ext_extra_rows(const ggml_tensor * op) { ++ assert(op->op == GGML_OP_FLASH_ATTN_EXT); ++ ++ const ggml_tensor * kv_rows = op->src[5]; ++ ++ if (!kv_rows) { ++ return 0; ++ } ++ ++ GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); ++ GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne); ++ ++ const int64_t n_rows = kv_rows->ne[0]; ++ const int64_t n_slices = kv_rows->ne[1]; ++ ++ // note: when V is a view of K, the gathered V is read from the gathered K, so only K is gathered ++ const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); ++ ++ const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*n_rows*ne12*n_slices, 16); ++ const size_t v_size = v_is_view_of_k ? 0 : GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne20*n_rows*ne22*n_slices, 16); ++ ++ return k_size + v_size; ++} ++ + int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_tensor * op = ctx->node(idx); + +@@ -3449,6 +3483,22 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + GGML_ASSERT(!op->src[3] || op->src[3]->ne[1] >= op->src[0]->ne[1] && + "the Flash-Attention Metal kernel requires the mask to be at least n_queries big"); + ++ // K/V row lists (ggml_flash_attn_ext_rows): src[5] holds one list of cache rows per q slice ++ // the attention loops then run over the mask columns and read K/V rows through the lists ++ const ggml_tensor * kv_rows = op->src[5]; ++ const bool has_rows = kv_rows != nullptr; ++ ++ GGML_ASSERT(!has_rows || (kv_rows->type == GGML_TYPE_I32 && ggml_is_contiguous(kv_rows))); ++ GGML_ASSERT(!has_rows || (kv_rows->ne[1] == ne03 && kv_rows->ne[2] == 1 && kv_rows->ne[3] == 1)); ++ GGML_ASSERT(!has_rows || op->src[3]); ++ ++ // the loop bound over the mask columns / K/V row lists ++ const int64_t ne11_attn = has_rows ? kv_rows->ne[0] : ne11; ++ ++ // the row lists are padded by the KV cache to a multiple of 256, so the pad path never triggers ++ GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_NCPSG == 0); ++ GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); ++ + float scale; + float max_bias; + float logit_softcap; +@@ -3463,6 +3513,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + const bool has_mask = op->src[3] != NULL; + const bool has_sinks = op->src[4] != NULL; ++ ++ GGML_ASSERT(!has_rows || has_mask); + const bool has_bias = max_bias != 0.0f; + const bool has_scap = logit_softcap != 0.0f; + +@@ -3499,12 +3551,25 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + const bool use_sparse = n_kv_max_sparse > 0; + const int n_kv_max_padded = use_sparse ? GGML_PAD(n_kv_max_sparse, OP_FLASH_ATTN_EXT_VEC_NCPSG) : 0; + ++ const bool use_vec = ggml_metal_op_flash_attn_ext_use_vec(op); ++ ++ // with kv_rows, the non-vec path gathers the referenced rows into a contiguous F16 buffer and ++ // attends over it with the F16 kernel - quantized KV is first dequantized with the F16 pass ++ const bool rows_gather = has_rows && !use_vec; ++ + // the vec kernels dequantize the KV inline; no need for the F16 dequant pass in the sparse path +- const bool use_kv_f16 = !use_sparse && ggml_metal_op_flash_attn_ext_use_kv_f16(op); ++ const bool dequant_kv = !use_sparse && (rows_gather ? ++ ggml_is_quantized(op->src[1]->type) : ggml_metal_op_flash_attn_ext_use_kv_f16(op)); ++ ++ const bool use_kv_f16 = !use_sparse && (rows_gather ? true : dequant_kv); + + ggml_metal_buffer_id bid_idx = bid_kv_f16; + bid_idx.offs += ggml_metal_op_flash_attn_ext_extra_kv_f16(op); + ++ // contiguous K/V buffers holding the rows referenced by the kv_rows lists ++ ggml_metal_buffer_id bid_rows = bid_idx; ++ bid_rows.offs += ggml_metal_op_flash_attn_ext_extra_idx(op); ++ + ggml_metal_buffer_id bid_k = bid_src1; + ggml_metal_buffer_id bid_v = bid_src2; + +@@ -3517,7 +3582,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + uint64_t nb22_attn = nb22; + uint64_t nb23_attn = nb23; + +- if (use_kv_f16) { ++ if (dequant_kv) { + assert(ggml_metal_op_flash_attn_ext_extra_kv_f16(op) != 0); + + const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); +@@ -3605,6 +3670,70 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + } + } + ++ // with kv_rows, gather the cache rows referenced by the lists into contiguous F16 buffers ++ // the attention then runs as a standard dense op over the gathered rows (tensor or half8x8 kernel) ++ if (rows_gather) { ++ assert(ggml_metal_op_flash_attn_ext_extra_rows(op) != 0); ++ ++ const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); ++ ++ GGML_ASSERT(ne20 % 4 == 0); ++ ++ const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*ne11_attn*ne12*ne03, 16); ++ ++ ggml_metal_kargs_flash_attn_ext_rows args0 = { ++ /*.ne11 =*/ (int32_t) ne11_attn, ++ /*.ne_12_2 =*/ ne12, ++ /*.ne10 =*/ ne10, ++ /*.ne20 =*/ v_is_view_of_k ? 0 : ne20, // the gathered V is a view of the gathered K ++ /*.v_off =*/ k_size, ++ /*.nb11 =*/ nb11_attn, ++ /*.nb12 =*/ nb12_attn, ++ /*.nb21 =*/ nb21_attn, ++ /*.nb22 =*/ nb22_attn, ++ }; ++ ++ auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_rows(lib, op); ++ const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline0), 64); ++ ++ ggml_metal_encoder_set_pipeline(enc, pipeline0); ++ ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); ++ ggml_metal_encoder_set_buffer (enc, bid_k, 1); ++ ggml_metal_encoder_set_buffer (enc, bid_v, 2); ++ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(kv_rows), 3); ++ ggml_metal_encoder_set_buffer (enc, bid_rows, 4); ++ ++ ggml_metal_encoder_dispatch_threadgroups(enc, ne11_attn, ne03, 1, nth, 1, 1); ++ ++ ggml_metal_op_concurrency_reset(ctx); ++ ++ // contiguous F16 layout of the gathered rows: [DK, n_rows, n_head_kv, n_streams] ++ bid_k = bid_rows; ++ ++ nb10_attn = sizeof(ggml_fp16_t); ++ nb11_attn = nb10_attn*ne10; ++ nb12_attn = nb11_attn*ne11_attn; ++ nb13_attn = nb12_attn*ne12; ++ ++ // if V is a view of K, the gathered V is read from the gathered K with K's strides ++ if (v_is_view_of_k) { ++ bid_v = bid_k; ++ ++ nb20_attn = nb10_attn; ++ nb21_attn = nb11_attn; ++ nb22_attn = nb12_attn; ++ nb23_attn = nb13_attn; ++ } else { ++ bid_v = bid_rows; ++ bid_v.offs += k_size; ++ ++ nb20_attn = sizeof(ggml_fp16_t); ++ nb21_attn = nb20_attn*ne20; ++ nb22_attn = nb21_attn*ne11_attn; ++ nb23_attn = nb22_attn*ne22; ++ } ++ } ++ + if (!use_sparse && ggml_metal_op_flash_attn_ext_use_tensor(op, props_dev->has_tensor)) { + // tensor API kernel + const int nqptg = ne00 >= 512 ? OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE : OP_FLASH_ATTN_EXT_TENSOR_NQPSG; // queries per threadgroup +@@ -3650,9 +3779,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.nb01 =*/ nb01, + /*.nb02 =*/ nb02, + /*.nb03 =*/ nb03, +- /*.ne11 =*/ ne11, ++ /*.ne11 =*/ (int32_t) ne11_attn, + /*.ne_12_2 =*/ ne12, +- /*.ne_12_3 =*/ ne13, ++ /*.ne_12_3 =*/ has_rows ? ne03 : ne13, // the gathered K/V holds one copy per stream + /*.ns10 =*/ ns10, + /*.nb11 =*/ nb11_attn, + /*.nb12 =*/ nb12_attn, +@@ -3710,7 +3839,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + bool need_sync = false; + +- const bool has_kvpad = ne11 % ncpsg != 0; ++ const bool has_kvpad = ne11_attn % ncpsg != 0; + + if (has_kvpad) { + assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); +@@ -3810,9 +3939,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.nb01 =*/ nb01, + /*.nb02 =*/ nb02, + /*.nb03 =*/ nb03, +- /*.ne11 =*/ ne11, ++ /*.ne11 =*/ (int32_t) ne11_attn, + /*.ne_12_2 =*/ ne12, +- /*.ne_12_3 =*/ ne13, ++ /*.ne_12_3 =*/ has_rows ? ne03 : ne13, // the gathered K/V holds one copy per stream + /*.ns10 =*/ ns10, + /*.nb11 =*/ nb11_attn, + /*.nb12 =*/ nb12_attn, +@@ -3878,7 +4007,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + bool need_sync = false; + +- const bool has_kvpad = !use_sparse && ne11 % ncpsg != 0; ++ const bool has_kvpad = !use_sparse && ne11_attn % ncpsg != 0; + + if (use_sparse) { + assert(ggml_metal_op_flash_attn_ext_extra_idx(op) != 0); +@@ -3961,13 +4090,13 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + // queries: Q*NSG*PAD2(ne00, 128) + // attn + mask: NSG*4*Q*C + // results: 2*NSG*Q*PAD2(ne20, 128) +- // sparse idx: NSG*C ints (only when use_sparse) ++ // sparse idx: NSG*C ints (when use_sparse, or when gathering K/V rows) + const int64_t dk_pad = GGML_PAD(ne00, 128); + const int64_t dv_pad = GGML_PAD(ne20, 128); + + auto fa_vec_smem = [&](int64_t nsg, int32_t nqptg) -> size_t { + const size_t smem_half = (size_t) (dk_pad + 4*ncpsg + 2*dv_pad)*nqptg*nsg; +- return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + (use_sparse ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); ++ return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + ((use_sparse || has_rows) ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); + }; + + int64_t nsg = 1; +@@ -3998,7 +4127,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + } else { + nwg = 32; + nsg = 1; +- while (2*nwg*nsg*ncpsg < ne11 && nsg < 4) { ++ while (2*nwg*nsg*ncpsg < ne11_attn && nsg < 4) { + nsg *= 2; + } + } +@@ -4019,7 +4148,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.nb01 =*/ nb01, + /*.nb02 =*/ nb02, + /*.nb03 =*/ nb03, +- /*.ne11 =*/ use_sparse ? n_kv_max_padded : ne11, ++ /*.ne11 =*/ use_sparse ? n_kv_max_padded : (int32_t) ne11_attn, + /*.ne_12_2 =*/ ne12, + /*.ne_12_3 =*/ ne13, + /*.ns10 =*/ ns10, +@@ -4048,7 +4177,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.n_kv_max_padded =*/ n_kv_max_padded, + }; + +- auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); ++ auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); + + GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); + +@@ -4059,7 +4188,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + ggml_metal_encoder_set_buffer (enc, bid_v, 3); + ggml_metal_encoder_set_buffer (enc, bid_src3, 4); + ggml_metal_encoder_set_buffer (enc, bid_src4, 5); +- ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : bid_src0, 8); ++ ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : (has_rows ? ggml_metal_get_buffer_id(kv_rows) : bid_src0), 8); + + const size_t smem = fa_vec_smem(nsg, nqptg); + +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.h b/ggml/src/ggml-metal/ggml-metal-ops.h +index 583d1156b..bed325743 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.h ++++ b/ggml/src/ggml-metal/ggml-metal-ops.h +@@ -46,6 +46,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_blk(const struct ggml_tensor * op); + size_t ggml_metal_op_flash_attn_ext_extra_tmp(const struct ggml_tensor * op); + size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const struct ggml_tensor * op); + size_t ggml_metal_op_flash_attn_ext_extra_idx(const struct ggml_tensor * op); ++size_t ggml_metal_op_flash_attn_ext_extra_rows(const struct ggml_tensor * op); + + int ggml_metal_op_concat (ggml_metal_op_t ctx, int idx); + int ggml_metal_op_repeat (ggml_metal_op_t ctx, int idx); +diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp +index 344882e04..cab2fbf99 100644 +--- a/ggml/src/ggml-metal/ggml-metal.cpp ++++ b/ggml/src/ggml-metal/ggml-metal.cpp +@@ -235,6 +235,7 @@ static size_t ggml_backend_metal_buffer_type_get_alloc_size(ggml_backend_buffer_ + res += ggml_metal_op_flash_attn_ext_extra_tmp(tensor); + res += ggml_metal_op_flash_attn_ext_extra_kv_f16(tensor); + res += ggml_metal_op_flash_attn_ext_extra_idx(tensor); ++ res += ggml_metal_op_flash_attn_ext_extra_rows(tensor); + } break; + case GGML_OP_CUMSUM: + case GGML_OP_ARGSORT: +diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal +index ebee1becd..06fe0a86c 100644 +--- a/ggml/src/ggml-metal/kernels/fa_aux.metal ++++ b/ggml/src/ggml-metal/kernels/fa_aux.metal +@@ -48,6 +48,82 @@ template [[host_name("kernel_flash_attn_ext_kv_q5_0_f16")]] kernel kernel_flash_ + template [[host_name("kernel_flash_attn_ext_kv_q5_1_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; + template [[host_name("kernel_flash_attn_ext_kv_q8_0_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; + ++// gather the K/V cache rows referenced by the kv_rows lists into contiguous F16 buffers ++// - one threadgroup per (row, stream); the attention is then run as a standard dense op over the ++// gathered rows, which avoids the per-tile K/V gather in the main kernels ++// - negative rows are padding: filled with zeros, their mask entries are -INF so they contribute nothing ++kernel void kernel_flash_attn_ext_rows( ++ constant ggml_metal_kargs_flash_attn_ext_rows & args, ++ device const char * k_src, ++ device const char * v_src, ++ device const int * rows, ++ device char * dst, ++ uint3 tgpig[[threadgroup_position_in_grid]], ++ ushort tiitg[[thread_index_in_threadgroup]], ++ ushort3 ntg[[threads_per_threadgroup]]) { ++ const int64_t i1 = tgpig[0]; // row index ++ const int64_t i3 = tgpig[1]; // stream ++ ++ const int64_t row = rows[i1 + i3*args.ne11]; ++ ++ // gathered layout: [DK, n_rows, n_head_kv, n_streams] and [DV, n_rows, n_head_kv, n_streams] F16 ++ device half4 * k_dst = (device half4 *) (dst + i3*args.ne_12_2*args.ne11*args.ne10*sizeof(half)); ++ device half4 * v_dst = (device half4 *) (dst + args.v_off + i3*args.ne_12_2*args.ne11*args.ne20*sizeof(half)); ++ ++ // note: the K/V cache is shared by all streams (ne13 = ne23 = 1), the row list selects the rows ++ // each thread copies up to 4 half4 values (32 bytes) to keep the memory transactions large ++ ++ // K: all heads of this row ++ { ++ const int64_t per_head = args.ne10/4; ++ const int64_t chunks_per_head = (per_head + 3)/4; ++ ++ for (int64_t i = tiitg; i < args.ne_12_2*chunks_per_head; i += ntg.x) { ++ const int64_t i2 = i/chunks_per_head; ++ const int64_t i0 = 4*(i%chunks_per_head); ++ const int n = (int) min((int64_t) 4, per_head - i0); ++ ++ device half4 * dst4 = k_dst + (i2*args.ne11 + i1)*per_head + i0; ++ ++ if (row >= 0) { ++ device const half4 * src4 = (device const half4 *) (k_src + row*args.nb11 + i2*args.nb12) + i0; ++ for (int j = 0; j < n; ++j) { ++ dst4[j] = src4[j]; ++ } ++ } else { ++ for (int j = 0; j < n; ++j) { ++ dst4[j] = half4(0.0h); ++ } ++ } ++ } ++ } ++ ++ // V: all heads of this row ++ { ++ const int64_t per_head = args.ne20/4; ++ const int64_t chunks_per_head = (per_head + 3)/4; ++ ++ for (int64_t i = tiitg; i < args.ne_12_2*chunks_per_head; i += ntg.x) { ++ const int64_t i2 = i/chunks_per_head; ++ const int64_t i0 = 4*(i%chunks_per_head); ++ const int n = (int) min((int64_t) 4, per_head - i0); ++ ++ device half4 * dst4 = v_dst + (i2*args.ne11 + i1)*per_head + i0; ++ ++ if (row >= 0) { ++ device const half4 * src4 = (device const half4 *) (v_src + row*args.nb21 + i2*args.nb22) + i0; ++ for (int j = 0; j < n; ++j) { ++ dst4[j] = src4[j]; ++ } ++ } else { ++ for (int j = 0; j < n; ++j) { ++ dst4[j] = half4(0.0h); ++ } ++ } ++ } ++ } ++} ++ + constant bool FC_flash_attn_ext_pad_has_mask [[function_constant(FC_FLASH_ATTN_EXT_PAD + 0)]]; + + constant int32_t FC_flash_attn_ext_pad_ncpsg [[function_constant(FC_FLASH_ATTN_EXT_PAD + 25)]]; +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index 46270ba4b..c81e4d09b 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -13,6 +13,7 @@ constant int32_t FC_flash_attn_ext_vec_ns20 [[function_constant(FC_FLASH_ATTN_EX + constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 22)]]; + constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; + constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; ++constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; + template< + typename q4_t, // query types in shared memory + typename k4_t, // key types in shared memory +@@ -90,7 +91,8 @@ kernel void kernel_flash_attn_ext_vec( + threadgroup o4_t * so4 = (threadgroup o4_t *) (shmem_f16 + SMEM_Q + SMEM_S + 2*sgitg*Q*PV); // scratch buffer for the results + + // sparse indices for the current block +- threadgroup int * spidx = FC_flash_attn_ext_vec_has_sparse ++ // note: with kv_rows, the buffer holds the row list of the current slice instead ++ threadgroup int * spidx = (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) + ? (threadgroup int *) (shmem_f16 + SMEM) + sgitg*C + : nullptr; + +@@ -165,6 +167,12 @@ kernel void kernel_flash_attn_ext_vec( + ((int64_t)(iq3%args.ne33)*args.ne32 + (iq2%args.ne32))*args.ne31*args.n_kv_max_padded + (iq1%args.ne31)*args.n_kv_max_padded; + } + ++ // K/V row list of the current slice (ggml_flash_attn_ext_rows) ++ // with kv_rows, the loop below runs over the mask columns (args.ne11) and the K/V cache rows ++ // are read indirectly through the list. negative entries are padding, their mask is -INF ++ device const int * rows_list = FC_flash_attn_ext_vec_has_rows ? ++ (device const int *) idx + (int64_t)(iq3%args.ne33)*args.ne11 : nullptr; ++ + float slope = 1.0f; + + // ALiBi +@@ -222,12 +230,12 @@ kernel void kernel_flash_attn_ext_vec( + ic = 0; + } + +- // load the sparse KV indices for the current block into shared memory +- if (FC_flash_attn_ext_vec_has_sparse) { ++ // load the KV row indices for the current block into shared memory ++ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { + FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { + const short i = ii*NW + tiisg; + +- spidx[i] = pidx[ic + i]; ++ spidx[i] = FC_flash_attn_ext_vec_has_rows ? rows_list[ic + i] : pidx[ic + i]; + } + simdgroup_barrier(mem_flags::mem_threadgroup); + } +@@ -242,6 +250,15 @@ kernel void kernel_flash_attn_ext_vec( + sm[qq*C + tiisg] = -MAXHALF; + } + } ++ } else if (FC_flash_attn_ext_vec_has_rows) { ++ // the mask is compact: column ic maps to cache row spidx[tiisg] ++ FOR_UNROLL (short qq = 0; qq < Q; ++qq) { ++ if ((iq1*Q + qq) < args.ne01) { ++ sm[qq*C + tiisg] = pm[qq][ic + tiisg]; ++ } else { ++ sm[qq*C + tiisg] = -MAXHALF; ++ } ++ } + } else { + FOR_UNROLL (short qq = 0; qq < Q; ++qq) { + if ((iq1*Q + qq) < args.ne01) { +@@ -276,7 +293,7 @@ kernel void kernel_flash_attn_ext_vec( + { + device const k4_t * pk4 = nullptr; + +- if (!FC_flash_attn_ext_vec_has_sparse) { ++ if (!FC_flash_attn_ext_vec_has_sparse && !FC_flash_attn_ext_vec_has_rows) { + pk4 = (device const k4_t *) (k + ic*args.nb11); + + pk4 += ty*NS10/4 + tx; +@@ -291,7 +308,7 @@ kernel void kernel_flash_attn_ext_vec( + + // each simdgroup processes Q queries and NE (NW/NL) cache elements + FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { +- if (FC_flash_attn_ext_vec_has_sparse) { ++ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { + // the KV rows are gathered from the index list; -1 entries are padding + const int i11 = spidx[NE*cc + ty]; + if (i11 >= 0) { +@@ -434,7 +451,7 @@ kernel void kernel_flash_attn_ext_vec( + } + } + +- if (FC_flash_attn_ext_vec_has_sparse) { ++ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { + FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { + // the KV rows are gathered from the index list; -1 entries are padding + const int i11 = spidx[NE*cc + ty]; +diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp +index 17ceacc7a..bb92e6c1e 100644 +--- a/ggml/src/ggml-opencl/ggml-opencl.cpp ++++ b/ggml/src/ggml-opencl/ggml-opencl.cpp +@@ -9402,6 +9402,10 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te + case GGML_OP_MEAN: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_FLASH_ATTN_EXT: { ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ if (op->src[5] != nullptr) { ++ return false; ++ } + #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { + return true; +diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp +index 22b2f45e2..67b2e1f9f 100644 +--- a/ggml/src/ggml-openvino/ggml-openvino.cpp ++++ b/ggml/src/ggml-openvino/ggml-openvino.cpp +@@ -1513,6 +1513,11 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { + return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"}; + } + ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ if (op->src[5] != nullptr) { ++ return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"}; ++ } ++ + if (op->src[4] != nullptr) { + return {false, "FLASH_ATTN_EXT with sinks is not supported"}; + } +diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp +index 6759af0ed..ebd0bd09b 100644 +--- a/ggml/src/ggml-sycl/ggml-sycl.cpp ++++ b/ggml/src/ggml-sycl/ggml-sycl.cpp +@@ -7178,7 +7178,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons + case GGML_OP_SOLVE_TRI: + return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; + case GGML_OP_FLASH_ATTN_EXT: +- return ggml_sycl_flash_attn_ext_supported(device, op); ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); + default: + return false; + } +diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +index 436bfe3bb..682c21b01 100644 +--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp ++++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +@@ -15569,6 +15569,10 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm + } + case GGML_OP_FLASH_ATTN_EXT: + { ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ if (op->src[5] != nullptr) { ++ return false; ++ } + bool coopmat2 = device->coopmat2; + uint32_t HSK = op->src[1]->ne[0]; + uint32_t HSV = op->src[2]->ne[0]; +diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp +index 15e6c784b..9bcf2d981 100644 +--- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp ++++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp +@@ -4580,7 +4580,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const + { + // conservative support checks for whether the more resource-intensive shader paths + // can be used, to avoid cases where flash_attn is assigned to the CPU later on +- supports_op = src0->type == GGML_TYPE_F32 && ++ // K/V row lists (ggml_flash_attn_ext_rows) are not supported ++ supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 && + (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || + src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && + (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || +diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c +index 01dc8d05c..7935876fc 100644 +--- a/ggml/src/ggml.c ++++ b/ggml/src/ggml.c +@@ -5516,20 +5516,37 @@ struct ggml_tensor * ggml_arange( + + // ggml_flash_attn_ext + +-struct ggml_tensor * ggml_flash_attn_ext( ++static struct ggml_tensor * ggml_flash_attn_ext_impl( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * mask, ++ struct ggml_tensor * kv_rows, + float scale, + float max_bias, + float logit_softcap) { + GGML_ASSERT(ggml_can_mul_mat(k, q)); + // TODO: check if vT can be multiplied by (k*qT) + +- GGML_ASSERT(q->ne[3] == k->ne[3]); +- GGML_ASSERT(q->ne[3] == v->ne[3]); ++ if (kv_rows) { ++ // k and v are shared by all q slices, kv_rows picks the rows of each slice ++ GGML_ASSERT(mask && mask->ne[0] == kv_rows->ne[0]); ++ GGML_ASSERT(mask->ne[1] >= q->ne[1]); ++ GGML_ASSERT(kv_rows->type == GGML_TYPE_I32 && ggml_is_contiguous(kv_rows)); ++ GGML_ASSERT(kv_rows->ne[0] > 0 && kv_rows->ne[0] <= INT32_MAX); ++ GGML_ASSERT(kv_rows->ne[1] == q->ne[3] && kv_rows->ne[2] == 1 && kv_rows->ne[3] == 1); ++ GGML_ASSERT(k->ne[1] > 0 && k->ne[1] <= INT32_MAX && k->ne[1] == v->ne[1]); ++ GGML_ASSERT(k->ne[2] == v->ne[2]); ++ GGML_ASSERT(q->nb[0] == ggml_type_size(q->type)); ++ GGML_ASSERT(k->nb[0] == ggml_type_size(k->type)); ++ GGML_ASSERT(v->nb[0] == ggml_type_size(v->type)); ++ GGML_ASSERT(k->ne[3] == 1); ++ GGML_ASSERT(v->ne[3] == 1); ++ } else { ++ GGML_ASSERT(q->ne[3] == k->ne[3]); ++ GGML_ASSERT(q->ne[3] == v->ne[3]); ++ } + + if (mask) { + GGML_ASSERT(mask->type == GGML_TYPE_F16); +@@ -5556,10 +5573,36 @@ struct ggml_tensor * ggml_flash_attn_ext( + result->src[1] = k; + result->src[2] = v; + result->src[3] = mask; ++ result->src[5] = kv_rows; + + return result; + } + ++struct ggml_tensor * ggml_flash_attn_ext( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, ++ struct ggml_tensor * k, ++ struct ggml_tensor * v, ++ struct ggml_tensor * mask, ++ float scale, ++ float max_bias, ++ float logit_softcap) { ++ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, NULL, scale, max_bias, logit_softcap); ++} ++ ++struct ggml_tensor * ggml_flash_attn_ext_rows( ++ struct ggml_context * ctx, ++ struct ggml_tensor * q, ++ struct ggml_tensor * k, ++ struct ggml_tensor * v, ++ struct ggml_tensor * mask, ++ struct ggml_tensor * kv_rows, ++ float scale, ++ float max_bias, ++ float logit_softcap) { ++ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, kv_rows, scale, max_bias, logit_softcap); ++} ++ + + void ggml_flash_attn_ext_set_prec( + struct ggml_tensor * a, diff --git a/include/llama.h b/include/llama.h index 428f51f8d..8e39fdf48 100644 --- a/include/llama.h @@ -121,6 +1508,91 @@ index 3b8f45d26..cd34e36a9 100644 LLM_KV_ATTENTION_INDEXER_BLOCK_SIZE, LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, LLM_KV_ATTENTION_INDEXER_TYPES, +diff --git a/src/llama-context-kv-rows.cpp b/src/llama-context-kv-rows.cpp +new file mode 100644 +index 000000000..463e53a9d +--- /dev/null ++++ b/src/llama-context-kv-rows.cpp +@@ -0,0 +1,79 @@ ++#include "llama-context.h" ++ ++#include "llama-graph.h" ++#include "llama-impl.h" ++ ++#include ++#include ++#include ++ ++void llama_context::resolve_fused_kv_rows( ++ const llama_memory_context_i * mctx, ++ uint32_t n_seqs, ++ const skippy_graph_build_inputs & graph_build_inputs) { ++ cparams.fused_kv_rows = false; ++ if (!cparams.flash_attn || !cparams.kv_unified) { ++ return; ++ } ++ ++ // Resolve the same one-token-per-owner shape as the upstream row probe, ++ // but compare to actual ordinary attention placement, not weight placement. ++ // In particular --no-kv-offload and filtered stages need not share their ++ // weight layer's device. Only stable backend handles survive the re-reserve. ++ using Key = std::pair; ++ std::map ordinary; ++ auto reserve = [&]() { ++ if (!graph_reserve(n_seqs, n_seqs, n_seqs, mctx, true, nullptr, graph_build_inputs)) { ++ throw std::runtime_error("failed to reserve graph for Flash Attention over K/V rows check"); ++ } ++ }; ++ reserve(); ++ std::map ordinals; ++ for (const auto & node : get_gf_res_reserve()->get_fused_nodes()) { ++ if (node.op == LLM_FUSED_OP_FLASH_ATTN) { ++ const auto backend = ggml_backend_sched_get_tensor_backend(sched.get(), node.tensor); ++ if (!backend || node.il < 0) { ++ return; ++ } ++ ordinary.emplace(Key{node.il, ordinals[node.il]++}, backend); ++ } ++ } ++ if (ordinary.empty()) { ++ return; ++ } ++ ++ try { ++ cparams.fused_kv_rows = true; ++ reserve(); ++ ordinals.clear(); ++ size_t observed = 0, row_nodes = 0; ++ bool same_backends = true; ++ for (const auto & node : get_gf_res_reserve()->get_fused_nodes()) { ++ if (node.op != LLM_FUSED_OP_FLASH_ATTN && node.op != LLM_FUSED_OP_FLASH_ATTN_KV_ROWS) { ++ continue; ++ } ++ const Key key{node.il, ordinals[node.il]++}; ++ const auto previous = ordinary.find(key); ++ const auto actual = ggml_backend_sched_get_tensor_backend(sched.get(), node.tensor); ++ same_backends &= previous != ordinary.end() && actual && previous->second == actual; ++ row_nodes += node.op == LLM_FUSED_OP_FLASH_ATTN_KV_ROWS; ++ ++observed; ++ } ++ cparams.fused_kv_rows = same_backends && observed == ordinary.size() && row_nodes > 0; ++ } catch (...) { ++ // Restore the ordinary graph before propagating the original probe ++ // failure. If even ordinary reservation fails, construction fails ++ // closed; no partially checked row graph is executable. ++ cparams.fused_kv_rows = false; ++ reserve(); ++ throw; ++ } ++ if (!cparams.fused_kv_rows) { ++ // Leave the scheduler with the ordinary graph now, rather than relying ++ // on a later worst-case reserve to remove the rejected row graph. ++ reserve(); ++ LLAMA_LOG_INFO("%s: K/V rows unavailable on ordinary attention backends, keeping ordinary graph\n", __func__); ++ } else { ++ LLAMA_LOG_INFO("%s: K/V rows enabled on ordinary attention backends\n", __func__); ++ } ++} diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 9011bef0d..42aa95c19 100644 --- a/src/llama-context.cpp @@ -1318,173 +2790,1965 @@ index 39c5619df..12771e390 100644 + void set_fused_gdn_for_test(bool fused_ar, bool fused_chunk); +#endif - ggml_backend_sched_t get_sched() const; + ggml_backend_sched_t get_sched() const; + +@@ -69,6 +99,7 @@ struct llama_context { + uint32_t n_ctx_seq() const; + uint32_t n_batch() const; + uint32_t n_ubatch() const; ++ bool kv_unified() const; + uint32_t n_seq_max() const; + + uint32_t n_threads() const; +@@ -78,6 +109,7 @@ struct llama_context { + + // return true if the memory was updated + bool memory_update(bool optimize); ++ bool memory_update(bool optimize, const skippy_graph_build_inputs & graph_build_inputs); + + enum llama_pooling_type pooling_type() const; + +@@ -149,14 +181,19 @@ struct llama_context { + const llama_ubatch & ubatch, + llm_graph_type gtype, + llama_memory_context_i * mctx, +- ggml_status & ret); ++ ggml_status & ret, ++ const skippy_graph_build_inputs & graph_build_inputs = {}); + + int encode(const llama_batch_ext & batch_inp); ++ int encode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + int decode(const llama_batch_ext & batch_inp); ++ int decode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + + // compat version + int encode(const llama_batch & batch_inp); ++ int encode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + int decode(const llama_batch & batch_inp); ++ int decode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + + // + // state save/load +@@ -263,13 +300,34 @@ public: + + // can reuse the llm_graph_result instance of the context (for example to update a memory module) + llm_graph_result * get_gf_res_reserve() const; ++ uint32_t admit_skippy_cache_capabilities(uint32_t memory_capabilities) { ++ if (!skippy_cache_admission_bound) { ++ skippy_cache_admitted_capabilities = skippy_cache_profile_seen ++ ? skippy_cache_capabilities & memory_capabilities : 0; ++ skippy_cache_admission_bound = true; ++ } ++ return skippy_cache_admitted_capabilities; ++ } ++ // live graph result of the most recent schedule, or null before the first build ++ llm_graph_result * get_gf_res_prev_active() const; + + // returns the result of ggml_backend_sched_graph_compute_async execution + ggml_status graph_compute(ggml_cgraph * gf, bool batched); + + // reserve a graph with a dummy ubatch of the specified size +- ggml_cgraph * graph_reserve( +- uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only = false, size_t * sizes = nullptr); ++ ggml_cgraph * graph_reserve(uint32_t n_tokens, ++ uint32_t n_seqs, ++ uint32_t n_outputs, ++ const llama_memory_context_i * mctx, ++ bool split_only = false, ++ size_t * sizes = nullptr, ++ const skippy_graph_build_inputs & graph_build_inputs = {}, ++ bool embedding_input = false); ++ ++ bool get_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; ++ bool get_input_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; ++ bool get_activation_frontier(std::vector & parts) const; ++ bool get_input_activation_frontier(std::vector & parts) const; + + bool set_sampler(llama_seq_id seq_id, llama_sampler * sampler); + +@@ -280,7 +338,8 @@ private: + llm_graph_result * res, + const llama_ubatch & ubatch, + const llama_memory_context_i * mctx, +- llm_graph_type gtype) const; ++ llm_graph_type gtype, ++ const skippy_graph_build_inputs & graph_build_inputs = {}) const; + + llm_graph_cb graph_get_cb() const; + +@@ -295,7 +354,10 @@ private: + + // disable auto fused ops (Flash Attention, Gated Delta Net) whose op lands on a device + // that differs from the layer it belongs to (usually due to missing backend support) +- void resolve_fused_ops(const llama_memory_context_i * mctx, uint32_t n_seqs); ++ void resolve_fused_ops( ++ const llama_memory_context_i * mctx, ++ uint32_t n_seqs, ++ const skippy_graph_build_inputs & graph_build_inputs); ++ ++ void resolve_fused_kv_rows( ++ const llama_memory_context_i * mctx, ++ uint32_t n_seqs, ++ const skippy_graph_build_inputs & graph_build_inputs); + + // TODO: read/write lora adapters and cvec + size_t state_write_data(llama_io_write_i & io); +@@ -312,6 +374,10 @@ private: + + llama_cparams cparams; + ++ const skippy_graph_build_inputs graph_build_inputs; ++ uint64_t computation_generation = 0; ++ ++ + llama_adapter_cvec_ptr cvec; + llama_adapter_loras_ptr loras; + +@@ -378,6 +444,7 @@ private: + ggml_backend_sched_ptr sched; + + bool sched_need_reserve = true; ++ uint64_t sched_reserve_count = 0; + + // whether the reserve graph has a logits tensor, set in sched_reserve() + // true until then, because the first output_reserve() runs before any graph is reserved +@@ -425,9 +492,32 @@ private: + // Separate arenas give batches with and without outputs distinct CUDA graph cache keys. + std::array gf_res_prev; + llm_graph_result_ptr gf_res_reserve; ++ // Intersect every reserved prefill/decode profile; no configuration can authorize state coverage. ++ uint32_t skippy_cache_capabilities = UINT32_MAX; ++ bool skippy_cache_profile_seen = false; ++ uint32_t skippy_cache_admitted_capabilities = 0; ++ bool skippy_cache_admission_bound = false; + + llm_graph_result * gf_res_prev_active = nullptr; + ++ bool activation_boundary_observed = false; ++ bool activation_boundary_stable = true; ++ enum ggml_type activation_boundary_type = GGML_TYPE_COUNT; ++ uint64_t activation_boundary_elements_per_token = 0; ++ uint64_t activation_boundary_bytes_per_token = 0; ++ ++ bool input_activation_boundary_observed = false; ++ bool input_activation_boundary_stable = true; ++ enum ggml_type input_activation_boundary_type = GGML_TYPE_COUNT; ++ uint64_t input_activation_boundary_elements_per_token = 0; ++ uint64_t input_activation_boundary_bytes_per_token = 0; ++ bool activation_frontier_observed = false; ++ bool activation_frontier_stable = true; ++ std::vector activation_frontier; ++ bool input_activation_frontier_observed = false; ++ bool input_activation_frontier_stable = true; ++ std::vector input_activation_frontier; ++ + // host buffer for the model output (logits and embeddings) + ggml_backend_buffer_ptr buf_output; + +diff --git a/src/llama-cparams.h b/src/llama-cparams.h +index f4eb181a7..3705569fc 100644 +--- a/src/llama-cparams.h ++++ b/src/llama-cparams.h +@@ -39,6 +39,8 @@ struct llama_cparams { + bool offload_kqv; + bool flash_attn; + bool auto_fa; ++ bool fused_kv_rows; // backend-probed unified per-owner attention rows ++ bool auto_fkvr; + bool fused_gdn_ar; // use fused gated delta net (autoregressive) + bool fused_gdn_ch; // use fused gated delta net (chunked) + bool auto_fgdn; +diff --git a/src/llama-ext.h b/src/llama-ext.h +index b55c0c357..9449e1da7 100644 +--- a/src/llama-ext.h ++++ b/src/llama-ext.h +@@ -75,6 +75,12 @@ LLAMA_API bool llama_quant_tensor_allows_quantization( + const quantize_state_impl * qs, + const ggml_tensor * tensor); + ++// Returns whether the selected tensor type requires importance weights. ++LLAMA_API bool llama_quant_tensor_requires_imatrix( ++ const ggml_tensor * tensor, ++ ggml_type type, ++ llama_ftype ftype); ++ + // Compute quantization type assignments for a list of tensors. + // All tensors should be quantizable (use llama_quant_tensor_allows_quantization to filter). + // result_types: caller-allocated array of n_tensors elements, filled with assigned types. +diff --git a/src/llama-graph-kv-rows.cpp b/src/llama-graph-kv-rows.cpp +new file mode 100644 +index 000000000..5da812201 +--- /dev/null ++++ b/src/llama-graph-kv-rows.cpp +@@ -0,0 +1,124 @@ ++#include "llama-graph.h" ++ ++#include "llama-cparams.h" ++#include "llama-kv-cache.h" ++#include "llama-kv-cache-iswa.h" ++#include "ggml-backend.h" ++ ++bool llm_graph_context::supports_row_attn(const ggml_tensor * node, const ggml_tensor * storage) const { ++ while (storage->view_src) { ++ storage = storage->view_src; ++ } ++ if (storage->buffer) { ++ const auto type = ggml_backend_buffer_get_type(storage->buffer); ++ const auto device = ggml_backend_buft_get_device(type); ++ if (device) { ++ return ggml_backend_dev_supports_op(device, node); ++ } ++ // Host storage may use the scheduler's existing CPU backend. Never ++ // redirect unsupported GPU-owned storage through a CPU pool copy. ++ if (!ggml_backend_buft_is_host(type) || !sched) { ++ return false; ++ } ++ for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { ++ const auto backend = ggml_backend_sched_get_backend(sched, i); ++ const auto device_cpu = ggml_backend_get_device(backend); ++ if (device_cpu && ggml_backend_dev_type(device_cpu) == GGML_BACKEND_DEVICE_TYPE_CPU && ++ ggml_backend_supports_op(backend, node)) { ++ return true; ++ } ++ } ++ return false; ++ } ++ return sched && ggml_backend_sched_get_n_backends(sched) > 0 && ++ ggml_backend_supports_op(ggml_backend_sched_get_backend(sched, 0), node); ++} ++ ++namespace { ++ ++void build_pool_row_inputs( ++ ggml_context * ctx, const llama_ubatch & ubatch, const llama_cparams & params, ++ const llama_kv_cache_context * mctx, ggml_tensor * & row_input, ggml_tensor * & mask_input, ++ uint32_t & physical_extent, const char * row_name, const char * mask_name) { ++ if (!params.flash_attn || !params.fused_kv_rows || params.training) { ++ return; ++ } ++ const uint32_t rows = mctx->get_n_kv_rows(); ++ const uint32_t slices = llama_kv_cache::get_n_kv_slices(ubatch); ++ if (!rows || rows % 256 != 0 || !slices) { ++ return; ++ } ++ physical_extent = mctx->get_n_kv(); ++ row_input = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, rows, slices); ++ mask_input = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, rows, ubatch.n_tokens / slices, 1, slices); ++ ggml_set_input(row_input); ++ ggml_set_input(mask_input); ++ ggml_set_name(row_input, row_name); ++ ggml_set_name(mask_input, mask_name); ++} ++ ++bool can_reuse_pool_row_inputs( ++ const llama_ubatch & ubatch, const llama_cparams & params, const llama_kv_cache_context * mctx, ++ const ggml_tensor * row_input, const ggml_tensor * mask_input, uint32_t physical_extent) { ++ const uint32_t rows = params.flash_attn && params.fused_kv_rows && !params.training ? mctx->get_n_kv_rows() : 0; ++ const uint32_t slices = llama_kv_cache::get_n_kv_slices(ubatch); ++ const bool use_rows = rows && rows % 256 == 0 && slices; ++ if (use_rows != (row_input != nullptr)) { ++ return false; ++ } ++ if (!use_rows) { ++ return true; ++ } ++ return physical_extent == mctx->get_n_kv() && row_input->ne[0] == rows && ++ row_input->ne[1] == slices && mask_input->ne[0] == rows && ++ mask_input->ne[1] == ubatch.n_tokens / slices && mask_input->ne[3] == slices; ++} ++ ++void set_pool_row_inputs( ++ const llama_ubatch & ubatch, const llama_cparams & params, const llama_kv_cache_context * mctx, ++ ggml_tensor * row_input, ggml_tensor * mask_input) { ++ if (row_input && row_input->buffer) { ++ mctx->set_input_kv_rows(row_input, &ubatch); ++ } ++ if (mask_input && mask_input->buffer) { ++ GGML_ASSERT(row_input && row_input->buffer); ++ mctx->set_input_kq_mask(mask_input, &ubatch, params.causal_attn, row_input); ++ } ++} ++ ++} // namespace ++ ++void llm_graph_input_attn_kv::build_row_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { ++ build_pool_row_inputs(ctx, ubatch, cparams, mctx, self_kv_rows, self_read_mask, ++ read_physical_extent, "attn_inp_kv_rows", "attn_inp_read_mask"); ++} ++ ++bool llm_graph_input_attn_kv::can_reuse_row_inputs(const llama_ubatch & ubatch, const llama_cparams & params) { ++ return can_reuse_pool_row_inputs(ubatch, params, mctx, self_kv_rows, self_read_mask, read_physical_extent); ++} ++ ++void llm_graph_input_attn_kv::set_row_inputs(const llama_ubatch & ubatch) { ++ set_pool_row_inputs(ubatch, cparams, mctx, self_kv_rows, self_read_mask); ++} ++ ++void llm_graph_input_attn_kv_iswa::build_row_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { ++ build_pool_row_inputs(ctx, ubatch, cparams, mctx->get_base(), self_kv_rows, self_read_mask, ++ read_physical_extent, "attn_inp_kv_rows", "attn_inp_read_mask"); ++ build_pool_row_inputs(ctx, ubatch, cparams, mctx->get_swa(), self_kv_rows_swa, self_read_mask_swa, ++ read_physical_extent_swa, "attn_inp_kv_rows_swa", "attn_inp_read_mask_swa"); ++} ++ ++bool llm_graph_input_attn_kv_iswa::can_reuse_row_inputs( ++ const llama_ubatch & ubatch, const llama_cparams & params) { ++ // Evaluate both pools: their compact extents and SWA visibility are independent. ++ const bool base = can_reuse_pool_row_inputs(ubatch, params, mctx->get_base(), ++ self_kv_rows, self_read_mask, read_physical_extent); ++ const bool swa = can_reuse_pool_row_inputs(ubatch, params, mctx->get_swa(), ++ self_kv_rows_swa, self_read_mask_swa, read_physical_extent_swa); ++ return base && swa; ++} ++ ++void llm_graph_input_attn_kv_iswa::set_row_inputs(const llama_ubatch & ubatch) { ++ set_pool_row_inputs(ubatch, cparams, mctx->get_base(), self_kv_rows, self_read_mask); ++ set_pool_row_inputs(ubatch, cparams, mctx->get_swa(), self_kv_rows_swa, self_read_mask_swa); ++} +diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp +index 6cadda971..67b94396a 100644 +--- a/src/llama-graph.cpp ++++ b/src/llama-graph.cpp +@@ -17,6 +17,7 @@ + #include "llama-memory-hybrid-iswa.h" + #include "llama-memory-recurrent.h" + ++#include + #include + #include + #include +@@ -25,6 +26,42 @@ + #include + #include + ++bool skippy_graph_build_inputs::topology_equal(const skippy_graph_build_inputs & other) const { ++ if (activation_import_identities != other.activation_import_identities || ++ activation_import_bindings != other.activation_import_bindings || ++ activation_export_identities != other.activation_export_identities || ++ activation_export_bindings != other.activation_export_bindings || ++ resident_tensor_names != other.resident_tensor_names || ++ execution_contract != other.execution_contract) return false; ++ if (activation_frontier.size() != other.activation_frontier.size()) return false; ++ for (size_t index = 0; index < activation_frontier.size(); ++index) { ++ const auto & left = activation_frontier[index]; ++ const auto & right = other.activation_frontier[index]; ++ if ((left.values != nullptr) != (right.values != nullptr) || ++ left.payload_bytes != right.payload_bytes || left.ggml_type != right.ggml_type || ++ left.rank != right.rank || left.token_axis != right.token_axis) return false; ++ for (int dimension = 0; dimension < GGML_MAX_DIMS; ++dimension) { ++ if (left.dimensions[dimension] != right.dimensions[dimension] || ++ left.byte_strides[dimension] != right.byte_strides[dimension]) return false; ++ } ++ } ++ return selection.enabled == other.selection.enabled && ++ selection.layer_start == other.selection.layer_start && ++ selection.layer_end == other.selection.layer_end && ++ selection.glm_dsa_policy_profile == other.selection.glm_dsa_policy_profile && ++ selection.glm_dsa_policy_flags == other.selection.glm_dsa_policy_flags && ++ selection.glm_dsa_short_prefill_max_tokens == other.selection.glm_dsa_short_prefill_max_tokens && ++ selection.glm_dsa_direct_sparse_decode_max_top_k == other.selection.glm_dsa_direct_sparse_decode_max_top_k && ++ selection.glm_dsa_dense_sparse_mask_max_bytes == other.selection.glm_dsa_dense_sparse_mask_max_bytes && ++ selection.glm_dsa_compact_flash_min_kv == other.selection.glm_dsa_compact_flash_min_kv && ++ selection.glm_dsa_phase_hint == other.selection.glm_dsa_phase_hint && ++ (activation_tokens.tokens != nullptr) == (other.activation_tokens.tokens != nullptr) && ++ activation_tokens.token_count == other.activation_tokens.token_count && ++ (mtp_embeddings.values != nullptr) == (other.mtp_embeddings.values != nullptr) && ++ mtp_embeddings.token_count == other.mtp_embeddings.token_count && ++ mtp_embeddings.n_embd == other.mtp_embeddings.n_embd; ++} ++ + // dedup helpers + + static ggml_tensor * build_attn_inp_kq_mask( +@@ -68,13 +105,13 @@ static bool can_reuse_kq_mask( + // impl + + void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) { +- if (ubatch->token) { ++ if (ubatch->token && tokens != nullptr && tokens->buffer != nullptr) { + const int64_t n_tokens = ubatch->n_tokens; + + ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens)); + } + +- if (ubatch->embd && embd && !ubatch->is_mixed()) { ++ if (ubatch->embd && embd != nullptr && embd->buffer != nullptr && !ubatch->is_mixed()) { + GGML_ASSERT(n_embd == embd->ne[0]); + + const int64_t n_tokens = ubatch->n_tokens; +@@ -128,11 +165,11 @@ static int64_t llm_graph_n_tok_rows(const llama_ubatch & ubatch) { + bool llm_graph_input_embd::can_reuse(const llm_graph_params & params) { + bool res = true; + +- res &= (!params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens); +- res &= (!params.ubatch.embd) || (embd && embd->ne[1] == params.ubatch.n_tokens); +- res &= (!mixed_tokens) || mixed_tokens->ne[0] == llm_graph_n_tok_rows(params.ubatch); +- res &= (!mixed_embd) || mixed_embd->ne[1] == params.ubatch.n_tokens; +- res &= (!scale_rows) || scale_rows->ne[1] == params.ubatch.n_tokens; ++ res &= (!params.ubatch.token) || (tokens && tokens->buffer && tokens->ne[0] == params.ubatch.n_tokens); ++ res &= (!params.ubatch.embd) || (embd && embd->buffer && embd->ne[1] == params.ubatch.n_tokens); ++ res &= (!mixed_tokens) || (mixed_tokens->buffer && mixed_tokens->ne[0] == llm_graph_n_tok_rows(params.ubatch)); ++ res &= (!mixed_embd) || (mixed_embd->buffer && mixed_embd->ne[1] == params.ubatch.n_tokens); ++ res &= (!scale_rows) || (scale_rows->buffer && scale_rows->ne[1] == params.ubatch.n_tokens); + + return res; + } +@@ -145,11 +182,21 @@ void llm_graph_input_embd_h::set_input(const llama_ubatch * ubatch) { + if (ubatch->token) { + ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens)); + } else { +- // note: mtmd embedding input goes through here + GGML_ASSERT(ubatch->embd); + GGML_ASSERT(n_embd == embd->ne[0]); ++ const float * values = ubatch->embd; ++ if (mtp_embeddings.values != nullptr) { ++ GGML_ASSERT(mtp_embeddings.n_embd == n_embd); ++ GGML_ASSERT(ubatch->pos != nullptr); ++ const llama_pos token_offset = ubatch->pos[0] - mtp_embeddings.pos_start; ++ GGML_ASSERT(token_offset >= 0); ++ GGML_ASSERT( ++ static_cast(token_offset) + ubatch->n_tokens <= ++ mtp_embeddings.token_count); ++ values = mtp_embeddings.values + static_cast(token_offset)*n_embd; ++ } + +- ggml_backend_tensor_set(embd, ubatch->embd, 0, n_tokens*n_embd*ggml_element_size(embd)); ++ ggml_backend_tensor_set(embd, values, 0, n_tokens*n_embd*ggml_element_size(embd)); + } + + GGML_ASSERT(ubatch->embd_state && "this graph requires a state embedding, see llama_batch_ext_set_embd_state()"); +@@ -158,18 +205,24 @@ void llm_graph_input_embd_h::set_input(const llama_ubatch * ubatch) { + ggml_backend_tensor_set(h, ubatch->embd_state, 0, n_tokens*n_embd_state*ggml_element_size(h)); + } + ++void llm_graph_input_embd_h::set_build_inputs(const skippy_graph_build_inputs & inputs) { ++ mtp_embeddings = inputs.mtp_embeddings; ++} ++ + bool llm_graph_input_embd_h::can_reuse(const llm_graph_params & params) { + bool res = true; + +- res &= (!params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens); +- res &= (!params.ubatch.embd) || (embd && embd->ne[1] == params.ubatch.n_tokens); +- res &= (!params.ubatch.embd_state) || (h && h->ne[1] == params.ubatch.n_tokens); ++ res &= (!params.ubatch.token) || (tokens && tokens->buffer && tokens->ne[0] == params.ubatch.n_tokens); ++ res &= (params.ubatch.token) || (embd && embd->buffer && embd->ne[1] == params.ubatch.n_tokens); ++ res &= (!params.ubatch.embd_state) || (h && h->buffer && h->ne[1] == params.ubatch.n_tokens); + + return res; + } + + void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { +- if (ubatch->pos && pos) { ++ // A filtered stage can omit positional work entirely. In that case the ++ // scheduler leaves this otherwise declared graph input unallocated. ++ if (ubatch->pos && pos && pos->buffer) { + const int64_t n_tokens = ubatch->n_tokens; + + const bool has_embd = ubatch->is_mixed() || ubatch->token == nullptr; +@@ -205,7 +258,7 @@ void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { + bool llm_graph_input_pos::can_reuse(const llm_graph_params & params) { + bool res = true; + +- res &= pos->ne[0] == params.ubatch.n_tokens*n_pos_per_embd; ++ res &= pos && pos->buffer && pos->ne[0] == params.ubatch.n_tokens*n_pos_per_embd; + + return res; + } +@@ -524,6 +577,7 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { + + void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + // the idxs are left unallocated when the KV cache is bypassed during training ++ // Filtered stages retain only the leaves used by their selected closure. + if (self_k_idxs && self_k_idxs->buffer) { + mctx->set_input_k_idxs(self_k_idxs, ubatch); + } +@@ -537,6 +591,8 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); + } + ++ set_row_inputs(*ubatch); ++ + if (self_k_rot && self_k_rot->buffer) { + mctx->set_input_k_rot(self_k_rot); + } +@@ -547,24 +603,38 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + } + + bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) { +- const auto * mctx = static_cast(params.mctx); ++ return can_reuse_attn(static_cast(params.mctx), ++ params.ubatch, params.cparams); ++} + +- this->mctx = mctx; ++bool llm_graph_input_attn_kv::can_reuse_attn(const llama_kv_cache_context * context, ++ const llama_ubatch & ubatch, const llama_cparams & params) { ++ mctx = context; + +- bool res = true; ++ bool res = can_reuse_row_inputs(ubatch, params); + +- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; ++ if (self_k_idxs && self_k_idxs->buffer) { ++ res &= self_k_idxs->ne[0] == ubatch.n_tokens; ++ } + //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there + +- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); ++ if (self_kq_mask && self_kq_mask->buffer) { ++ res &= can_reuse_kq_mask(self_kq_mask, mctx, ubatch, params); ++ } + + return res; + } + + void llm_graph_input_attn_k::set_input(const llama_ubatch * ubatch) { +- mctx->set_input_k_idxs(self_k_idxs, ubatch); ++ // Filtered stages can omit their attention path, leaving these declared ++ // graph inputs unallocated by the scheduler. ++ if (self_k_idxs && self_k_idxs->buffer) { ++ mctx->set_input_k_idxs(self_k_idxs, ubatch); ++ } + +- mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); ++ if (self_kq_mask && self_kq_mask->buffer) { ++ mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); ++ } + } + + bool llm_graph_input_attn_k::can_reuse(const llm_graph_params & params) { +@@ -576,9 +646,10 @@ bool llm_graph_input_attn_k::can_reuse(const llm_graph_params & params) { + bool llm_graph_input_attn_k::can_reuse_impl(const llm_graph_params & params) { + bool res = true; + +- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; ++ res &= self_k_idxs && self_k_idxs->buffer && self_k_idxs->ne[0] == params.ubatch.n_tokens; + +- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); ++ res &= self_kq_mask && self_kq_mask->buffer && ++ can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); + + return res; + } +@@ -594,37 +665,51 @@ llm_graph_input_attn_kv_msa::llm_graph_input_attn_kv_msa( + void llm_graph_input_attn_kv_msa::set_input(const llama_ubatch * ubatch) { + llm_graph_input_attn_kv::set_input(ubatch); + +- if (self_k_idxs_idx) { ++ if (self_k_idxs_idx && self_k_idxs_idx->buffer) { + mctx_msa->get_idx()->set_input_k_idxs(self_k_idxs_idx, ubatch); + } + } + + bool llm_graph_input_attn_kv_msa::can_reuse(const llm_graph_params & params) { +- mctx_msa = static_cast(params.mctx); ++ const auto * runtime_memory = dynamic_cast(params.mctx); ++ if (runtime_memory == nullptr) return false; ++ mctx_msa = runtime_memory; + + // the parent class operates on the base cache context + this->mctx = mctx_msa->get_base(); + + bool res = true; + +- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; +- if (self_k_idxs_idx) { ++ if (self_k_idxs && self_k_idxs->buffer) { ++ res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; ++ } ++ if (self_k_idxs_idx && self_k_idxs_idx->buffer) { + res &= self_k_idxs_idx->ne[0] == params.ubatch.n_tokens; + } + +- res &= can_reuse_kq_mask(self_kq_mask, this->mctx, params.ubatch, params.cparams); ++ if (self_kq_mask && self_kq_mask->buffer) { ++ res &= can_reuse_kq_mask(self_kq_mask, this->mctx, params.ubatch, params.cparams); ++ } + + return res; + } + + void llm_graph_input_attn_k_dsa::set_input(const llama_ubatch * ubatch) { +- mctx->get_mla()->set_input_k_idxs(self_k_idxs_mla, ubatch); ++ if (self_k_idxs_mla && self_k_idxs_mla->buffer) { ++ mctx->get_mla()->set_input_k_idxs(self_k_idxs_mla, ubatch); ++ } + +- mctx->get_mla()->set_input_kq_mask(self_kq_mask_mla, ubatch, cparams.causal_attn); ++ if (self_kq_mask_mla && self_kq_mask_mla->buffer) { ++ mctx->get_mla()->set_input_kq_mask(self_kq_mask_mla, ubatch, cparams.causal_attn); ++ } + +- mctx->get_lid()->set_input_k_idxs(self_k_idxs_lid, ubatch); ++ if (self_k_idxs_lid && self_k_idxs_lid->buffer) { ++ mctx->get_lid()->set_input_k_idxs(self_k_idxs_lid, ubatch); ++ } + +- mctx->get_lid()->set_input_kq_mask(self_kq_mask_lid, ubatch, cparams.causal_attn); ++ if (self_kq_mask_lid && self_kq_mask_lid->buffer) { ++ mctx->get_lid()->set_input_kq_mask(self_kq_mask_lid, ubatch, cparams.causal_attn); ++ } + + // left unallocated when the indexer does not use the rotation + if (self_k_rot_lid && self_k_rot_lid->buffer) { +@@ -633,7 +718,9 @@ void llm_graph_input_attn_k_dsa::set_input(const llama_ubatch * ubatch) { + } + + bool llm_graph_input_attn_k_dsa::can_reuse(const llm_graph_params & params) { +- mctx = static_cast(params.mctx); ++ const auto * runtime_memory = dynamic_cast(params.mctx); ++ if (runtime_memory == nullptr) return false; ++ mctx = runtime_memory; + + return can_reuse_impl(params); + } +@@ -641,11 +728,19 @@ bool llm_graph_input_attn_k_dsa::can_reuse(const llm_graph_params & params) { + bool llm_graph_input_attn_k_dsa::can_reuse_impl(const llm_graph_params & params) { + bool res = true; + +- res &= self_k_idxs_mla->ne[0] == params.ubatch.n_tokens; +- res &= self_k_idxs_lid->ne[0] == params.ubatch.n_tokens; ++ if (self_k_idxs_mla && self_k_idxs_mla->buffer) { ++ res &= self_k_idxs_mla->ne[0] == params.ubatch.n_tokens; ++ } ++ if (self_k_idxs_lid && self_k_idxs_lid->buffer) { ++ res &= self_k_idxs_lid->ne[0] == params.ubatch.n_tokens; ++ } + +- res &= can_reuse_kq_mask(self_kq_mask_mla, mctx->get_mla(), params.ubatch, params.cparams); +- res &= can_reuse_kq_mask(self_kq_mask_lid, mctx->get_lid(), params.ubatch, params.cparams); ++ if (self_kq_mask_mla && self_kq_mask_mla->buffer) { ++ res &= can_reuse_kq_mask(self_kq_mask_mla, mctx->get_mla(), params.ubatch, params.cparams); ++ } ++ if (self_kq_mask_lid && self_kq_mask_lid->buffer) { ++ res &= can_reuse_kq_mask(self_kq_mask_lid, mctx->get_lid(), params.ubatch, params.cparams); ++ } + + return res; + } +@@ -695,6 +790,8 @@ void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) { + mctx->get_swa()->set_input_kq_mask(self_kq_mask_swa, ubatch, cparams.causal_attn); + } + ++ set_row_inputs(*ubatch); ++ + if (self_k_rot && self_k_rot->buffer) { + mctx->get_base()->set_input_k_rot(self_k_rot); + } +@@ -713,30 +810,35 @@ void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) { + } + + bool llm_graph_input_attn_kv_iswa::can_reuse(const llm_graph_params & params) { +- const auto * mctx = static_cast(params.mctx); ++ return can_reuse_attn(static_cast(params.mctx), ++ params.ubatch, params.cparams); ++} + +- this->mctx = mctx; ++bool llm_graph_input_attn_kv_iswa::can_reuse_attn( ++ const llama_kv_cache_iswa_context * context, const llama_ubatch & ubatch, ++ const llama_cparams & params) { ++ mctx = context; + +- bool res = true; ++ bool res = can_reuse_row_inputs(ubatch, params); + + // base tensors may not be allocated if there are no non-SWA attention layers + if (self_k_idxs && self_k_idxs->buffer) { +- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; +- //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there ++ res &= self_k_idxs->ne[0] == ubatch.n_tokens; ++ //res &= self_v_idxs->ne[0] == ubatch.n_tokens; // TODO: need to move this to the unified cache and check there + } + + if (self_kq_mask && self_kq_mask->buffer) { +- res &= can_reuse_kq_mask(self_kq_mask, mctx->get_base(), params.ubatch, params.cparams); ++ res &= can_reuse_kq_mask(self_kq_mask, mctx->get_base(), ubatch, params); + } + + // swa tensors may not be allocated if there are no SWA attention layers + if (self_k_idxs_swa && self_k_idxs_swa->buffer) { +- res &= self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; +- //res &= self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there ++ res &= self_k_idxs_swa->ne[0] == ubatch.n_tokens; ++ //res &= self_v_idxs_swa->ne[0] == ubatch.n_tokens; // TODO: need to move this to the unified cache and check there + } + + if (self_kq_mask_swa && self_kq_mask_swa->buffer) { +- res &= can_reuse_kq_mask(self_kq_mask_swa, mctx->get_swa(), params.ubatch, params.cparams); ++ res &= can_reuse_kq_mask(self_kq_mask_swa, mctx->get_swa(), ubatch, params); + } + + return res; +@@ -1040,6 +1142,33 @@ static void dsv4_build_comp_inputs( + } + } + ++std::unique_ptr llm_graph_input_dsv4_create( ++ ggml_context * ctx, ++ const llama_hparams & hparams, ++ const llama_cparams & cparams, ++ const llama_ubatch & ubatch, ++ const llama_kv_cache_dsv4_context * mctx) { ++ const auto * raw_ctx = mctx->get_raw(); ++ auto inp_raw = std::make_unique(cparams, raw_ctx); ++ const int64_t n_stream = mctx->get_csa_plan(ubatch).n_stream; ++ ++ GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "DSV4 expects SWA raw cache"); ++ ++ inp_raw->self_k_idxs = raw_ctx->build_input_k_idxs(ctx, ubatch); ++ inp_raw->self_kq_mask = dsv4_build_raw_kq_mask(ctx, raw_ctx, ubatch, cparams, n_stream); ++ inp_raw->self_kq_mask_cnv = inp_raw->self_kq_mask; ++ inp_raw->self_k_rot = raw_ctx->build_input_k_rot(ctx); ++ ++ auto inp = std::make_unique(cparams, std::move(inp_raw), mctx); ++ dsv4_build_comp_inputs(ctx, inp->inp_csa, mctx->get_csa_plan(ubatch), "csa", cparams, n_stream); ++ dsv4_build_comp_inputs(ctx, inp->inp_hca, mctx->get_hca_plan(ubatch), "hca", cparams, n_stream); ++ dsv4_build_comp_inputs(ctx, inp->inp_lid, mctx->get_lid_plan(ubatch), "lid", cparams, n_stream); ++ inp->inp_csa.k_rot = mctx->get_csa()->build_input_k_rot(ctx); ++ inp->inp_hca.k_rot = mctx->get_hca()->build_input_k_rot(ctx); ++ inp->inp_lid.k_rot = mctx->get_lid()->build_input_k_rot(ctx); ++ return inp; ++} ++ + void llm_graph_input_dsv4_raw::set_input(const llama_ubatch * ubatch) { + if (self_k_idxs && self_k_idxs->buffer) { + mctx->set_input_k_idxs(self_k_idxs); +@@ -1147,22 +1276,12 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { + } + + void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { +- mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); +- mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); +- +- mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); +- +- if (inp_attn->self_k_rot) { +- mctx->get_attn()->set_input_k_rot(inp_attn->self_k_rot); +- } +- +- if (inp_attn->self_v_rot) { +- mctx->get_attn()->set_input_v_rot(inp_attn->self_v_rot); +- } ++ inp_attn->mctx = mctx->get_attn(); ++ inp_attn->set_input(ubatch); + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + +- if (inp_rs->s_copy) { ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + +@@ -1178,16 +1297,15 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { + + this->mctx = mctx; + +- bool res = true; ++ bool res = inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); + +- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; +- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there +- +- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); +- +- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { ++ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); ++ } + +- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; ++ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { ++ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; ++ } + + res &= inp_rs->head == mctx->get_recr()->get_head(); + res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); +@@ -1199,13 +1317,18 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { + // Instead of creating a hybrid input, the graph can simply create 2 separate inputs. + // Refactoring is required in the future. + void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { +- mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); ++ const auto * attn_ctx = mctx->get_attn(); + +- mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); ++ // These tensors may not be allocated for staged slices that contain only ++ // recurrent layers. ++ if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { ++ attn_ctx->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); ++ attn_ctx->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); ++ } + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + +- if (inp_rs->s_copy) { ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + +@@ -1223,62 +1346,35 @@ bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { + + bool res = true; + +- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; +- +- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); +- +- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); +- +- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; +- +- res &= inp_rs->head == mctx->get_recr()->get_head(); +- res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); +- +- return res; +-} +- +-void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { +- const auto * attn_ctx = mctx->get_attn(); +- +- // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { +- attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); +- attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); ++ res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; + } + + if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { +- attn_ctx->get_base()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); +- } +- +- // swa tensors may not be allocated if there are no SWA attention layers +- if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { +- attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); +- attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); ++ res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); + } + +- if (inp_attn->self_kq_mask_swa && inp_attn->self_kq_mask_swa->buffer) { +- attn_ctx->get_swa()->set_input_kq_mask(inp_attn->self_kq_mask_swa, ubatch, cparams.causal_attn); ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { ++ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); + } + +- if (inp_attn->self_k_rot) { +- attn_ctx->get_base()->set_input_k_rot(inp_attn->self_k_rot); ++ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { ++ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; + } + +- if (inp_attn->self_v_rot) { +- attn_ctx->get_base()->set_input_v_rot(inp_attn->self_v_rot); +- } ++ res &= inp_rs->head == mctx->get_recr()->get_head(); ++ res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + +- if (inp_attn->self_k_rot_swa) { +- attn_ctx->get_swa()->set_input_k_rot(inp_attn->self_k_rot_swa); +- } ++ return res; ++} + +- if (inp_attn->self_v_rot_swa) { +- attn_ctx->get_swa()->set_input_v_rot(inp_attn->self_v_rot_swa); +- } ++void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { ++ inp_attn->mctx = mctx->get_attn(); ++ inp_attn->set_input(ubatch); + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + +- if (inp_rs->s_copy) { ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + +@@ -1296,28 +1392,16 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) + + bool res = true; + +- const auto * attn_ctx = mctx->get_attn(); ++ res &= inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); + +- // base tensors may not be allocated if there are no non-SWA attention layers +- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { +- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; +- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there ++ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { ++ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); + } + +- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, attn_ctx->get_base(), params.ubatch, params.cparams); +- +- // swa tensors may not be allocated if there are no SWA attention layers +- if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { +- res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; +- //res &= inp_attn->self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there ++ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { ++ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; + } + +- res &= can_reuse_kq_mask(inp_attn->self_kq_mask_swa, attn_ctx->get_swa(), params.ubatch, params.cparams); +- +- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); +- +- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; +- + res &= inp_rs->head == mctx->get_recr()->get_head(); + res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + +@@ -1383,6 +1467,8 @@ void llm_graph_result::reset() { + t_embd = nullptr; + t_embd_pooled = nullptr; + t_h_nextn = nullptr; ++ activation_imports.clear(); ++ activation_exports.clear(); + + t_layer_inp.resize(LLAMA_MAX_LAYERS + 1); + std::fill(t_layer_inp.begin(), t_layer_inp.end(), nullptr); +@@ -1397,8 +1483,17 @@ void llm_graph_result::reset() { + inputs.clear(); + fused_nodes.clear(); + hdmd_inputs.clear(); +- +- buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false)); ++ block_boundaries.clear(); ++ state_effects.clear(); ++ input_choices.clear(); ++ build_inputs = {}; ++ request_input_bindings.clear(); ++ request_input_ordinals.clear(); ++ ++ // A filtered runtime first constructs the canonical whole-model graph and ++ // then materializes a second graph descriptor plus detached frontier ++ // leaves in this same metadata arena. ++ buf_compute_meta.resize(2*(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false))); + + ggml_init_params params = { + /*.mem_size =*/ buf_compute_meta.size(), +@@ -1411,17 +1506,92 @@ void llm_graph_result::reset() { + gf = ggml_new_graph_custom(ctx_compute.get(), max_nodes, false); + } + ++void llm_graph_result::set_inputs(const llama_ubatch * ubatch, const skippy_graph_build_inputs & build_inputs) { ++ this->build_inputs = build_inputs; ++ set_inputs(ubatch); ++} ++ + void llm_graph_result::set_inputs(const llama_ubatch * ubatch) { + for (auto & input : inputs) { ++ input->set_build_inputs(build_inputs); + input->set_input(ubatch); + } ++ GGML_ASSERT(build_inputs.activation_frontier.empty() || ++ build_inputs.activation_frontier.size() == activation_imports.size()); ++ for (size_t index = 0; index < build_inputs.activation_frontier.size(); ++index) { ++ const auto & source = build_inputs.activation_frontier[index]; ++ ggml_tensor * destination = activation_imports[index].tensor; ++ if (source.values == nullptr) { ++ GGML_ASSERT(activation_imports[index].optional); ++ continue; ++ } ++ GGML_ASSERT(destination != nullptr && destination->buffer != nullptr); ++ GGML_ASSERT(source.rank > 0 && source.rank <= GGML_MAX_DIMS && ++ source.token_axis >= 0 && source.token_axis < static_cast(source.rank)); ++ if (destination->type != static_cast(source.ggml_type)) { ++ throw std::runtime_error( ++ "activation frontier part type mismatch at index " + std::to_string(index) + ++ " binding=" + activation_imports[index].binding + ++ " destination=" + ggml_type_name(destination->type) + ++ " source=" + ggml_type_name(static_cast(source.ggml_type))); ++ } ++ for (uint32_t dimension = 0; dimension < source.rank; ++dimension) { ++ const int64_t expected = static_cast(dimension) == source.token_axis ? ++ ubatch->n_tokens : source.dimensions[dimension]; ++ GGML_ASSERT(destination->ne[dimension] == expected); ++ } ++ ++ size_t token_offset = 0; ++ if (!source.sequence_ids.empty() && ubatch->seq_id != nullptr && ubatch->seq_id[0] != nullptr) { ++ const llama_seq_id seq_id = ubatch->seq_id[0][0]; ++ const auto found = std::find(source.sequence_ids.begin(), source.sequence_ids.end(), seq_id); ++ GGML_ASSERT(found != source.sequence_ids.end()); ++ const size_t sequence_index = static_cast(found - source.sequence_ids.begin()); ++ token_offset = source.sequence_offsets[sequence_index]; ++ if (ubatch->pos != nullptr) { ++ GGML_ASSERT(ubatch->pos[0] >= source.sequence_pos_starts[sequence_index]); ++ token_offset += static_cast(ubatch->pos[0] - source.sequence_pos_starts[sequence_index]); ++ } ++ } else if (ubatch->pos != nullptr && source.dimensions[source.token_axis] > ubatch->n_tokens) { ++ GGML_ASSERT(ubatch->pos[0] >= source.pos_start); ++ token_offset = static_cast(ubatch->pos[0] - source.pos_start); ++ } ++ GGML_ASSERT(token_offset + static_cast(ubatch->n_tokens) <= ++ static_cast(source.dimensions[source.token_axis])); ++ const size_t inner_bytes = static_cast(source.byte_strides[source.token_axis]); ++ const size_t source_plane_bytes = inner_bytes * static_cast(source.dimensions[source.token_axis]); ++ const size_t destination_plane_bytes = inner_bytes * static_cast(ubatch->n_tokens); ++ GGML_ASSERT(source_plane_bytes > 0 && source.payload_bytes % source_plane_bytes == 0); ++ const size_t outer_count = static_cast(source.payload_bytes) / source_plane_bytes; ++ for (size_t outer = 0; outer < outer_count; ++outer) { ++ const size_t source_offset = outer * source_plane_bytes + token_offset * inner_bytes; ++ const size_t destination_offset = outer * destination_plane_bytes; ++ ggml_backend_tensor_set( ++ destination, ++ static_cast(source.values) + source_offset, ++ destination_offset, ++ destination_plane_bytes); ++ } ++ } + } + + void llm_graph_result::set_outputs(const llm_graph_params & params) { ++ const auto bind_ports = [](std::vector & ports, ++ const std::vector & expected) { ++ if (ports.empty() || ports.size() != expected.size()) return; ++ // Tensor names are local graph details and can collide with a different ++ // planner binding. Port registration order is the cross-build contract. ++ for (size_t index = 0; index < ports.size(); ++index) { ++ ports[index].binding = expected[index]; ++ } ++ }; ++ bind_ports(activation_imports, params.build_inputs.activation_import_bindings); ++ bind_ports(activation_exports, params.build_inputs.activation_export_bindings); + if (t_logits != nullptr) { + ggml_set_output(t_logits); + } + if (t_embd != nullptr) { ++ ggml_build_forward_expand(gf, t_embd); + ggml_set_output(t_embd); + } + if (t_embd_pooled != nullptr) { +@@ -1430,6 +1600,11 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { + if (t_h_nextn != nullptr) { + ggml_set_output(t_h_nextn); + } ++ for (const skippy_activation_port & port : activation_exports) { ++ if (port.tensor != nullptr) { ++ ggml_set_output(port.tensor); ++ } ++ } + { + const auto & embeddings_layer_inp = params.cparams.embeddings_layer_inp; + for (size_t il = 0; il < embeddings_layer_inp.size(); ++il) { +@@ -1461,6 +1636,74 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { + } + } + ++void llm_graph_result::add_skippy_activation_import( ++ ggml_tensor * tensor, int32_t token_axis, bool optional, bool token_axis_explicit) { ++ if (tensor == nullptr) return; ++ const auto found = std::find_if(activation_imports.begin(), activation_imports.end(), ++ [tensor](const skippy_activation_port & port) { return port.tensor == tensor; }); ++ if (found == activation_imports.end()) { ++ activation_imports.push_back({tensor, token_axis, optional, {}, token_axis_explicit}); ++ } ++} ++ ++void llm_graph_result::add_skippy_activation_export( ++ ggml_tensor * tensor, int32_t token_axis, bool optional, bool token_axis_explicit) { ++ if (tensor == nullptr) return; ++ const auto found = std::find_if(activation_exports.begin(), activation_exports.end(), ++ [tensor](const skippy_activation_port & port) { return port.tensor == tensor; }); ++ if (found == activation_exports.end()) { ++ activation_exports.push_back({tensor, token_axis, optional, {}, token_axis_explicit}); ++ } ++} ++ ++void llm_graph_result::add_skippy_input_choice( ++ const std::array & alternatives, ++ uint32_t selected) { ++ GGML_ASSERT(alternatives[0] != nullptr && alternatives[1] != nullptr && selected < alternatives.size()); ++ input_choices.push_back({alternatives, selected}); ++} ++ ++void llm_graph_result::replace_with_stage_graph( ++ ggml_cgraph * graph, ++ std::vector imports, ++ std::vector exports, ++ std::vector effects) { ++ GGML_ASSERT(graph != nullptr); ++ const auto retain_if_present = [graph](ggml_tensor *& tensor) { ++ if (tensor == nullptr) return; ++ for (int index = 0; index < ggml_graph_n_nodes(graph); ++index) { ++ if (ggml_graph_node(graph, index) == tensor) return; ++ } ++ tensor = nullptr; ++ }; ++ gf = graph; ++ state_effects = std::move(effects); ++ activation_imports = std::move(imports); ++ activation_exports = std::move(exports); ++ retain_if_present(t_logits); ++ retain_if_present(t_embd); ++ retain_if_present(t_embd_pooled); ++ retain_if_present(t_h_nextn); ++ for (auto *& tensor : t_layer_inp) retain_if_present(tensor); ++ for (auto *& tensor : t_sampled) retain_if_present(tensor); ++ for (auto *& tensor : t_sampled_probs) retain_if_present(tensor); ++ for (auto *& tensor : t_sampled_logits) retain_if_present(tensor); ++ for (auto *& tensor : t_candidates) retain_if_present(tensor); ++ ++ // resolve_fused_ops() compares the backend of every fused node with the ++ // device of its layer. Fused nodes of layers outside this stage are not in ++ // the stage graph, so the scheduler never assigns them a backend and they ++ // would read as a device mismatch. Keep only the nodes this stage computes. ++ std::unordered_set stage_nodes; ++ for (int index = 0; index < ggml_graph_n_nodes(graph); ++index) { ++ stage_nodes.insert(ggml_graph_node(graph, index)); ++ } ++ fused_nodes.erase(std::remove_if(fused_nodes.begin(), fused_nodes.end(), ++ [&stage_nodes](const llm_graph_fused_node & node) { ++ return stage_nodes.count(node.tensor) == 0; ++ }), fused_nodes.end()); ++} ++ + bool llm_graph_result::can_reuse(const llm_graph_params & params) { + if (!this->params.allow_reuse(params)) { + if (debug > 1) { +@@ -1494,6 +1737,42 @@ bool llm_graph_result::can_reuse(const llm_graph_params & params) { + } + + llm_graph_input_i * llm_graph_result::add_input(llm_graph_input_ptr input) { ++ const auto request_input = [&](ggml_tensor * tensor, const char * identity) { ++ if (tensor == nullptr) { ++ return; ++ } ++ const auto existing = std::find_if(request_input_bindings.begin(), request_input_bindings.end(), ++ [tensor](const skippy_request_input_binding & binding) { ++ return binding.tensor == tensor; ++ }); ++ if (existing == request_input_bindings.end()) { ++ const uint32_t ordinal = request_input_ordinals[identity]++; ++ request_input_bindings.push_back( ++ {tensor, std::string(identity) + "." + std::to_string(ordinal)}); ++ } ++ }; ++ ++ // Some family builders create generic input bundles directly instead of ++ // going through build_inp_embd(). Register those request leaves here so ++ // every graph exposes the same semantic input contract to stage planning. ++ // A mode the builder does not offer stays out of the advertised embeddings ++ // channel while its leaves keep the semantic graph complete. ++ if (auto * embd = dynamic_cast(input.get())) { ++ request_input(embd->tokens, "tokens"); ++ request_input(embd->embd, embd->allow_embeddings ? "embeddings" : "unavailable.embeddings"); ++ // The mixed batch carries only the token rows it names, with the ++ // remaining rows supplied as raw embeddings, so it owns its own leaves. ++ request_input(embd->mixed_tokens, "tokens.mixed"); ++ request_input(embd->mixed_slots, "tokens.mixed.slots"); ++ request_input(embd->mixed_embd, ++ embd->allow_embeddings ? "embeddings.mixed" : "unavailable.embeddings.mixed"); ++ request_input(embd->scale_rows, "scale.rows"); ++ } ++ if (auto * mtp = dynamic_cast(input.get())) { ++ request_input(mtp->tokens, "tokens"); ++ request_input(mtp->embd, "embeddings"); ++ request_input(mtp->h, "mtp.hidden"); ++ } + inputs.emplace_back(std::move(input)); + return inputs.back().get(); + } +@@ -1513,6 +1792,7 @@ void llm_graph_result::set_hdmd_input(const ggml_tensor * cur, const ggml_tensor + + void llm_graph_result::set_params(const llm_graph_params & params) { + this->params = params; ++ build_inputs = params.build_inputs; + } + + // +@@ -1561,6 +1841,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : + hdmd (params.hdmd), + samplers (params.samplers), + cb_func (params.cb), ++ build_inputs (params.build_inputs), + res (params.res), + ctx0 (res->get_ctx()), + gf (res->get_gf()) { +@@ -1573,7 +1854,143 @@ void llm_graph_context::cb(ggml_tensor * cur, const char * name, int il) const { + } + } + ++void llm_graph_context::begin_block(ggml_tensor * cur, int il) const { ++ res->block_boundaries.push_back({skippy_block_boundary_kind::entry, il, cur}); ++} ++ ++void llm_graph_context::end_block(ggml_tensor * cur, int il) const { ++ // Expand eagerly so block boundary positions partition the executable ++ // graph: lazy expansion lets independent nodes from later blocks be ++ // appended before an earlier block's exit tensor. ++ ggml_build_forward_expand(gf, cur); ++ res->block_boundaries.push_back({skippy_block_boundary_kind::exit, il, cur}); ++} ++ ++void llm_graph_context::state_read(skippy_state_kind kind, ggml_tensor * storage, int il) const { ++ res->state_effects.push_back({kind, skippy_state_access::read, ++ il, skippy_state_canonical_storage(storage), nullptr, -1, ++ il >= n_layer ? skippy_state_residency::per_stage : skippy_state_residency::layer_local}); ++} ++ ++void llm_graph_context::state_write(skippy_state_kind kind, ggml_tensor * storage, ggml_tensor * effect_node, int il) const { ++ const ggml_tensor * canonical = skippy_state_canonical_storage(storage); ++ int64_t ordinal = 0; ++ for (const auto & effect : res->state_effects) { ++ if (effect.access == skippy_state_access::write && effect.kind == kind && ++ effect.layer == il && effect.storage == canonical) { ++ ++ordinal; ++ } ++ } ++ res->state_effects.push_back({kind, skippy_state_access::write, il, canonical, effect_node, ordinal, ++ il >= n_layer ? skippy_state_residency::per_stage : skippy_state_residency::layer_local}); ++} ++ ++void llm_graph_context::request_input(ggml_tensor * tensor, const char * identity) const { ++ if (tensor != nullptr) { ++ const uint32_t ordinal = res->request_input_ordinals[identity]++; ++ res->request_input_bindings.push_back({tensor, std::string(identity) + "." + std::to_string(ordinal)}); ++ } ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_no_cache * input) const { ++ request_input(input->self_kq_mask, "attention.mask"); ++ request_input(input->self_kq_mask_swa, "attention.swa.mask"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_kv * input) const { ++ request_input(input->self_k_idxs, "attention.key_indices"); ++ request_input(input->self_v_idxs, "attention.value_indices"); ++ request_input(input->self_kq_mask, "attention.mask"); ++ request_input(input->self_kv_rows, "attention.kv_rows"); ++ request_input(input->self_read_mask, "attention.read_mask"); ++ request_input(input->self_k_rot, "attention.key_rotation"); ++ request_input(input->self_v_rot, "attention.value_rotation"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_k * input) const { ++ request_input(input->self_k_idxs, "attention.key_indices"); ++ request_input(input->self_kq_mask, "attention.mask"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_kv_iswa * input) const { ++ request_input(input->self_k_idxs, "attention.base.key_indices"); ++ request_input(input->self_v_idxs, "attention.base.value_indices"); ++ request_input(input->self_kq_mask, "attention.base.mask"); ++ request_input(input->self_kv_rows, "attention.base.read_rows"); ++ request_input(input->self_read_mask, "attention.base.read_mask"); ++ request_input(input->self_k_rot, "attention.base.key_rotation"); ++ request_input(input->self_v_rot, "attention.base.value_rotation"); ++ request_input(input->self_k_idxs_swa, "attention.swa.key_indices"); ++ request_input(input->self_v_idxs_swa, "attention.swa.value_indices"); ++ request_input(input->self_kq_mask_swa, "attention.swa.mask"); ++ request_input(input->self_kv_rows_swa, "attention.swa.read_rows"); ++ request_input(input->self_read_mask_swa, "attention.swa.read_mask"); ++ request_input(input->self_k_rot_swa, "attention.swa.key_rotation"); ++ request_input(input->self_v_rot_swa, "attention.swa.value_rotation"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_k_iswa * input) const { ++ request_input(input->self_k_idxs, "attention.base.key_indices"); ++ request_input(input->self_kq_mask, "attention.base.mask"); ++ request_input(input->self_k_rot, "attention.base.key_rotation"); ++ request_input(input->self_k_idxs_swa, "attention.swa.key_indices"); ++ request_input(input->self_kq_mask_swa, "attention.swa.mask"); ++ request_input(input->self_k_rot_swa, "attention.swa.key_rotation"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_k_dsa * input) const { ++ request_input(input->self_k_idxs_mla, "attention.dsa.mla.key_indices"); ++ request_input(input->self_k_idxs_lid, "attention.dsa.indexer.key_indices"); ++ request_input(input->self_kq_mask_mla, "attention.dsa.mla.mask"); ++ request_input(input->self_kq_mask_lid, "attention.dsa.indexer.mask"); ++ request_input(input->self_k_rot_lid, "attention.dsa.indexer.key_rotation"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_k_dsa_iswa * input) const { ++ request_inputs(input->get_dsa()); ++ request_input(input->get_swa()->self_k_idxs, "attention.swa.key_indices"); ++ request_input(input->get_swa()->self_kq_mask, "attention.swa.mask"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_attn_kv_msa * input) const { ++ request_inputs(static_cast(input)); ++ request_input(input->self_k_idxs_idx, "attention.msa.indexer.key_indices"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_mem_hybrid_iswa * input) const { ++ request_inputs(input->get_attn()); ++ request_inputs(input->get_recr()); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_rs * input) const { ++ request_input(input->s_copy, "recurrent.copy_indices"); ++} ++ ++void llm_graph_context::request_inputs(llm_graph_input_dsv4 * input) const { ++ const auto register_comp = [&](const llm_graph_input_dsv4::comp_input & comp, const char * plane) { ++ const std::string prefix = std::string("dsv4.") + plane + "."; ++ request_input(comp.state_pos, (prefix + "state_positions").c_str()); ++ request_input(comp.state_persist_src_idxs, (prefix + "persist_source_indices").c_str()); ++ request_input(comp.state_persist_dst_idxs, (prefix + "persist_destination_indices").c_str()); ++ request_input(comp.state_restore_src_idxs, (prefix + "restore_source_indices").c_str()); ++ request_input(comp.state_restore_dst_idxs, (prefix + "restore_destination_indices").c_str()); ++ request_input(comp.state_snapshot_src_idxs, (prefix + "snapshot_source_indices").c_str()); ++ request_input(comp.state_snapshot_dst_idxs, (prefix + "snapshot_destination_indices").c_str()); ++ request_input(comp.state_read_idxs, (prefix + "read_indices").c_str()); ++ request_input(comp.state_write_idxs, (prefix + "write_indices").c_str()); ++ request_input(comp.state_write_pos, (prefix + "write_positions").c_str()); ++ request_input(comp.kq_mask, (prefix + "attention_mask").c_str()); ++ request_input(comp.k_rot, (prefix + "key_rotation").c_str()); ++ }; + ++ auto * raw = input->get_raw(); ++ request_input(raw->self_k_idxs, "dsv4.raw.key_indices"); ++ request_input(raw->self_kq_mask, "dsv4.raw.attention_mask"); ++ request_input(raw->self_k_rot, "dsv4.raw.key_rotation"); ++ register_comp(input->get_csa(), "csa"); ++ register_comp(input->get_hca(), "hca"); ++ register_comp(input->get_lid(), "lid"); ++} + + ggml_tensor * llm_graph_context::build_cvec( + ggml_tensor * cur, +@@ -1615,7 +2032,8 @@ ggml_tensor * llm_graph_context::build_hadamard_input( + ggml_tensor * llm_graph_context::build_lora_mm( + ggml_tensor * w, + ggml_tensor * cur, +- ggml_tensor * w_s) const { ++ ggml_tensor * w_s, ++ enum ggml_prec prec) const { + cur = build_hadamard_input(w, cur); + ggml_tensor * res = ggml_mul_mat(ctx0, w, cur); + +@@ -1627,6 +2045,11 @@ ggml_tensor * llm_graph_context::build_lora_mm( + ggml_prec_set_acc(res, GGML_PREC_BF16); + } + ++ if (prec != GGML_PREC_DEFAULT) { ++ // Set precision on the base MUL_MAT before an optional scale/LoRA attachment changes the root op. ++ ggml_prec_set_acc(res, prec); ++ } ++ + if (w_s) { + res = ggml_mul(ctx0, res, w_s); + } +@@ -2145,6 +2568,10 @@ ggml_tensor * llm_graph_context::build_moe_ffn( + ggml_tensor * selected_experts_in) const { + const int64_t n_embd = cur->ne[0]; + const int64_t n_tokens = cur->ne[1]; ++ const auto top_k = [&](ggml_tensor * value, int64_t k) { ++ auto * result = ggml_argsort_top_k(ctx0, value, k); ++ return result; ++ }; + const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4; // for llama4, we apply the sigmoid-ed weights before the FFN + + ggml_tensor * logits = nullptr; +@@ -2214,14 +2641,14 @@ ggml_tensor * llm_graph_context::build_moe_ffn( + // organize experts into n_expert_groups + ggml_tensor * selection_groups = ggml_reshape_3d(ctx0, selection_probs, n_exp_per_group, hparams.n_expert_groups, n_tokens); // [n_exp_per_group, n_expert_groups, n_tokens] + +- ggml_tensor * group_scores = ggml_argsort_top_k(ctx0, selection_groups, 2); // [2, n_expert_groups, n_tokens] ++ ggml_tensor * group_scores = top_k(selection_groups, 2); // [2, n_expert_groups, n_tokens] + group_scores = ggml_get_rows(ctx0, ggml_reshape_4d(ctx0, selection_groups, 1, selection_groups->ne[0], selection_groups->ne[1], selection_groups->ne[2]), group_scores); // [1, 2, n_expert_groups, n_tokens] + + // get top n_group_used expert groups + group_scores = ggml_sum_rows(ctx0, ggml_reshape_3d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2], group_scores->ne[3])); // [1, n_expert_groups, n_tokens] + group_scores = ggml_reshape_2d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2]); // [n_expert_groups, n_tokens] + +- ggml_tensor * expert_groups = ggml_argsort_top_k(ctx0, group_scores, hparams.n_group_used); // [n_group_used, n_tokens] ++ ggml_tensor * expert_groups = top_k(group_scores, hparams.n_group_used); // [n_group_used, n_tokens] + cb(expert_groups, "ffn_moe_group_topk", il); + + // mask out the other groups +@@ -2234,7 +2661,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( + // select experts + ggml_tensor * selected_experts = selected_experts_in; + if (selected_experts == nullptr) { +- selected_experts = ggml_argsort_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens] ++ selected_experts = top_k(selection_probs, n_expert_used); // [n_expert_used, n_tokens] + cb(selected_experts->src[0], "ffn_moe_argsort", il); + } + cb(selected_experts, "ffn_moe_topk", il); +@@ -2467,6 +2894,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( + for (uint32_t i = 0; i < n_expert_used_il; ++i) { + cur_experts[i] = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]); + ++ + ggml_build_forward_expand(gf, cur_experts[i]); + } + +@@ -2531,14 +2959,30 @@ ggml_tensor * llm_graph_context::build_moe_cache_slots( + return ggml_reshape_2d(ctx0, slots, selected_experts->ne[0], selected_experts->ne[1]); // [n_expert_used, n_tokens] + } + ++// Deepstack models embed text and multimodal rows in the same graph, and only ++// the token rows carry the Granite embedding scale. Keep the decision in one ++// place so the stage planner sees the same input contract the graph executes. ++static bool scale_embedding_input(uint32_t input_mode, uint32_t n_deepstack_layers) { ++ return input_mode == 0 || n_deepstack_layers == 0; ++} ++ ++#ifdef LLAMA_STAGE_BUILD_TESTS ++bool skippy_scale_embedding_input_for_test(uint32_t input_mode, uint32_t n_deepstack_layers) { ++ return scale_embedding_input(input_mode, n_deepstack_layers); ++} ++#endif ++ + // input embeddings with optional lora +-ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float tok_scale) const { ++ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float tok_scale, bool allow_embeddings) const { ++ if (ubatch.embd && !allow_embeddings) { ++ GGML_ABORT("This GGUF does not support multimodal. Please reconvert it."); ++ } + const int64_t n_embd_inp = hparams.n_embd_inp(); + const int64_t n_embd = hparams.n_embd; + + assert(n_embd_inp >= n_embd); + +- auto inp = std::make_unique(n_embd_inp); ++ auto inp = std::make_unique(n_embd_inp, allow_embeddings); + + // mixed path (ubatch.is_mixed()): set_rows the token rows into a copy of the embd rows, with its own inputs as select branches must not share tensors + // TODO: use inp->tokens and inp->embd once ggml_build_forward_select allows it +@@ -2559,11 +3003,17 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to + inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens); + cb(inp->tokens, "inp_tokens", -1); + ggml_set_input(inp->tokens); ++ request_input(inp->tokens, "tokens"); + res->t_inp_tokens = inp->tokens; + + inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd_inp, ubatch.n_tokens); + cb(inp->embd, "inp_embd", -1); + ggml_set_input(inp->embd); ++ // Advertise only input modes this graph can execute. Planning uses these ++ // declarations to discover additional profiles without probing invalid modes. ++ if (allow_embeddings) { ++ request_input(inp->embd, "embeddings"); ++ } + + if (has_mixed) { + inp->mixed_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tok_rows); +@@ -2658,6 +3108,12 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to + + const int idx = ubatch.is_mixed() ? 2 : ubatch.token ? 0 : 1; + ++ // the non-mixed graph executes exactly the token and the raw-embedding mode ++ if (!has_mixed) { ++ const std::array alternatives = { inps[0], inps[1] }; ++ res->add_skippy_input_choice(alternatives, (uint32_t) idx); ++ } ++ + ggml_tensor * cur = ggml_build_forward_select(gf, inps.data(), has_mixed ? 3 : 2, idx); + + if (n_embd_inp != n_embd) { +@@ -2668,7 +3124,7 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to + + // NOTE: For deepstack models, only apply scale to token inputs (ie text-only input). + // Raw embeddings are assumed to be multimodal inputs that should not be scaled. +- const bool scale_tok_only = hparams.f_embedding_scale != 0.0f && hparams.n_deepstack_layers > 0; ++ const bool scale_tok_only = hparams.f_embedding_scale != 0.0f && !scale_embedding_input(1, hparams.n_deepstack_layers); + + // For Granite architecture + if (hparams.f_embedding_scale != 0.0f && !scale_tok_only) { +@@ -2710,6 +3166,7 @@ ggml_tensor * llm_graph_context::build_inp_pos() const { + cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t)n_tokens*hparams.n_pos_per_embd()); + ggml_set_input(cur); + cb(cur, "inp_pos", -1); ++ request_input(cur, "positions"); + + res->add_input(std::move(inp)); + +@@ -2725,6 +3182,7 @@ ggml_tensor * llm_graph_context::build_inp_attn_scale() const { + cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens); + ggml_set_input(cur); + cb(cur, "inp_attn_scale", -1); ++ request_input(cur, "attention.scale"); + + res->add_input(std::move(inp)); + +@@ -2747,6 +3205,7 @@ ggml_tensor * llm_graph_context::build_inp_out_ids() const { + cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs); + ggml_set_input(cur); + ggml_set_name(cur, "out_ids"); ++ request_input(cur, "output.indices"); + + res->add_input(std::move(inp)); + +@@ -2761,6 +3220,7 @@ ggml_tensor * llm_graph_context::build_inp_mean() const { + cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq); + ggml_set_input(cur); + ggml_set_name(cur, "mean"); ++ request_input(cur, "pooling.mean"); + + res->add_input(std::move(inp)); + +@@ -2775,6 +3235,7 @@ ggml_tensor * llm_graph_context::build_inp_cls() const { + cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq); + ggml_set_input(cur); + ggml_set_name(cur, "cls"); ++ request_input(cur, "pooling.indices"); + + res->add_input(std::move(inp)); + +@@ -2863,11 +3324,16 @@ ggml_tensor * llm_graph_context::build_attn_mha( + ggml_tensor * v_mla, + int64_t n_kv_max, + float kq_scale, +- int il) const { ++ int il, ++ ggml_tensor * kv_rows, ++ ggml_tensor * dense_mask) const { ++ ggml_tensor * original_q = q; ++ ggml_tensor * original_k = k; ++ ggml_tensor * original_v = v; + const bool v_trans = v->nb[1] > v->nb[2]; + + // split the batch into streams if needed +- const auto n_stream = k->ne[3]; ++ const auto n_stream = kv_rows ? kv_rows->ne[1] : k->ne[3]; + + // the stream dim steps over one stream's worth of dim-2 (tokens): (ne[2]/n_stream) rows of stride nb[2]. + // q->nb[3]/n_stream only equals that for a contiguous q; nope-only MLA (glm5-next) passes a permuted +@@ -2888,7 +3354,31 @@ ggml_tensor * llm_graph_context::build_attn_mha( + v = ggml_transpose(ctx0, v); + } + ++ const float softcap = hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f; ++ const auto configure_attention = [&](ggml_tensor * node) { ++ ggml_flash_attn_ext_add_sinks(node, sinks); ++ GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); ++ ggml_flash_attn_ext_set_n_kv_max(node, static_cast(n_kv_max)); ++ ggml_prec_set_acc(node, GGML_PREC_F32); ++ }; ++ if (kv_rows) { ++ // Query capability with the original stored types BEFORE adding ++ // any full-pool F32 conversion. This metadata node is not expanded ++ // if the device keeps this storage on ordinary attention. ++ cur = ggml_flash_attn_ext_rows(ctx0, q, k, v, fa_mask, kv_rows, ++ kq_scale, hparams.f_max_alibi_bias, softcap); ++ configure_attention(cur); ++ if (!supports_row_attn(cur, original_k)) { ++ GGML_ASSERT(dense_mask); ++ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, ++ sinks, v_mla, n_kv_max, kq_scale, il); ++ } ++ } ++ + // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) ++ // Supported F32 row paths retain ordinary FA's whole-pool conversion; ++ // row selection does not make that conversion proportional to live KV. ++ const bool convert_f32 = k->type == GGML_TYPE_F32 || v->type == GGML_TYPE_F32; + if (k->type == GGML_TYPE_F32) { + k = ggml_cast(ctx0, k, GGML_TYPE_F16); + } +@@ -2897,14 +3387,21 @@ ggml_tensor * llm_graph_context::build_attn_mha( + v = ggml_cast(ctx0, v, GGML_TYPE_F16); + } + +- cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias, +- hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); +- res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); +- +- ggml_flash_attn_ext_add_sinks(cur, sinks); +- GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); +- ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); +- ggml_prec_set_acc(cur, GGML_PREC_F32); ++ if (!kv_rows || convert_f32) { ++ cur = kv_rows ? ggml_flash_attn_ext_rows(ctx0, q, k, v, fa_mask, ++ kv_rows, kq_scale, hparams.f_max_alibi_bias, softcap) : ++ ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, ++ kq_scale, hparams.f_max_alibi_bias, softcap); ++ configure_attention(cur); ++ } ++ if (kv_rows && !supports_row_attn(cur, original_k)) { ++ // Keep unsupported devices and K/V types on their existing native ++ // attention path, rather than copying the shared pool to the CPU. ++ GGML_ASSERT(dense_mask); ++ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, ++ sinks, v_mla, n_kv_max, kq_scale, il); ++ } ++ res->add_fused_node({kv_rows ? LLM_FUSED_OP_FLASH_ATTN_KV_ROWS : LLM_FUSED_OP_FLASH_ATTN, cur, il}); + + if (v_mla) { + #if 0 +@@ -3019,6 +3516,8 @@ llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache() con + inp->self_kq_mask_swa_cnv = nullptr; + } + ++ request_inputs(inp.get()); ++ + return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp)); + } + +@@ -3103,6 +3602,8 @@ static std::unique_ptr build_attn_inp_kv_impl( + inp->self_kq_mask_cnv = inp->self_kq_mask; + } + ++ inp->build_row_inputs(ctx0, ubatch); ++ + inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); + inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); + +@@ -3113,6 +3614,7 @@ llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv() const { + const auto * mctx_cur = static_cast(mctx); + + auto inp = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur); ++ request_inputs(inp.get()); + + return (llm_graph_input_attn_kv *) res->add_input(std::move(inp)); + } +@@ -3164,17 +3666,30 @@ ggml_tensor * llm_graph_context::build_attn( + const auto & k_idxs = inp->get_k_idxs(); + const auto & v_idxs = inp->get_v_idxs(); + +- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); +- ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); ++ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); ++ ggml_tensor * v_write = mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il); ++ ++ ggml_build_forward_expand(gf, k_write); ++ ggml_build_forward_expand(gf, v_write); ++ ++ state_write(skippy_state_kind::kv_key, k_write, k_write, il); ++ state_write(skippy_state_kind::kv_value, v_write, v_write, il); + } + + k = mctx_cur->get_k(ctx0, il); + v = mctx_cur->get_v(ctx0, il); ++ ++ state_read(skippy_state_kind::kv_key, k, il); ++ state_read(skippy_state_kind::kv_value, v, il); + } + + ggml_tensor * kq_mask = inp->get_kq_mask(); + +- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); ++ // Bias-producing builders retain their existing dense mask and semantics. ++ const bool rows = inp->self_kv_rows != nullptr && kq_b == nullptr && v_mla == nullptr; ++ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, ++ rows ? inp->self_read_mask : kq_mask, sinks, v_mla, 0, kq_scale, il, ++ rows ? inp->self_kv_rows : nullptr, kq_mask); + cb(cur, "kqv_out", il); + + if (inp->self_v_rot) { +@@ -3226,6 +3741,7 @@ llm_graph_input_attn_k * llm_graph_context::build_attn_inp_k() const { + const auto * mctx_cur = static_cast(mctx); + + auto inp = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur); ++ request_inputs(inp.get()); + + return (llm_graph_input_attn_k *) res->add_input(std::move(inp)); + } +@@ -3256,7 +3772,9 @@ ggml_tensor * llm_graph_context::build_attn( + { + const auto & k_idxs = inp->get_k_idxs(); + +- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); ++ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); ++ ggml_build_forward_expand(gf, k_write); ++ state_write(skippy_state_kind::kv_key, k_write, k_write, il); + } + + const auto & kq_mask = inp->get_kq_mask(); +@@ -3265,6 +3783,8 @@ ggml_tensor * llm_graph_context::build_attn( + ggml_tensor * k = mctx_cur->get_k(ctx0, il); + ggml_tensor * v = ggml_view_4d(ctx0, k, v_cur->ne[0], k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); + ++ state_read(skippy_state_kind::kv_key, k, il); ++ + ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); + cb(cur, "kqv_out", il); + +@@ -3320,6 +3840,8 @@ ggml_tensor * llm_graph_context::build_attn( + + const auto & kq_mask = inp->get_kq_mask_mla(); + ++ GGML_ASSERT(top_k != nullptr); ++ + // prepare new kq mask - starts filled with -INFINITY + ggml_tensor * kq_mask_all = ggml_fill(ctx0, kq_mask, -INFINITY); + +@@ -3422,13 +3944,17 @@ ggml_tensor * llm_graph_context::build_attn( + if (store_kv && k_cur) { + const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); + +- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); ++ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); ++ ggml_build_forward_expand(gf, k_write); ++ state_write(skippy_state_kind::kv_key, k_write, k_write, il); + } + + if (store_kv && v_cur) { + const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); -@@ -69,6 +99,7 @@ struct llama_context { - uint32_t n_ctx_seq() const; - uint32_t n_batch() const; - uint32_t n_ubatch() const; -+ bool kv_unified() const; - uint32_t n_seq_max() const; +- ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); ++ ggml_tensor * v_write = mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il); ++ ggml_build_forward_expand(gf, v_write); ++ state_write(skippy_state_kind::kv_value, v_write, v_write, il); + } - uint32_t n_threads() const; -@@ -78,6 +109,7 @@ struct llama_context { + const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); +@@ -3437,7 +3963,14 @@ ggml_tensor * llm_graph_context::build_attn( + ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); + ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); + +- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); ++ state_read(skippy_state_kind::kv_key, k, il); ++ state_read(skippy_state_kind::kv_value, v, il); ++ ++ ggml_tensor * kv_rows = is_swa ? inp->self_kv_rows_swa : inp->self_kv_rows; ++ ggml_tensor * read_mask = is_swa ? inp->self_read_mask_swa : inp->self_read_mask; ++ const bool rows = kv_rows && !use_kv_cur && !kq_b && !v_mla; ++ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, rows ? read_mask : kq_mask, ++ sinks, v_mla, 0, kq_scale, il, rows ? kv_rows : nullptr, kq_mask); + cb(cur, "kqv_out", il); + + if (v_rot) { +@@ -3498,7 +4031,9 @@ ggml_tensor * llm_graph_context::build_attn( + if (k_cur) { + const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); + +- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); ++ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); ++ ggml_build_forward_expand(gf, k_write); ++ state_write(skippy_state_kind::kv_key, k_write, k_write, il); + } - // return true if the memory was updated - bool memory_update(bool optimize); -+ bool memory_update(bool optimize, const skippy_graph_build_inputs & graph_build_inputs); + const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); +@@ -3508,6 +4043,8 @@ ggml_tensor * llm_graph_context::build_attn( + ggml_tensor * k = mctx_cur->get_k(ctx0, il); + ggml_tensor * v = ggml_view_4d(ctx0, k, v_cur->ne[0], k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); - enum llama_pooling_type pooling_type() const; ++ state_read(skippy_state_kind::kv_key, k, il); ++ + ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); + cb(cur, "kqv_out", il); -@@ -149,14 +181,19 @@ struct llama_context { - const llama_ubatch & ubatch, - llm_graph_type gtype, - llama_memory_context_i * mctx, -- ggml_status & ret); -+ ggml_status & ret, -+ const skippy_graph_build_inputs & graph_build_inputs = {}); +@@ -3622,6 +4159,8 @@ llm_graph_input_attn_k_dsa * llm_graph_context::build_attn_inp_k_dsa() const { - int encode(const llama_batch_ext & batch_inp); -+ int encode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - int decode(const llama_batch_ext & batch_inp); -+ int decode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + auto inp = build_attn_inp_k_dsa_impl(ctx0, ubatch, hparams, cparams, mctx_cur); - // compat version - int encode(const llama_batch & batch_inp); -+ int encode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - int decode(const llama_batch & batch_inp); -+ int decode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); ++ request_inputs(inp.get()); ++ + return (llm_graph_input_attn_k_dsa *) res->add_input(std::move(inp)); + } - // - // state save/load -@@ -263,13 +300,34 @@ public: +@@ -3639,6 +4178,7 @@ llm_graph_input_attn_k_dsa_iswa * llm_graph_context::build_attn_inp_k_dsa_iswa() + inp_swa->self_kq_mask_cnv = inp_swa->self_kq_mask; - // can reuse the llm_graph_result instance of the context (for example to update a memory module) - llm_graph_result * get_gf_res_reserve() const; -+ uint32_t admit_skippy_cache_capabilities(uint32_t memory_capabilities) { -+ if (!skippy_cache_admission_bound) { -+ skippy_cache_admitted_capabilities = skippy_cache_profile_seen -+ ? skippy_cache_capabilities & memory_capabilities : 0; -+ skippy_cache_admission_bound = true; -+ } -+ return skippy_cache_admitted_capabilities; -+ } -+ // live graph result of the most recent schedule, or null before the first build -+ llm_graph_result * get_gf_res_prev_active() const; + auto inp = std::make_unique(std::move(inp_dsa), std::move(inp_swa), mctx_cur); ++ request_inputs(inp.get()); - // returns the result of ggml_backend_sched_graph_compute_async execution - ggml_status graph_compute(ggml_cgraph * gf, bool batched); + return (llm_graph_input_attn_k_dsa_iswa *) res->add_input(std::move(inp)); + } +@@ -3668,6 +4208,8 @@ llm_graph_input_attn_kv_msa * llm_graph_context::build_attn_inp_kv_msa(bool msa_ + inp->self_k_idxs_idx = mctx_idx->build_input_k_idxs(ctx0, ubatch); + } - // reserve a graph with a dummy ubatch of the specified size -- ggml_cgraph * graph_reserve( -- uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only = false, size_t * sizes = nullptr); -+ ggml_cgraph * graph_reserve(uint32_t n_tokens, -+ uint32_t n_seqs, -+ uint32_t n_outputs, -+ const llama_memory_context_i * mctx, -+ bool split_only = false, -+ size_t * sizes = nullptr, -+ const skippy_graph_build_inputs & graph_build_inputs = {}, -+ bool embedding_input = false); ++ request_inputs(inp.get()); + -+ bool get_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; -+ bool get_input_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; -+ bool get_activation_frontier(std::vector & parts) const; -+ bool get_input_activation_frontier(std::vector & parts) const; + return (llm_graph_input_attn_kv_msa *) res->add_input(std::move(inp)); + } - bool set_sampler(llama_seq_id seq_id, llama_sampler * sampler); +@@ -3697,12 +4239,16 @@ llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const + inp->self_kq_mask_swa_cnv = inp->self_kq_mask_swa; + } -@@ -280,7 +338,8 @@ private: - llm_graph_result * res, - const llama_ubatch & ubatch, - const llama_memory_context_i * mctx, -- llm_graph_type gtype) const; -+ llm_graph_type gtype, -+ const skippy_graph_build_inputs & graph_build_inputs = {}) const; ++ inp->build_row_inputs(ctx0, ubatch); ++ + inp->self_k_rot = mctx_cur->get_base()->build_input_k_rot(ctx0); + inp->self_v_rot = mctx_cur->get_base()->build_input_v_rot(ctx0); - llm_graph_cb graph_get_cb() const; + inp->self_k_rot_swa = mctx_cur->get_swa()->build_input_k_rot(ctx0); + inp->self_v_rot_swa = mctx_cur->get_swa()->build_input_v_rot(ctx0); -@@ -295,7 +354,10 @@ private: ++ request_inputs(inp.get()); ++ + return (llm_graph_input_attn_kv_iswa *) res->add_input(std::move(inp)); + } - // disable auto fused ops (Flash Attention, Gated Delta Net) whose op lands on a device - // that differs from the layer it belongs to (usually due to missing backend support) -- void resolve_fused_ops(const llama_memory_context_i * mctx, uint32_t n_seqs); -+ void resolve_fused_ops( -+ const llama_memory_context_i * mctx, -+ uint32_t n_seqs, -+ const skippy_graph_build_inputs & graph_build_inputs); +@@ -3731,32 +4277,16 @@ llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa() const { - // TODO: read/write lora adapters and cvec - size_t state_write_data(llama_io_write_i & io); -@@ -312,6 +374,10 @@ private: + inp->self_k_rot_swa = mctx_cur->get_swa()->build_input_k_rot(ctx0); - llama_cparams cparams; ++ request_inputs(inp.get()); ++ + return (llm_graph_input_attn_k_iswa *) res->add_input(std::move(inp)); + } -+ const skippy_graph_build_inputs graph_build_inputs; -+ uint64_t computation_generation = 0; + llm_graph_input_dsv4 * llm_graph_context::build_inp_dsv4() const { + const auto * mctx_cur = static_cast(mctx); +- const auto * raw_ctx = mctx_cur->get_raw(); +- +- auto inp_raw = std::make_unique(cparams, raw_ctx); ++ auto inp = llm_graph_input_dsv4_create(ctx0, hparams, cparams, ubatch, mctx_cur); + +- const int64_t n_stream = mctx_cur->get_csa_plan(ubatch).n_stream; +- +- GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "DSV4 expects SWA raw cache"); +- +- inp_raw->self_k_idxs = raw_ctx->build_input_k_idxs(ctx0, ubatch); +- inp_raw->self_kq_mask = dsv4_build_raw_kq_mask(ctx0, raw_ctx, ubatch, cparams, n_stream); +- inp_raw->self_kq_mask_cnv = inp_raw->self_kq_mask; +- +- inp_raw->self_k_rot = raw_ctx->build_input_k_rot(ctx0); +- auto inp = std::make_unique(cparams, std::move(inp_raw), mctx_cur); +- +- dsv4_build_comp_inputs(ctx0, inp->inp_csa, mctx_cur->get_csa_plan(ubatch), "csa", cparams, n_stream); +- dsv4_build_comp_inputs(ctx0, inp->inp_hca, mctx_cur->get_hca_plan(ubatch), "hca", cparams, n_stream); +- dsv4_build_comp_inputs(ctx0, inp->inp_lid, mctx_cur->get_lid_plan(ubatch), "lid", cparams, n_stream); +- inp->inp_csa.k_rot = mctx_cur->get_csa()->build_input_k_rot(ctx0); +- inp->inp_hca.k_rot = mctx_cur->get_hca()->build_input_k_rot(ctx0); +- inp->inp_lid.k_rot = mctx_cur->get_lid()->build_input_k_rot(ctx0); ++ request_inputs(inp.get()); + + return (llm_graph_input_dsv4 *) res->add_input(std::move(inp)); + } +@@ -3772,14 +4302,37 @@ ggml_tensor * llm_graph_context::build_rs( + uint32_t rs_size, + int32_t rs_zero, + const llm_graph_get_rows_fn & get_state_rows) const { ++ return build_rs_impl(s, state_copy, state_copy_main, state_size, n_seqs, ++ n_rs, rs_head, rs_size, rs_zero, get_state_rows, nullptr, -1); ++} + ++ggml_tensor * llm_graph_context::build_rs_impl( ++ ggml_tensor * s, ++ ggml_tensor * state_copy, ++ ggml_tensor * state_copy_main, ++ int32_t state_size, ++ int32_t n_seqs, ++ uint32_t n_rs, ++ uint32_t rs_head, ++ uint32_t rs_size, ++ int32_t rs_zero, ++ const llm_graph_get_rows_fn & get_state_rows, ++ const skippy_state_kind * kind, int il) const { + + GGML_UNUSED(rs_size); ++ if (kind != nullptr) { ++ state_read(*kind, s, il); ++ } + ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, s->ne[1]); + + // Clear a single state which will then be copied to the other cleared states. + // Note that this is a no-op when the view is zero-sized. + ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0)); +- ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0)); ++ ggml_tensor * zero_write = ggml_scale_inplace(ctx0, state_zero, 0); ++ ggml_build_forward_expand(gf, zero_write); ++ if (kind != nullptr) { ++ state_write(*kind, s, zero_write, il); ++ } + + // copy states + // NOTE: assuming the copy destinations are ALL contained between rs_head and rs_head + n_rs +@@ -3796,10 +4349,12 @@ ggml_tensor * llm_graph_context::build_rs( + + // copy extra states which won't be changed further (between n_seqs and n_rs) + ggml_tensor * states_extra = ggml_view_2d(ctx0, states_all, state_size, n_rs - n_seqs, states_all->nb[1], (n_seqs - i0)*states_all->nb[1]); +- ggml_build_forward_expand(gf, +- ggml_cpy(ctx0, +- states_extra, +- ggml_view_2d(ctx0, s, state_size, (n_rs - n_seqs), s->nb[1], (rs_head + n_seqs)*s->nb[1]))); ++ ggml_tensor * extra_destination = ggml_view_2d(ctx0, s, state_size, (n_rs - n_seqs), s->nb[1], (rs_head + n_seqs)*s->nb[1]); ++ ggml_tensor * extra_write = ggml_cpy(ctx0, states_extra, extra_destination); ++ ggml_build_forward_expand(gf, extra_write); ++ if (kind != nullptr) { ++ state_write(*kind, s, extra_write, il); ++ } + + return output_states; + } +@@ -3831,6 +4386,7 @@ llm_graph_input_rs * llm_graph_context::build_rs_inp() const { + const auto * mctx_cur = static_cast(mctx); + + auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur); ++ request_inputs(inp.get()); + + return (llm_graph_input_rs *) res->add_input(std::move(inp)); + } +@@ -3852,6 +4408,22 @@ ggml_tensor * llm_graph_context::build_rs( + get_state_rows); + } + ++ggml_tensor * llm_graph_context::build_rs( ++ llm_graph_input_rs * inp, ++ ggml_tensor * s, ++ int32_t state_size, ++ int32_t n_seqs, ++ skippy_state_kind kind, int il, ++ const llm_graph_get_rows_fn & get_state_rows) const { ++ const auto * kv_state = inp->mctx; ++ // the state kinds registered by this overload follow the same gather the plain overload uses ++ ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : inp->s_copy; ++ ++ return build_rs_impl(s, state_copy, inp->s_copy_main, state_size, n_seqs, ++ kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(), ++ get_state_rows, &kind, il); ++} + - llama_adapter_cvec_ptr cvec; - llama_adapter_loras_ptr loras; + ggml_tensor * llm_graph_context::build_rwkv_token_shift_load( + llm_graph_input_rs * inp, + const llama_ubatch & ubatch, +@@ -3866,7 +4438,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_load( -@@ -378,6 +444,7 @@ private: - ggml_backend_sched_ptr sched; + ggml_tensor * token_shift = build_rs( + inp, token_shift_all, +- hparams.n_embd_r(), n_seqs); ++ hparams.n_embd_r(), n_seqs, skippy_state_kind::recurrent_conv, il); - bool sched_need_reserve = true; -+ uint64_t sched_reserve_count = 0; + token_shift = ggml_reshape_3d(ctx0, token_shift, hparams.n_embd, token_shift_count, n_seqs); - // whether the reserve graph has a logits tensor, set in sched_reserve() - // true until then, because the first output_reserve() runs before any graph is reserved -@@ -425,9 +492,32 @@ private: - // Separate arenas give batches with and without outputs distinct CUDA graph cache keys. - std::array gf_res_prev; - llm_graph_result_ptr gf_res_reserve; -+ // Intersect every reserved prefill/decode profile; no configuration can authorize state coverage. -+ uint32_t skippy_cache_capabilities = UINT32_MAX; -+ bool skippy_cache_profile_seen = false; -+ uint32_t skippy_cache_admitted_capabilities = 0; -+ bool skippy_cache_admission_bound = false; +@@ -3886,11 +4458,14 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store( - llm_graph_result * gf_res_prev_active = nullptr; + const auto kv_head = mctx_cur->get_head(); -+ bool activation_boundary_observed = false; -+ bool activation_boundary_stable = true; -+ enum ggml_type activation_boundary_type = GGML_TYPE_COUNT; -+ uint64_t activation_boundary_elements_per_token = 0; -+ uint64_t activation_boundary_bytes_per_token = 0; +- return ggml_cpy( +- ctx0, +- ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0), +- ggml_view_1d(ctx0, mctx_cur->get_r_l(il), hparams.n_embd_r()*n_seqs, hparams.n_embd_r()*kv_head*ggml_element_size(mctx_cur->get_r_l(il))) +- ); ++ ggml_tensor * token_shift_source = ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0); + -+ bool input_activation_boundary_observed = false; -+ bool input_activation_boundary_stable = true; -+ enum ggml_type input_activation_boundary_type = GGML_TYPE_COUNT; -+ uint64_t input_activation_boundary_elements_per_token = 0; -+ uint64_t input_activation_boundary_bytes_per_token = 0; -+ bool activation_frontier_observed = false; -+ bool activation_frontier_stable = true; -+ std::vector activation_frontier; -+ bool input_activation_frontier_observed = false; -+ bool input_activation_frontier_stable = true; -+ std::vector input_activation_frontier; ++ ggml_tensor * token_shift_destination = ggml_view_1d(ctx0, mctx_cur->get_r_l(il), hparams.n_embd_r()*n_seqs, ++ hparams.n_embd_r()*kv_head*ggml_element_size(mctx_cur->get_r_l(il))); + - // host buffer for the model output (logits and embeddings) - ggml_backend_buffer_ptr buf_output; ++ ggml_tensor * token_shift_write = ggml_cpy(ctx0, token_shift_source, token_shift_destination); ++ state_write(skippy_state_kind::recurrent_conv, mctx_cur->get_r_l(il), token_shift_write, il); ++ return token_shift_write; + } -diff --git a/src/llama-ext.h b/src/llama-ext.h -index b55c0c357..9449e1da7 100644 ---- a/src/llama-ext.h -+++ b/src/llama-ext.h -@@ -75,6 +75,12 @@ LLAMA_API bool llama_quant_tensor_allows_quantization( - const quantize_state_impl * qs, - const ggml_tensor * tensor); + llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { +@@ -3898,6 +4473,8 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { -+// Returns whether the selected tensor type requires importance weights. -+LLAMA_API bool llama_quant_tensor_requires_imatrix( -+ const ggml_tensor * tensor, -+ ggml_type type, -+ llama_ftype ftype); + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); ++ request_inputs(inp_rs.get()); ++ request_inputs(inp_attn.get()); + + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); + +@@ -3909,6 +4486,8 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const + + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); ++ request_inputs(inp_rs.get()); ++ request_inputs(inp_attn.get()); + + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); + +@@ -3941,7 +4520,10 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() + inp_attn->self_kq_mask_swa_cnv = inp_attn->self_kq_mask_swa; + } + ++ inp_attn->build_row_inputs(ctx0, ubatch); + - // Compute quantization type assignments for a list of tensors. - // All tensors should be quantizable (use llama_quant_tensor_allows_quantization to filter). - // result_types: caller-allocated array of n_tensors elements, filled with assigned types. + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); ++ request_inputs(inp.get()); + + return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); + } diff --git a/src/llama-graph.h b/src/llama-graph.h index 9867c9540..7137c58d6 100644 --- a/src/llama-graph.h @@ -1516,6 +4780,19 @@ index 9867c9540..7137c58d6 100644 void set_input(const llama_ubatch * ubatch) override; +@@ -1246,7 +1280,11 @@ struct llm_graph_context { + ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] + int64_t n_kv_max, + float kq_scale, +- int il) const; ++ int il, ++ ggml_tensor * kv_rows = nullptr, ++ ggml_tensor * dense_mask = nullptr) const; ++ ++ bool supports_row_attn(const ggml_tensor * node, const ggml_tensor * storage) const; + + llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; + diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index f05b5d6bb..1a554d204 100644 --- a/src/llama-hparams.cpp @@ -2883,7 +6160,10 @@ index a1ec67e26..3648d3207 100644 + if (record_index >= record_count) { + error = "CacheGen records do not cover the native KV page"; + return false; -+ } + } +- +- for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) { +- cells.seq_add(idx, ubatch.seq_id[i][s]); + const auto & record = records[record_index++]; + const size_t rows = static_cast(record.token_count); + uint32_t expected_kind = SKIPPY_CACHEGEN_RECORD_F16; @@ -2912,11 +6192,12 @@ index a1ec67e26..3648d3207 100644 + error = "CacheGen record order or destination geometry is invalid"; + } + return false; -+ } + } + entry.tiles.push_back({ record.payload, record.payload_bytes, static_cast(token_offset), + static_cast(rows) }); + token_offset += rows; -+ } + } +- } + storage.push_back(std::move(entry)); + logical_offset += static_cast(desc.token_count) * row_bytes; + return true; @@ -3775,6 +7056,8 @@ index 5aafbebb3..152da5166 100644 uint32_t get_n_kv() const; uint32_t get_n_kv_rows() const; + uint32_t get_n_kv_pos_contiguous() const; ++ uint32_t get_n_kv_rows() const; ++ void set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const; ggml_type type_k() const; ggml_type type_v() const; @@ -3809,6 +7092,12 @@ index 5aafbebb3..152da5166 100644 // // update context +@@ -470,4 +552,5 @@ private: + // a heuristic, to avoid attending the full cache if it is not yet utilized + // as the cache gets filled, the benefit from this heuristic disappears + int32_t n_kv; ++ uint32_t n_kv_rows = 0; + }; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 85a8e0f75..4b50afe71 100644 --- a/src/llama-kv-cells.h @@ -3818,6 +7107,7 @@ index 85a8e0f75..4b50afe71 100644 seq_pos[s].clear(); std::fill(seq_bits[s].begin(), seq_bits[s].end(), 0); + seq_pos_index_mismatch[s] = 0; ++ std::fill(seq_bits[s].begin(), seq_bits[s].end(), 0); } } @@ -3832,34 +7122,34 @@ index 85a8e0f75..4b50afe71 100644 + assert(isrc < pos.size()); + assert(idst < pos.size()); + assert(isrc != idst); - -- // assert(pos[idst] == -1); -- // assert(pos[isrc] != -1); ++ + assert(pos[idst] == -1); + assert(seq[idst].none()); + assert(pos[isrc] != -1); +- // assert(pos[idst] == -1); +- // assert(pos[isrc] != -1); ++ seq_pos_rm(isrc); + - // pos [idst] = pos [isrc]; - // shift[idst] = shift[isrc]; - // seq [idst] = seq [isrc]; -+ seq_pos_rm(isrc); - -- // pos [isrc] = -1; -- // shift[isrc] = 0; -- // seq [isrc].reset(); + pos [idst] = pos [isrc]; + ext [idst] = ext [isrc]; + shift[idst] = shift[isrc]; + seq [idst] = seq [isrc]; -- // used.erase (isrc); -- // used.insert(idst); -- //} +- // pos [isrc] = -1; +- // shift[isrc] = 0; +- // seq [isrc].reset(); + pos [isrc] = -1; + ext [isrc].reset(); + shift[isrc] = 0; + seq [isrc].reset(); -+ + +- // used.erase (isrc); +- // used.insert(idst); +- //} + used.erase (isrc); + used.insert(idst); + @@ -3888,6 +7178,45 @@ index 85a8e0f75..4b50afe71 100644 + return positions.begin()->first == 0 && pos_max >= 0 && + positions.size() == static_cast(pos_max) + 1; + } ++ ++ uint32_t seq_n_cells(llama_seq_id seq_id) const { ++ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); ++ return seq_pos[seq_id].size(); ++ } ++ ++ uint32_t seq_n_cells(llama_seq_id seq_id, llama_pos p_min) const { ++ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); ++ const auto & positions = seq_pos[seq_id]; ++ return std::distance(positions.lower_bound({p_min, 0}), positions.end()); ++ } ++ ++ // One ascending physical-cell list per owner, padded with -1. Shared ++ // cells appear in every owner's list; position cutoffs only remove rows ++ // hidden by SWA from every query of that slice. ++ void get_seq_cells(const std::vector & seq_ids, ++ const std::vector & p_min, int32_t * data, int64_t n_per_seq) const { ++ assert(!seq_ids.empty()); ++ assert(p_min.empty() || p_min.size() == seq_ids.size()); ++ const uint32_t n_words = (used_max_p1() + 63) / 64; ++ for (size_t s = 0; s < seq_ids.size(); ++s) { ++ assert(seq_ids[s] >= 0 && seq_ids[s] < LLAMA_MAX_SEQ); ++ const auto & bits = seq_bits[seq_ids[s]]; ++ const uint32_t n_w = std::min(n_words, bits.size()); ++ const llama_pos minimum = p_min.empty() ? 0 : p_min[s]; ++ int32_t * dst = data + s * n_per_seq; ++ int32_t * end = dst + n_per_seq; ++ for (uint32_t w = 0; w < n_w; ++w) { ++ for (uint64_t b = bits[w]; b != 0; b &= b - 1) { ++ const int32_t cell = 64 * w + llama_kv_ctz64(b); ++ if (pos[cell] >= minimum) { ++ GGML_ASSERT(dst < end); ++ *dst++ = cell; ++ } ++ } ++ } ++ std::fill(dst, end, -1); ++ } ++ } + // note: call only if the cell is not empty llama_pos pos_get(uint32_t i) const { @@ -3918,9 +7247,120 @@ index 85a8e0f75..4b50afe71 100644 + if (pos[i] != static_cast(i)) { + ++seq_pos_index_mismatch[s]; + } ++ if (seq_bits[s].empty()) { ++ seq_bits[s].assign((pos.size() + 63) / 64, 0); ++ } ++ seq_bits[s][i / 64] |= 1ull << (i % 64); } // remove cell i +diff --git a/src/llama-kv-rows.cpp b/src/llama-kv-rows.cpp +new file mode 100644 +index 000000000..57608f5ae +--- /dev/null ++++ b/src/llama-kv-rows.cpp +@@ -0,0 +1,101 @@ ++#include "llama-kv-cache.h" ++ ++#include "ggml-backend.h" ++ ++#include ++#include ++ ++uint32_t llama_kv_cache::get_n_kv_slices(const llama_ubatch & ubatch) { ++ if (!ubatch.n_tokens || !ubatch.n_seqs_unq || !ubatch.n_seq_id || !ubatch.seq_id || ++ !ubatch.seq_id_unq || ubatch.decision_order) { ++ return 0; ++ } ++ uint32_t slices = 0; ++ if (ubatch.n_seqs_unq == 1) { ++ slices = 1; ++ } else if (ubatch.equal_seqs() && ubatch.n_seqs == ubatch.n_seqs_unq) { ++ slices = ubatch.n_seqs; ++ } else if (ubatch.n_tokens == ubatch.n_seqs_unq) { ++ slices = ubatch.n_tokens; ++ } ++ if (!slices || ubatch.n_tokens % slices != 0) { ++ return 0; ++ } ++ // Query blocks determine stream order, not seq_id_unq's enumeration order. ++ const uint32_t per_slice = ubatch.n_tokens / slices; ++ std::set actual, expected; ++ for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { ++ expected.insert(ubatch.seq_id_unq[s]); ++ } ++ for (uint32_t s = 0; s < slices; ++s) { ++ const uint32_t first = s * per_slice; ++ if (ubatch.n_seq_id[first] != 1 || !ubatch.seq_id[first]) { ++ return 0; ++ } ++ const auto owner = ubatch.seq_id[first][0]; ++ if (owner < 0 || owner >= LLAMA_MAX_SEQ || !actual.insert(owner).second) { ++ return 0; ++ } ++ for (uint32_t i = first; i < first + per_slice; ++i) { ++ if (ubatch.n_seq_id[i] != 1 || !ubatch.seq_id[i] || ubatch.seq_id[i][0] != owner) { ++ return 0; ++ } ++ } ++ } ++ return actual == expected ? slices : 0; ++} ++ ++std::vector llama_kv_cache::get_kv_rows_p_min(const llama_ubatch & ubatch, uint32_t n_slices) const { ++ if (!n_swa || (swa_type != LLAMA_SWA_TYPE_STANDARD && swa_type != LLAMA_SWA_TYPE_CHUNKED)) { ++ return {}; ++ } ++ GGML_ASSERT(n_slices && ubatch.pos && ubatch.n_tokens % n_slices == 0); ++ const uint32_t per_slice = ubatch.n_tokens / n_slices; ++ std::vector result(n_slices); ++ for (uint32_t s = 0; s < n_slices; ++s) { ++ const auto * begin = ubatch.pos + s * per_slice; ++ const llama_pos minimum = *std::min_element(begin, begin + per_slice); ++ result[s] = swa_type == LLAMA_SWA_TYPE_STANDARD ? minimum - (llama_pos) n_swa + 1 : ++ (minimum / (llama_pos) n_swa) * (llama_pos) n_swa; ++ } ++ return result; ++} ++ ++uint32_t llama_kv_cache::get_n_kv_rows(const llama_ubatch & ubatch) const { ++ const uint32_t slices = get_n_kv_slices(ubatch); ++ if (n_stream != 1 || !slices) { ++ return 0; ++ } ++ const auto & cells = v_cells[0]; ++ const auto minimum = get_kv_rows_p_min(ubatch, slices); ++ const uint32_t per_slice = ubatch.n_tokens / slices; ++ uint32_t maximum = 0; ++ for (uint32_t s = 0; s < slices; ++s) { ++ const auto owner = ubatch.seq_id[s * per_slice][0]; ++ const auto count = minimum.empty() ? cells.seq_n_cells(owner) : cells.seq_n_cells(owner, minimum[s]); ++ maximum = std::max(maximum, count); ++ } ++ return std::min(GGML_PAD(maximum, 256u), get_size()); ++} ++ ++void llama_kv_cache::set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const { ++ GGML_ASSERT(rows && rows->buffer && ggml_backend_buffer_is_host(rows->buffer)); ++ GGML_ASSERT(n_stream == 1 && rows->type == GGML_TYPE_I32 && ggml_is_contiguous(rows)); ++ const uint32_t slices = get_n_kv_slices(*ubatch); ++ GGML_ASSERT(slices && rows->ne[1] == slices && rows->ne[2] == 1 && rows->ne[3] == 1); ++ const uint32_t per_slice = ubatch->n_tokens / slices; ++ std::vector owners(slices); ++ for (uint32_t s = 0; s < slices; ++s) { ++ owners[s] = ubatch->seq_id[s * per_slice][0]; ++ } ++ v_cells[0].get_seq_cells(owners, get_kv_rows_p_min(*ubatch, slices), ++ static_cast(rows->data), rows->ne[0]); ++} ++ ++uint32_t llama_kv_cache_context::get_n_kv_rows() const { ++ return n_kv_rows; ++} ++ ++void llama_kv_cache_context::set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const { ++ kv->set_input_kv_rows(rows, ubatch); ++} diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 9213ac1dc..b7570d445 100644 --- a/src/llama-memory-recurrent.cpp diff --git a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch index 4908abdb81..4a22b660de 100644 --- a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch +++ b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch @@ -2584,7 +2584,7 @@ index 5e6099ce1..8c21125d5 100644 X(FA_AUX, fa_aux) \ X(FA_F16, fa_f16) \ X(FA_F32, fa_f32) \ -@@ -180,6 +183,11 @@ struct ggml_metal_library { +@@ -180,6 +183,11 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi ggml_metal_device_t dev; ggml_metal_pipelines_t pipelines; // cache of compiled pipelines @@ -3744,6 +3744,7 @@ index 426c48741..0a5980aaa 100644 + target_link_libraries(skippy-graph-build-inputs PRIVATE llama) + add_dependencies(skippy-stage-slice-plan skippy-graph-build-inputs skippy-profile-residency) + add_test(NAME skippy_decode_input_width COMMAND skippy-graph-build-inputs --input-width) ++ add_test(NAME skippy_iswa_row_inputs COMMAND skippy-graph-build-inputs --iswa-rows) + + add_test( + NAME skippy_graph_build_inputs diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index aa2bb8af52..cf9189a48a 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -13,13 +13,14 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts .../tests/hardware_application_probe.cpp | 76 + src/skippy/tests/input_capabilities.cpp | 78 + .../tests/input_leaf_state_regression.h | 49 + + src/skippy/tests/iswa_row_inputs_cases.hpp | 307 +++ src/skippy/tests/live_graph_reference.h | 194 ++ src/skippy/tests/noalloc_graph_planning.cpp | 1137 +++++++++++ src/skippy/tests/profile_residency.cpp | 258 +++ .../tests/renamed_multishard_planning.cpp | 1665 +++++++++++++++++ .../tests/residual_checkpoint_regression.h | 52 + src/skippy/tests/runtime_events.cpp | 695 +++++++ - src/skippy/tests/sampling_history.cpp | 517 +++++ + src/skippy/tests/sampling_history.cpp | 967 ++++++++++ src/skippy/tests/stage_plan_header.c | 10 + src/skippy/tests/stage_plan_header.cpp | 13 + src/skippy/tests/stage_slice_plan.cpp | 1198 ++++++++++++ @@ -27,13 +28,14 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts tests/test-chat-auto-parser.cpp | 47 + tests/test-chat.cpp | 189 +- tests/test-deepseek4-mtp.h | 88 + + tests/test-flash-attn-rows.cpp | 536 ++++++ tests/test-graph-contract-fixture.h | 155 ++ tests/test-llama-archs.cpp | 351 +++- tests/test-reasoning-budget.cpp | 24 + tests/test-skippy-activation-validation.cpp | 18 + tests/test-skippy-cachegen-import.cpp | 347 ++++ tests/test-skippy-cachegen-metal.cpp | 399 ++++ - tests/test-skippy-kv-cells-contiguous.cpp | 20 + + tests/test-skippy-kv-cells-contiguous.cpp | 118 ++ tests/test-skippy-kv-page-export.cpp | 367 ++++ tests/test-skippy-model-loader-accounting.cpp | 320 ++++ .../test-skippy-recurrent-state-roundtrip.cpp | 160 ++ @@ -50,6 +52,7 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts create mode 100644 src/skippy/tests/hardware_application_probe.cpp create mode 100644 src/skippy/tests/input_capabilities.cpp create mode 100644 src/skippy/tests/input_leaf_state_regression.h + create mode 100644 src/skippy/tests/iswa_row_inputs_cases.hpp create mode 100644 src/skippy/tests/live_graph_reference.h create mode 100644 src/skippy/tests/noalloc_graph_planning.cpp create mode 100644 src/skippy/tests/profile_residency.cpp @@ -62,6 +65,7 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts create mode 100644 src/skippy/tests/stage_plan_header.cpp create mode 100644 src/skippy/tests/stage_slice_plan.cpp create mode 100644 tests/test-deepseek4-mtp.h + create mode 100644 tests/test-flash-attn-rows.cpp create mode 100644 tests/test-graph-contract-fixture.h create mode 100644 tests/test-skippy-activation-validation.cpp create mode 100644 tests/test-skippy-cachegen-import.cpp @@ -235,6 +239,8 @@ index 000000000..cd2e4af3f +#include +#include + ++#include "iswa_row_inputs_cases.hpp" ++ +class recording_input final : public llm_graph_input_i { +public: + void set_build_inputs(const skippy_graph_build_inputs & inputs) override { @@ -779,6 +785,7 @@ index 000000000..cd2e4af3f +static const char * fused_op_name(llm_fused_op op) { + switch (op) { + case LLM_FUSED_OP_FLASH_ATTN: return "flash attention"; ++ case LLM_FUSED_OP_FLASH_ATTN_KV_ROWS: return "flash attention with KV rows"; + case LLM_FUSED_OP_GDN_AR: return "Gated Delta Net (autoregressive)"; + case LLM_FUSED_OP_GDN_CH: return "Gated Delta Net (chunked)"; + case LLM_FUSED_OP_LIGHTNING_INDEXER: return "Lightning Indexer"; @@ -1118,6 +1125,12 @@ index 000000000..cd2e4af3f + if (const int rc = check_embedding_execution_profiles()) { + return rc; + } ++ if (argc == 2 && std::strcmp(argv[1], "--iswa-rows") == 0) { ++ llama_backend_init(); ++ const int rc = check_iswa_row_inputs(); ++ llama_backend_free(); ++ return rc; ++ } + if (argc == 2 && std::strcmp(argv[1], "--input-width") == 0) { + return check_decode_input_width(); + } @@ -1876,6 +1889,319 @@ index 000000000..33d3faca9 + if (skippy_infer_state_effects({}, graph, boundaries, effects, error)) { return 96; } + return 0; +} +diff --git a/src/skippy/tests/iswa_row_inputs_cases.hpp b/src/skippy/tests/iswa_row_inputs_cases.hpp +new file mode 100644 +index 000000000..331607a34 +--- /dev/null ++++ b/src/skippy/tests/iswa_row_inputs_cases.hpp +@@ -0,0 +1,307 @@ ++#pragma once ++ ++#include "llama-kv-cache-iswa.h" ++#include "llama-memory-hybrid-iswa.h" ++ ++#include ++#include ++#include ++ ++// A tiny native cache/graph fixture, not a synthetic model certification. No ++// weights or family builders: the actual generic ISWA builder and two caches ++// own all row lists, masks, allocation, reuse and attention computations below. ++class iswa_row_fixture_model final : public llama_model { ++public: ++ iswa_row_fixture_model() : llama_model(llama_model_default_params()) { ++ arch = LLM_ARCH_LLAMA; ++ attn_rot = false; ++ hparams.n_layer_all = 2; ++ hparams.n_embd = 64; ++ hparams.n_embd_head_k_full = hparams.n_embd_head_v_full = 64; ++ hparams.n_embd_head_k_swa = hparams.n_embd_head_v_swa = 64; ++ hparams.n_head_arr.fill(1); ++ hparams.n_head_kv_arr.fill(1); ++ hparams.is_swa_impl[1] = 1; ++ hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; ++ hparams.n_swa = 2; ++ } ++ void load_stats(llama_model_loader &) override {} ++ void load_hparams(llama_model_loader &) override {} ++ void load_vocab(llama_model_loader &) override {} ++ bool load_tensors(llama_model_loader &) override { return false; } ++ void load_arch_hparams(llama_model_loader &) override {} ++ void load_arch_tensors(llama_model_loader &) override {} ++ std::unique_ptr build_arch_graph(const llm_graph_params &) const override { return nullptr; } ++}; ++ ++static void iswa_row_require(bool condition, const char * message) { ++ if (!condition) throw std::runtime_error(message); ++} ++ ++static llama_ubatch iswa_row_batch(uint32_t per_owner, llama_pos first, bool two_owners) { ++ llama_ubatch batch = {}; ++ batch.b_equal_seqs = 1; ++ batch.n_seq_tokens = per_owner; ++ batch.n_seqs = batch.n_seqs_unq = two_owners ? 2 : 1; ++ batch.n_tokens = per_owner * batch.n_seqs; ++ batch.n_pos = 1; ++ batch.data = std::make_shared(); ++ auto & data = *batch.data; ++ data.token.assign(batch.n_tokens, 1); ++ data.pos.resize(batch.n_tokens); ++ data.n_seq_id.assign(batch.n_tokens, 1); ++ data.seq_id_data.resize(batch.n_tokens); ++ data.seq_id.resize(batch.n_tokens); ++ data.seq_id_unq = two_owners ? std::vector{0, 1} : std::vector{0}; ++ data.output.assign(batch.n_tokens, 1); ++ data.seq_idx.assign(LLAMA_MAX_SEQ, -1); ++ for (uint32_t i = 0; i < batch.n_seqs_unq; ++i) data.seq_idx[data.seq_id_unq[i]] = i; ++ for (uint32_t i = 0; i < batch.n_tokens; ++i) { ++ // Deliberately different from seq_id_unq order: Q blocks own stream order. ++ data.seq_id_data[i] = two_owners ? 1 - i/per_owner : 0; ++ data.seq_id[i] = &data.seq_id_data[i]; ++ data.pos[i] = first + i%per_owner; ++ } ++ batch.token = data.token.data(); ++ batch.pos = data.pos.data(); ++ batch.n_seq_id = data.n_seq_id.data(); ++ batch.seq_id = data.seq_id.data(); ++ batch.seq_id_unq = data.seq_id_unq.data(); ++ batch.output = data.output.data(); ++ batch.seq_idx = data.seq_idx.data(); ++ return batch; ++} ++ ++static std::unique_ptr iswa_row_apply( ++ llama_kv_cache_iswa & cache, const llama_ubatch & batch) { ++ auto base = cache.get_base()->prepare({batch}); ++ auto swa = cache.get_swa()->prepare({batch}); ++ iswa_row_require(base.size() == 1 && swa.size() == 1, "ISWA prepare both pools"); ++ auto context = std::make_unique( ++ &cache, std::move(base), std::move(swa), std::vector{batch}); ++ iswa_row_require(context->apply(), "ISWA apply both pools"); ++ return context; ++} ++ ++static void iswa_row_check_pool( ++ const llama_kv_cache & cache, const llama_ubatch & batch, ++ const ggml_tensor * rows, const ggml_tensor * mask, bool swa) { ++ iswa_row_require(rows && mask && rows->buffer && mask->buffer, "ISWA both live inputs allocated"); ++ iswa_row_require(rows->type == GGML_TYPE_I32 && rows->ne[0] >= 256 && rows->ne[0] % 256 == 0 && rows->ne[1] == 2 && ++ mask->type == GGML_TYPE_F16 && mask->ne[0] == rows->ne[0] && mask->ne[1] == 2 && mask->ne[3] == 2, ++ "ISWA row/mask geometry"); ++ const uint32_t width = static_cast(rows->ne[0]); ++ const auto * actual_rows = static_cast(rows->data); ++ const auto * actual_mask = static_cast(mask->data); ++ for (uint32_t stream = 0; stream < 2; ++stream) { ++ const llama_seq_id owner = batch.seq_id[stream*2][0]; ++ const auto & cells = cache.get_cells(owner); ++ std::vector expected; ++ for (uint32_t physical = 0; physical < cells.size(); ++physical) { ++ // Independent scalar scan of actual membership and the known 2-row window. ++ if (cells.seq_has(physical, owner) && (!swa || cells.pos_get(physical) >= batch.pos[stream*2] - 1)) { ++ expected.push_back(static_cast(physical)); ++ } ++ } ++ iswa_row_require(!expected.empty() && expected.size() < width, "ISWA nonempty bounded expected rows"); ++ for (uint32_t column = 0; column < width; ++column) { ++ const int32_t physical = column < expected.size() ? expected[column] : -1; ++ iswa_row_require(actual_rows[stream*width + column] == physical, "ISWA current ascending owner rows"); ++ for (uint32_t q = 0; q < 2; ++q) { ++ const llama_pos query = batch.pos[stream*2 + q]; ++ const bool visible = physical >= 0 && cells.pos_get(physical) <= query && ++ (!swa || cells.pos_get(physical) > query - 2); ++ const float value = ggml_fp16_to_fp32(actual_mask[(stream*2 + q)*width + column]); ++ iswa_row_require(visible ? value == 0.0f : (std::isinf(value) && value < 0), ++ "ISWA exact causal/SWA compact mask"); ++ } ++ } ++ } ++} ++ ++static void iswa_row_check_bindings(const llm_graph_result & result, const llm_graph_input_attn_kv_iswa & input) { ++ const std::pair expected[] = { ++ {input.self_kv_rows, "attention.base.read_rows.0"}, ++ {input.self_read_mask, "attention.base.read_mask.0"}, ++ {input.self_kv_rows_swa, "attention.swa.read_rows.0"}, ++ {input.self_read_mask_swa, "attention.swa.read_mask.0"}, ++ }; ++ for (const auto & item : expected) { ++ iswa_row_require(item.first != nullptr, "ISWA missing declared input"); ++ const auto & bindings = result.get_request_input_bindings(); ++ const auto count = std::count_if(bindings.begin(), bindings.end(), [&](const skippy_request_input_binding & binding) { ++ return binding.tensor == item.first && binding.identity == item.second; ++ }); ++ iswa_row_require(count == 1, "ISWA semantic input binding"); ++ } ++} ++ ++static int check_iswa_row_inputs() { ++ try { ++ iswa_row_fixture_model model; ++ llama_kv_cache_iswa cache(model, GGML_TYPE_F16, GGML_TYPE_F16, false, false, ++ false, true, 512, 3, 16, 256, nullptr, nullptr, nullptr, nullptr); ++ auto prefix = iswa_row_batch(8, 0, false); ++ auto prefix_context = iswa_row_apply(cache, prefix); ++ cache.seq_cp(0, 1, -1, -1); ++ cache.seq_cp(0, 2, -1, -1); // parked owner keeps the shared prefix live ++ auto first = iswa_row_batch(2, 8, true); ++ auto first_context = iswa_row_apply(cache, first); ++ ggml_backend_ptr cpu(ggml_backend_cpu_init()); ++ iswa_row_require(cpu != nullptr, "ISWA CPU backend"); ++ ggml_backend_t backends[] = {cpu.get()}; ++ ggml_backend_sched_ptr scheduler(ggml_backend_sched_new(backends, nullptr, 1, 512, false, true)); ++ iswa_row_require(scheduler != nullptr, "ISWA CPU scheduler"); ++ llm_graph_result result(512); ++ llm_graph_params params = {}; ++ params.arch = model.arch; ++ params.hparams = model.hparams; ++ params.cparams.flash_attn = params.cparams.fused_kv_rows = true; ++ params.cparams.kv_unified = params.cparams.causal_attn = params.cparams.offload_kqv = true; ++ params.cparams.n_ctx = 512; ++ params.cparams.n_seq_max = 3; ++ params.ubatch = first; ++ params.mctx = first_context.get(); ++ params.sched = scheduler.get(); ++ params.backend_cpu = cpu.get(); ++ params.res = &result; ++ llm_graph_context graph(params); ++ auto * input = graph.build_attn_inp_kv_iswa(); ++ iswa_row_check_bindings(result, *input); ++ auto * q = ggml_new_tensor_3d(result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); ++ ggml_set_input(q); ++ std::vector outputs; ++ for (int layer = 0; layer < 2; ++layer) { ++ outputs.push_back(graph.build_attn(input, nullptr, nullptr, nullptr, q, nullptr, nullptr, ++ nullptr, nullptr, nullptr, 0.125f, layer)); ++ } ++ const auto & fused = result.get_fused_nodes(); ++ iswa_row_require(fused.size() == 2, "ISWA both attention layers"); ++ for (const auto & node : fused) { ++ const bool swa = model.hparams.is_swa(node.il); ++ iswa_row_require(node.op == LLM_FUSED_OP_FLASH_ATTN_KV_ROWS && node.tensor->src[6] == nullptr && ++ node.tensor->src[5] == (swa ? input->self_kv_rows_swa : input->self_kv_rows) && ++ node.tensor->src[3] == (swa ? input->self_read_mask_swa : input->self_read_mask) && ++ ggml_backend_supports_op(cpu.get(), node.tensor), "ISWA per-layer pool/route admission"); ++ } ++ iswa_row_require(ggml_backend_sched_alloc_graph(scheduler.get(), result.get_gf()), "ISWA graph allocation"); ++ std::vector zeros(64*4, 0.0f); ++ ggml_backend_tensor_set(q, zeros.data(), 0, zeros.size()*sizeof(float)); ++ const auto execute = [&](const llama_ubatch & batch) { ++ result.set_inputs(&batch); ++ iswa_row_check_pool(*cache.get_base(), batch, input->self_kv_rows, input->self_read_mask, false); ++ iswa_row_check_pool(*cache.get_swa(), batch, input->self_kv_rows_swa, input->self_read_mask_swa, true); ++ iswa_row_require(ggml_backend_sched_graph_compute(scheduler.get(), result.get_gf()) == GGML_STATUS_SUCCESS, ++ "ISWA finite graph compute"); ++ for (auto * output : outputs) { ++ std::vector values(ggml_nelements(output)); ++ ggml_backend_tensor_get(output, values.data(), 0, values.size()*sizeof(float)); ++ for (float value : values) iswa_row_require(std::isfinite(value) && value == 0.0f, "ISWA zero-KV finite output"); ++ } ++ }; ++ execute(first); ++ auto next = iswa_row_batch(2, 10, true); ++ auto next_context = iswa_row_apply(cache, next); ++ params.ubatch = next; ++ params.mctx = next_context.get(); ++ iswa_row_require(input->can_reuse(params) && input->mctx == next_context.get(), "ISWA refresh actual current mctx"); ++ execute(next); ++ for (const auto * pool : {cache.get_base(), cache.get_swa()}) { ++ const auto & cells = pool->get_cells(2); ++ for (uint32_t i = 0; i < 8; ++i) { ++ iswa_row_require(cells.seq_has(i, 0) && cells.seq_has(i, 1) && cells.seq_has(i, 2) && ++ cells.pos_get(i) == static_cast(i), "ISWA shared parked prefix retained"); ++ } ++ } ++ // Exercise the hybrid caller with real typed contexts too. The fixture ++ // has no recurrent layers: this checks attention delegation, not RS math. ++ llama_memory_hybrid_iswa hybrid(model, GGML_TYPE_F16, GGML_TYPE_F16, false, false, ++ 512, 16, 256, GGML_TYPE_F32, GGML_TYPE_F32, 3, 3, 0, false, true, ++ nullptr, [](int32_t) { return false; }); ++ auto * hybrid_cache = hybrid.get_mem_attn(); ++ auto hybrid_prefix = iswa_row_apply(*hybrid_cache, prefix); ++ hybrid_cache->seq_cp(0, 1, -1, -1); ++ hybrid_cache->seq_cp(0, 2, -1, -1); ++ auto hybrid_first = iswa_row_apply(*hybrid_cache, first); ++ auto hybrid_context = hybrid.init_full(); ++ auto * old_hybrid_context = static_cast(hybrid_context.get()); ++ ggml_backend_sched_ptr hybrid_scheduler(ggml_backend_sched_new(backends, nullptr, 1, 512, false, true)); ++ iswa_row_require(hybrid_scheduler != nullptr, "hybrid ISWA CPU scheduler"); ++ llm_graph_result hybrid_result(512); ++ auto hybrid_params = params; ++ hybrid_params.ubatch = first; ++ hybrid_params.mctx = hybrid_context.get(); ++ hybrid_params.res = &hybrid_result; ++ hybrid_params.sched = hybrid_scheduler.get(); ++ llm_graph_context hybrid_graph(hybrid_params); ++ auto * hybrid_input = hybrid_graph.build_inp_mem_hybrid_iswa(); ++ iswa_row_check_bindings(hybrid_result, *hybrid_input->get_attn()); ++ auto * hybrid_q = ggml_new_tensor_3d(hybrid_result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); ++ ggml_set_input(hybrid_q); ++ std::vector hybrid_outputs; ++ for (int layer = 0; layer < 2; ++layer) { ++ hybrid_outputs.push_back(hybrid_graph.build_attn(hybrid_input->get_attn(), nullptr, nullptr, nullptr, ++ hybrid_q, nullptr, nullptr, nullptr, nullptr, nullptr, 0.125f, layer)); ++ } ++ iswa_row_require(ggml_backend_sched_alloc_graph(hybrid_scheduler.get(), hybrid_result.get_gf()), ++ "hybrid ISWA graph allocation"); ++ ggml_backend_tensor_set(hybrid_q, zeros.data(), 0, zeros.size()*sizeof(float)); ++ const auto execute_hybrid = [&](const llama_ubatch & batch) { ++ hybrid_result.set_inputs(&batch); ++ const auto * attention = hybrid_input->get_attn(); ++ iswa_row_check_pool(*hybrid_cache->get_base(), batch, attention->self_kv_rows, attention->self_read_mask, false); ++ iswa_row_check_pool(*hybrid_cache->get_swa(), batch, attention->self_kv_rows_swa, attention->self_read_mask_swa, true); ++ iswa_row_require(ggml_backend_sched_graph_compute(hybrid_scheduler.get(), hybrid_result.get_gf()) == GGML_STATUS_SUCCESS, ++ "hybrid ISWA finite compute"); ++ for (auto * output : hybrid_outputs) { ++ std::vector values(ggml_nelements(output)); ++ ggml_backend_tensor_get(output, values.data(), 0, values.size()*sizeof(float)); ++ for (float value : values) iswa_row_require(std::isfinite(value) && value == 0.0f, "hybrid ISWA finite output"); ++ } ++ }; ++ execute_hybrid(first); ++ auto hybrid_next = iswa_row_apply(*hybrid_cache, next); ++ auto next_hybrid_context = hybrid.init_full(); ++ hybrid_params.ubatch = next; ++ hybrid_params.mctx = next_hybrid_context.get(); ++ const auto * actual_hybrid_context = static_cast(next_hybrid_context.get()); ++ iswa_row_require(actual_hybrid_context != old_hybrid_context && hybrid_input->can_reuse(hybrid_params) && ++ hybrid_input->mctx == actual_hybrid_context && hybrid_input->get_attn()->mctx == actual_hybrid_context->get_attn(), ++ "hybrid ISWA refresh both current context pointers"); ++ execute_hybrid(next); ++ ++ auto ragged = next; ++ ragged.b_equal_seqs = 0; ++ ragged.n_tokens = 3; ++ iswa_row_require(!input->can_reuse_row_inputs(ragged, params.cparams), "ISWA ragged topology rejects row reuse"); ++ auto ordinary = params.cparams; ++ ordinary.fused_kv_rows = false; ++ iswa_row_require(!input->can_reuse_row_inputs(next, ordinary), "ISWA row-enabled topology cannot reuse ordinary"); ++ ordinary = params.cparams; ++ ordinary.training = true; ++ iswa_row_require(!input->can_reuse_row_inputs(next, ordinary), "ISWA training cannot reuse row topology"); ++ // Test both ordinary pool builders without changing the product setting. ++ llm_graph_result ordinary_result(512); ++ params.cparams.fused_kv_rows = false; ++ params.res = &ordinary_result; ++ llm_graph_context ordinary_graph(params); ++ auto * ordinary_input = ordinary_graph.build_attn_inp_kv_iswa(); ++ iswa_row_require(!ordinary_input->self_kv_rows && !ordinary_input->self_kv_rows_swa, ++ "ISWA ordinary row inputs absent"); ++ auto * ordinary_q = ggml_new_tensor_3d(ordinary_result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); ++ for (int layer = 0; layer < 2; ++layer) { ++ ordinary_graph.build_attn(ordinary_input, nullptr, nullptr, nullptr, ordinary_q, nullptr, nullptr, ++ nullptr, nullptr, nullptr, 0.125f, layer); ++ } ++ iswa_row_require(ordinary_result.get_fused_nodes().size() == 2, "ISWA both ordinary layers"); ++ for (const auto & node : ordinary_result.get_fused_nodes()) { ++ iswa_row_require(node.op == LLM_FUSED_OP_FLASH_ATTN && !node.tensor->src[5] && !node.tensor->src[6] && ++ node.tensor->src[3] == (model.hparams.is_swa(node.il) ? ordinary_input->self_kq_mask_swa : ordinary_input->self_kq_mask), ++ "ISWA ordinary per-layer mask"); ++ } ++ return 0; ++ } catch (const std::exception & error) { ++ std::fprintf(stderr, "ISWA row-input regression: %s\n", error.what()); ++ return 120; ++ } ++} diff --git a/src/skippy/tests/live_graph_reference.h b/src/skippy/tests/live_graph_reference.h new file mode 100644 index 000000000..73129bf07 @@ -6208,12 +6534,14 @@ index 000000000..00a6ff0ec +} diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp new file mode 100644 -index 000000000..9e134586f +index 000000000..ec345c761 --- /dev/null +++ b/src/skippy/tests/sampling_history.cpp -@@ -0,0 +1,517 @@ +@@ -0,0 +1,967 @@ +#include "skippy.h" +#include "../runtime_types.h" ++#include "../sampling_internal.h" ++#include "../sampling_argmax.h" +#include "../runtime_support.h" +#include "llama-model.h" +#include "llama-graph.h" @@ -6566,6 +6894,10 @@ index 000000000..9e134586f + ok(status, error); + CHECK(session->token_history.size() == prefix.size()); + CHECK(session->sampling_accepted_token_count <= session->token_history.size()); ++ CHECK(session->sampler == nullptr); ++ configure(session, sampling, false, prefix.size() + 1); ++ CHECK(decode(session, sampling, 2) == 42); ++ CHECK(decode(session, sampling, 42) == 43); + release(session); +} + @@ -6595,6 +6927,108 @@ index 000000000..9e134586f + release(restored); +} + ++// Temperature 0 with the defaults and sampler order the serving layer sends. ++skippy_sampling_config temperature_zero_config() { ++ skippy_sampling_config config{}; ++ config.version = 1; ++ config.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ config.temperature = 0.0f; ++ config.top_k = 40; ++ config.top_p = 0.95f; ++ config.min_p = 0.05f; ++ config.typical_p = 1.0f; ++ config.top_nsigma = -1.0f; ++ config.dynatemp_exponent = 1.0f; ++ config.repeat_penalty = 1.0f; ++ config.penalty_last_n = 64; ++ config.dry_base = 1.75f; ++ config.dry_allowed_length = 2; ++ config.dry_penalty_last_n = 64; ++ config.xtc_threshold = 0.1f; ++ config.mirostat_entropy = 5.0f; ++ config.mirostat_learning_rate = 0.1f; ++ config.reasoning_budget_tokens = -1; ++ config.sampler_count = 9; ++ for (uint32_t i = 0; i < config.sampler_count; ++i) { ++ config.samplers[i] = i + 1; ++ } ++ return config; ++} ++ ++// The token a freshly built chain selects from the row the last decode sampled. ++llama_token full_chain_token(skippy_session * session) { ++ auto * reference = common_sampler_clone(session->sampler); ++ CHECK(reference != nullptr); ++ common_sampler_reset(reference); ++ for (const llama_token token : session->token_history) { ++ common_sampler_accept(reference, token, true); ++ } ++ const auto token = common_sampler_sample(reference, session->ctx, -1); ++ CHECK(common_sampler_last(session->sampler) == session->token_history.back()); ++ CHECK(session->sampling_accepted_token_count == session->token_history.size()); ++ common_sampler_free(reference); ++ return token; ++} ++ ++// Count the decodes that took the argmax path and check each against the full chain. ++uint64_t argmax_decodes(skippy_model * model, const skippy_sampling_config & sampling, ++ std::vector * predicted) { ++ auto * session = create(model); ++ prefill(session, {1, 2, 3, 4, 5, 6, 7, 8}); ++ const uint64_t before = session->sampling_argmax_count; ++ llama_token previous = 9; ++ for (int step = 0; step < 6; ++step) { ++ previous = decode(session, sampling, previous); ++ CHECK(previous == full_chain_token(session)); ++ predicted->push_back(previous); ++ } ++ const uint64_t taken = session->sampling_argmax_count - before; ++ release(session); ++ return taken; ++} ++ ++void argmax_path(skippy_model * model) { ++ // Repeated biases apply in order to the original logit, without pre-summing. ++ skippy_argmax_plan plan; ++ skippy_prepare_argmax_plan(&plan, {{0, -1e20f}, {1, 0.0f}, {0, 1.0f}, {-1, 4.0f}}, 2); ++ const float logits[] = {1e20f, 0.5f}; ++ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); ++ skippy_prepare_argmax_plan(&plan, {}, 2); ++ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); ++ ++ // Each request can only select the top biased logit, so it must not run the full chain. ++ auto ignore_eos = temperature_zero_config(); ++ ignore_eos.flags |= SKIPPY_SAMPLING_FLAG_IGNORE_EOS; ++ ignore_eos.ignore_eos = 1; ++ auto logit_bias = temperature_zero_config(); ++ logit_bias.logit_bias_count = 2; ++ logit_bias.logit_bias[0] = {7, -3.0f}; ++ logit_bias.logit_bias[1] = {9, 2.5f}; ++ auto inert_penalties = temperature_zero_config(); ++ inert_penalties.presence_penalty = 0.5f; ++ inert_penalties.frequency_penalty = 0.5f; ++ inert_penalties.penalty_last_n = 0; ++ for (const auto & sampling : {ignore_eos, logit_bias, inert_penalties}) { ++ std::vector predicted; ++ const uint64_t taken = argmax_decodes(model, sampling, &predicted); ++ if (taken != predicted.size()) { ++ std::fprintf(stderr, "argmax path taken for %llu of %zu temperature-0 decodes\n", ++ static_cast(taken), predicted.size()); ++ } ++ CHECK(taken == predicted.size()); ++ } ++ ++ // Equal biased maxima keep the full chain's tie order. ++ auto tie = temperature_zero_config(); ++ tie.logit_bias_count = 2; ++ tie.logit_bias[0] = {3, 1e30f}; ++ tie.logit_bias[1] = {5, 1e30f}; ++ std::vector predicted; ++ CHECK(argmax_decodes(model, tie, &predicted) == 0); ++ for (const llama_token token : predicted) { ++ CHECK(token == 3 || token == 5); ++ } ++} + +int32_t stage_layers(skippy_session * session) { + return session->stage_model->model->hparams.n_layer(); @@ -6883,6 +7317,7 @@ index 000000000..9e134586f + error = nullptr; + + config = sampling_config(); ++ config.temperature = 0.8f; + config.ignore_eos = 1; + config.logit_bias_count = 3; + const auto * vocab = llama_model_get_vocab(model->model); @@ -7021,6 +7456,8 @@ index 000000000..9e134586f + // partial side payload is intentionally empty there. + CHECK(require_recurrent); + state_round_trip(model); ++ } else if (argmax) { ++ argmax_path(model); + } else { + for (const bool full : {false, true}) { + if (grammar) { @@ -8790,6 +9227,548 @@ index 000000000..87a499031 + } + return 0; +} +diff --git a/tests/test-flash-attn-rows.cpp b/tests/test-flash-attn-rows.cpp +new file mode 100644 +index 000000000..22e1bc3d9 +--- /dev/null ++++ b/tests/test-flash-attn-rows.cpp +@@ -0,0 +1,536 @@ ++#include "ggml.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++constexpr int64_t kv_heads = 2; ++constexpr int64_t requests = 4; ++// Match test_flash_attn_ext::max_nmse_err in test-backend-ops.cpp. ++constexpr double max_nmse = 5e-4; ++ ++struct attention_case { ++ int64_t queries; ++ int64_t logical_rows; ++ bool mask; ++ bool sinks; ++ bool query_local = false; ++ bool strided_query = false; ++ ggml_type type_k = GGML_TYPE_F16; ++ ggml_type type_v = GGML_TYPE_F16; ++ int64_t dk = 256; ++ int64_t dv = 256; ++ float max_bias = 1.5f; ++ int64_t heads = 8; ++ float logit_softcap = 0.0f; ++}; ++ ++void require(bool condition, const char * message) { ++ if (!condition) { ++ throw std::runtime_error(message); ++ } ++} ++ ++struct inputs { ++ const attention_case spec; ++ const int64_t physical_rows; ++ const int64_t mask_queries; ++ std::vector q; ++ const size_t row_k; ++ const size_t row_v; ++ std::vector k, v, logical_k, logical_v; ++ std::vector mask; ++ std::vector rows; ++ std::array visible_rows{}; ++ std::vector sinks; ++ ++ explicit inputs(attention_case value) : spec(value), physical_rows(2*value.logical_rows + 257), ++ mask_queries((value.queries + 63)/64*64), ++ q(value.dk*value.queries*value.heads*requests), ++ row_k(ggml_row_size(value.type_k, value.dk)), row_v(ggml_row_size(value.type_v, value.dv)), ++ k(row_k*physical_rows*kv_heads), v(row_v*physical_rows*kv_heads), ++ logical_k(row_k*value.logical_rows*kv_heads*requests), ++ logical_v(row_v*value.logical_rows*kv_heads*requests), ++ mask(value.logical_rows*mask_queries*requests), ++ rows(value.logical_rows*requests), sinks(value.heads) { ++ std::mt19937 random(34791); ++ std::uniform_real_distribution sample(-0.75f, 0.75f); ++ for (float & item : q) { ++ item = sample(random); ++ } ++ std::vector values(std::max(value.dk, value.dv)*physical_rows*kv_heads); ++ for (float & item : values) { ++ item = sample(random); ++ } ++ ggml_quantize_chunk(value.type_k, values.data(), k.data(), 0, physical_rows*kv_heads, value.dk, nullptr); ++ for (float & item : values) { ++ item = sample(random); ++ } ++ ggml_quantize_chunk(value.type_v, values.data(), v.data(), 0, physical_rows*kv_heads, value.dv, nullptr); ++ for (float & item : sinks) { ++ item = sample(random); ++ } ++ } ++ ++ void refresh(int phase) { ++ const int64_t width = spec.logical_rows; ++ std::fill(rows.begin(), rows.end(), -1); ++ std::fill(logical_k.begin(), logical_k.end(), 0); ++ std::fill(logical_v.begin(), logical_v.end(), 0); ++ const int epoch = phase % 2; ++ const std::array counts = epoch == 0 ? ++ std::array{0, 31, 65, int32_t(width - 7)} : ++ std::array{65, int32_t(width - 9), 0, 31}; ++ for (int64_t request = 0; request < requests; ++request) { ++ visible_rows[request] = spec.mask ? counts[request] : int32_t(width); ++ for (int32_t slot = 0; slot < visible_rows[request]; ++slot) { ++ // Shared first rows plus interleaved, nonmonotonic physical rows. ++ const int32_t physical = int32_t((slot*37 + (slot < 5 ? 0 : request*53) + epoch*101) % physical_rows); ++ rows[request*width + slot] = physical; ++ } ++ for (int64_t slot = 0; slot < width; ++slot) { ++ const int32_t physical = std::max(0, rows[request*width + slot]); ++ for (int64_t head = 0; head < kv_heads; ++head) { ++ const size_t src = head*physical_rows + physical; ++ const size_t dst = (request*kv_heads + head)*width + slot; ++ // Preserve the exact encoded block bytes, not re-quantized floats. ++ std::copy_n(k.data() + src*row_k, row_k, logical_k.data() + dst*row_k); ++ std::copy_n(v.data() + src*row_v, row_v, logical_v.data() + dst*row_v); ++ } ++ } ++ for (int64_t query = 0; query < mask_queries; ++query) { ++ const int32_t count = std::max(0, visible_rows[request] - (spec.query_local ? int32_t(query % 3) : 0)); ++ for (int64_t slot = 0; slot < width; ++slot) { ++ float bias = -std::numeric_limits::infinity(); ++ if (query < spec.queries && slot < count) { ++ bias = spec.mask ? -0.025f*float(slot % 7) : 0.0f; ++ if (spec.mask && slot % 11 == 3) { ++ bias = -std::numeric_limits::infinity(); ++ } ++ } ++ mask[(request*mask_queries + query)*width + slot] = ggml_fp32_to_fp16(bias); ++ } ++ } ++ } ++ } ++}; ++ ++struct graph_fixture { ++ ggml_context * ctx = nullptr; ++ ggml_backend_buffer_t buffer = nullptr; ++ ggml_tensor * q = nullptr; ++ ggml_tensor * k = nullptr; ++ ggml_tensor * v = nullptr; ++ ggml_tensor * mask = nullptr; ++ ggml_tensor * rows = nullptr; ++ ggml_tensor * sinks = nullptr; ++ ggml_tensor * output = nullptr; ++ ggml_cgraph * graph = nullptr; ++ const bool row_based; ++ ++ graph_fixture(ggml_backend_t backend, const inputs & data, bool use_rows) : row_based(use_rows) { ++ ggml_init_params params{32*ggml_tensor_overhead() + ggml_graph_overhead_custom(32, false), nullptr, true}; ++ ctx = ggml_init(params); ++ require(ctx != nullptr, "allocate graph context"); ++ if (data.spec.strided_query) { ++ auto storage = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, 2*data.spec.queries, data.spec.heads, requests); ++ q = ggml_view_4d(ctx, storage, data.spec.dk, data.spec.queries, data.spec.heads, requests, ++ 2*storage->nb[1], storage->nb[2], storage->nb[3], 0); ++ } else { ++ q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, data.spec.queries, data.spec.heads, requests); ++ } ++ const int64_t storage_rows = row_based ? data.physical_rows : data.spec.logical_rows; ++ const int64_t streams = row_based ? 1 : requests; ++ k = ggml_new_tensor_4d(ctx, data.spec.type_k, data.spec.dk, storage_rows, kv_heads, streams); ++ v = ggml_new_tensor_4d(ctx, data.spec.type_v, data.spec.dv, storage_rows, kv_heads, streams); ++ // The ordinary reference materializes exactly the same row0 padding. ++ if (row_based || data.spec.mask) { ++ mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, data.spec.logical_rows, data.mask_queries, 1, requests); ++ } ++ if (row_based) { ++ rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, data.spec.logical_rows, requests); ++ output = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, ++ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, ++ data.spec.logit_softcap); ++ } else { ++ output = ggml_flash_attn_ext(ctx, q, k, v, mask, ++ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, ++ data.spec.logit_softcap); ++ } ++ if (data.spec.sinks) { ++ sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, data.spec.heads); ++ ggml_flash_attn_ext_add_sinks(output, sinks); ++ } ++ ggml_prec_set_acc(output, GGML_PREC_F32); ++ require(output->src[5] == rows && output->src[6] == nullptr, ++ "row constructor must preserve the src5-only contract"); ++ if (rows) { ++ require(rows->type == GGML_TYPE_I32 && rows->ne[0] == data.spec.logical_rows && ++ rows->ne[1] == requests && rows->ne[2] == 1 && rows->ne[3] == 1, ++ "row constructor must use one physical table per query stream"); ++ } ++ require(ggml_backend_supports_op(backend, output), "selected backend does not support rows test shape"); ++ graph = ggml_new_graph_custom(ctx, 32, false); ++ ggml_build_forward_expand(graph, output); ++ buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); ++ require(buffer != nullptr, "allocate backend graph tensors"); ++ } ++ ++ ~graph_fixture() { ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++ } ++ graph_fixture(const graph_fixture &) = delete; ++ graph_fixture & operator=(const graph_fixture &) = delete; ++ ++ std::vector run(ggml_backend_t backend, const inputs & data) { ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t head = 0; head < data.spec.heads; ++head) { ++ for (int64_t query = 0; query < data.spec.queries; ++query) { ++ const size_t offset = request*q->nb[3] + head*q->nb[2] + query*q->nb[1]; ++ const size_t source = ((request*data.spec.heads + head)*data.spec.queries + query)*data.spec.dk; ++ ggml_backend_tensor_set(q, data.q.data() + source, offset, data.spec.dk*sizeof(float)); ++ } ++ } ++ } ++ ggml_backend_tensor_set(k, row_based ? data.k.data() : data.logical_k.data(), 0, ggml_nbytes(k)); ++ ggml_backend_tensor_set(v, row_based ? data.v.data() : data.logical_v.data(), 0, ggml_nbytes(v)); ++ if (mask) { ++ ggml_backend_tensor_set(mask, data.mask.data(), 0, ggml_nbytes(mask)); ++ } ++ if (rows) { ++ ggml_backend_tensor_set(rows, data.rows.data(), 0, ggml_nbytes(rows)); ++ } ++ if (sinks) { ++ ggml_backend_tensor_set(sinks, data.sinks.data(), 0, ggml_nbytes(sinks)); ++ } ++ require(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS, "compute attention graph"); ++ std::vector result(ggml_nelements(output)); ++ ggml_backend_tensor_get(output, result.data(), 0, ggml_nbytes(output)); ++ return result; ++ } ++}; ++ ++bool exceptional_query(const inputs & data, int64_t request, int64_t query) { ++ if (data.spec.sinks) { return false; } ++ const auto begin = data.mask.begin() + (request*data.mask_queries + query)*data.spec.logical_rows; ++ return std::all_of(begin, begin + data.spec.logical_rows, ++ [](ggml_fp16_t value) { return ggml_fp16_to_fp32(value) == -INFINITY; }); ++} ++ ++int result_class(float value) { ++ if (std::isfinite(value)) { return 0; } ++ if (std::isnan(value)) { return 1; } ++ return std::signbit(value) ? 3 : 2; ++} ++ ++void exceptional_result_control(const std::vector & ordinary, const std::vector & rows, ++ const inputs & data, const char * backend, int phase) { ++ std::array ordinary_classes{}, rows_classes{}; ++ size_t mismatches = 0, elements = 0; ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t query = 0; query < data.spec.queries; ++query) { ++ if (!exceptional_query(data, request, query)) { continue; } ++ const size_t begin = (request*data.spec.queries + query)*data.spec.heads*data.spec.dv; ++ for (size_t i = begin; i < begin + data.spec.heads*data.spec.dv; ++i) { ++ const int left = result_class(ordinary[i]), right = result_class(rows[i]); ++ ++ordinary_classes[left]; ++rows_classes[right]; ++ mismatches += left != right; ++elements; ++ } ++ } ++ } ++ if (!elements) { return; } ++ std::printf("EXCEPTIONAL_RESULT backend=%s phase=%d elements=%zu ordinary_finite_nan_posinf_neginf=%zu,%zu,%zu,%zu rows_finite_nan_posinf_neginf=%zu,%zu,%zu,%zu class_mismatches=%zu no_finite_qualification=1\n", ++ backend, phase, elements, ordinary_classes[0], ordinary_classes[1], ordinary_classes[2], ordinary_classes[3], ++ rows_classes[0], rows_classes[1], rows_classes[2], rows_classes[3], mismatches); ++ require(mismatches == 0, "same-backend all-masked ordinary/rows result classes differ"); ++} ++ ++void compare(const std::vector & expected, const std::vector & actual, ++ const inputs & data, const char * backend, int phase) { ++ double maximum_nmse = 0.0; ++ float max_absolute = 0.0f; ++ const size_t request_elements = data.spec.dv*data.spec.heads*data.spec.queries; ++ std::vector exceptional(requests*data.spec.queries); ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t query = 0; query < data.spec.queries; ++query) { ++ exceptional[request*data.spec.queries + query] = exceptional_query(data, request, query); ++ } ++ } ++ for (int64_t request = 0; request < requests; ++request) { ++ double error = 0.0, energy = 0.0; ++ for (size_t i = request*request_elements; i < (request + 1)*request_elements; ++i) { ++ const int64_t query = (i - request*request_elements) / (data.spec.heads*data.spec.dv); ++ if (exceptional[request*data.spec.queries + query]) { continue; } ++ require(std::isfinite(expected[i]) && std::isfinite(actual[i]), "non-finite attention output"); ++ const double delta = double(expected[i]) - actual[i]; ++ error += delta*delta; ++ energy += double(expected[i])*expected[i]; ++ max_absolute = std::max(max_absolute, float(std::abs(delta))); ++ } ++ if (energy == 0.0) { ++ require(error == 0.0, "zero-energy finite-domain output must remain exact"); ++ } else { ++ maximum_nmse = std::max(maximum_nmse, error/energy); ++ require(error/energy <= max_nmse, "rows attention exceeds existing FA NMSE tolerance"); ++ } ++ } ++ std::printf("PASS finite-domain backend=%s K=%s V=%s dk=%lld dv=%lld heads=%lld bias=%.2f q=%lld logical=%lld mask=%d sinks=%d query_local=%d strided_q=%d softcap=%.2f phase=%d max_request_nmse=%.9g max_abs=%.9g\n", ++ backend, ggml_type_name(data.spec.type_k), ggml_type_name(data.spec.type_v), ++ (long long) data.spec.dk, (long long) data.spec.dv, (long long) data.spec.heads, ++ data.spec.mask ? data.spec.max_bias : 0.0f, (long long) data.spec.queries, (long long) data.spec.logical_rows, ++ data.spec.mask, data.spec.sinks, data.spec.query_local, data.spec.strided_query, ++ data.spec.logit_softcap, phase, maximum_nmse, max_absolute); ++} ++ ++void set_threads(ggml_backend_t backend) { ++ const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)); ++ const auto setter = reinterpret_cast( ++ ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads")); ++ if (setter) { ++ setter(backend, 4); ++ } ++} ++ ++// Accept an exact device (e.g. MTL0/CUDA0) or its registry (Metal/CUDA). ++ggml_backend_t open_backend(const char * name) { ++ if (auto exact = ggml_backend_init_by_name(name, nullptr)) { ++ return exact; ++ } ++ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { ++ auto device = ggml_backend_dev_get(i); ++ const auto registry = ggml_backend_dev_backend_reg(device); ++ if (std::strcmp(ggml_backend_reg_name(registry), name) == 0) { ++ return ggml_backend_dev_init(device, nullptr); ++ } ++ } ++ return nullptr; ++} ++ ++void run_case(ggml_backend_t cpu, ggml_backend_t target, attention_case spec) { ++ inputs data(spec); ++ graph_fixture reference(cpu, data, false); ++ graph_fixture row_based(cpu, data, true); ++ require(reference.output->src[5] == nullptr && reference.output->src[6] == nullptr, ++ "ordinary FA must remain free of row metadata"); ++ if (!spec.mask) { ++ require(reference.mask == nullptr && row_based.mask != nullptr, ++ "ordinary unmasked input and required rows zero-mask metadata are distinct representations"); ++ std::printf("REPRESENTATION ordinary_mask=null rows_mask=explicit_zero logical_values=unmasked\n"); ++ } ++ require(std::memcmp(reference.output->op_params, row_based.output->op_params, ++ sizeof(reference.output->op_params)) == 0, "rows must retain ordinary arithmetic parameters"); ++ std::unique_ptr device; ++ std::unique_ptr device_ordinary; ++ if (target != cpu) { ++ if (ggml_backend_supports_op(target, row_based.output)) { ++ require(ggml_backend_supports_op(target, reference.output), "rows require an ordinary same-backend control"); ++ device = std::make_unique(target, data, true); ++ device_ordinary = std::make_unique(target, data, false); ++ std::printf("ADMISSION rows backend=%s K=%s V=%s dk=%lld dv=%lld q=%lld mask=%d\n", ++ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), ++ (long long) spec.dk, (long long) spec.dv, (long long) spec.queries, spec.mask); ++ } else { ++ const bool dense_supported = ggml_backend_supports_op(target, reference.output); ++ if (dense_supported) { ++ device = std::make_unique(target, data, false); ++ } ++ std::printf("%s backend=%s K=%s V=%s q=%lld mask=%d query_local=%d softcap=%.2f rows_admission=0 ordinary_admission=%d; CPU reference is separate\n", ++ dense_supported ? "FALLBACK ordinary-selected-backend" : "SKIP unsupported-selected-backend", ++ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), ++ (long long) spec.queries, spec.mask, spec.query_local, spec.logit_softcap, dense_supported); ++ } ++ } ++ // Changed row tables and masks must remain visible after graph reuse. ++ for (int phase = 0; phase < 4; ++phase) { ++ data.refresh(phase); ++ const auto expected = reference.run(cpu, data); ++ if (phase == 0) { ++ const auto repeated = reference.run(cpu, data); ++ require(expected.size() == repeated.size(), "ordinary repeat output size"); ++ for (int64_t request = 0; request < requests; ++request) { ++ for (int64_t query = 0; query < spec.queries; ++query) { ++ const size_t begin = (request*spec.queries + query)*spec.heads*spec.dv; ++ const size_t count = spec.heads*spec.dv; ++ if (exceptional_query(data, request, query)) { ++ for (size_t i = begin; i < begin + count; ++i) { ++ require(result_class(expected[i]) == result_class(repeated[i]), "ordinary exceptional repeat class"); ++ } ++ } else { ++ require(std::memcmp(expected.data() + begin, repeated.data() + begin, ++ count*sizeof(float)) == 0, "ordinary finite-domain output must self-repeat exactly"); ++ } ++ } ++ } ++ } ++ const auto cpu_rows = row_based.run(cpu, data); ++ exceptional_result_control(expected, cpu_rows, data, ggml_backend_name(cpu), phase); ++ compare(expected, cpu_rows, data, ggml_backend_name(cpu), phase); ++ if (device) { ++ const auto actual = device->run(target, data); ++ if (device_ordinary && spec.mask && !spec.sinks) { ++ const auto ordinary = device_ordinary->run(target, data); ++ exceptional_result_control(ordinary, actual, data, ggml_backend_name(target), phase); ++ } ++ compare(expected, actual, data, ggml_backend_name(target), phase); ++ } ++ } ++} ++ ++void run_unquantized_vector_cases(ggml_backend_t cpu, ggml_backend_t target) { ++ const std::array types = {GGML_TYPE_F16, GGML_TYPE_BF16}; ++ // Wide GQA must retain the shared hardware policy rather than force vec. ++ for (auto type_k : types) { ++ for (auto type_v : types) { ++ for (int64_t queries : {1, 2}) { ++ run_case(cpu, target, {queries, 256, true, false, false, false, ++ type_k, type_v, 256, 256, 0.0f, 16}); ++ } ++ } ++ } ++ for (int64_t dimension : {64, 128, 256}) { ++ for (auto type_k : types) { ++ for (auto type_v : types) { ++ for (int64_t queries : {1, 2}) { ++ if (dimension != 256) { ++ run_case(cpu, target, {queries, 256, true, true, false, false, ++ type_k, type_v, dimension, dimension}); ++ } ++ run_case(cpu, target, {queries, 256, false, false, false, false, ++ type_k, type_v, dimension, dimension}); ++ if (dimension != 64) { ++ run_case(cpu, target, {queries, 256, true, true, false, false, ++ type_k, type_v, dimension, dimension, 0.0f, 8, 4.0f}); ++ } ++ } ++ } ++ } ++ } ++ run_case(cpu, target, {2, 256, true, true, false, true, ++ GGML_TYPE_F16, GGML_TYPE_BF16, 128, 128}); ++} ++ ++void run_softcap_capability_cases(ggml_backend_t cpu, ggml_backend_t target) { ++ const auto registry = ggml_backend_dev_backend_reg(ggml_backend_get_device(target)); ++ const bool cuda = std::strcmp(ggml_backend_reg_name(registry), "CUDA") == 0; ++ for (auto type_k : {GGML_TYPE_F16, GGML_TYPE_BF16}) { ++ for (auto type_v : {GGML_TYPE_F16, GGML_TYPE_BF16}) { ++ for (int64_t queries : {1, 2}) { ++ attention_case spec{queries, 256, true, true, false, false, ++ type_k, type_v, 64, 64, 0.0f, 8, 4.0f}; ++ if (cuda) { ++ inputs data(spec); ++ graph_fixture dense(cpu, data, false); ++ graph_fixture row_based(cpu, data, true); ++ require(!ggml_backend_supports_op(target, dense.output) && ++ !ggml_backend_supports_op(target, row_based.output), ++ "CUDA must refuse head64 softcap without a compiled kernel"); ++ std::printf("PASS CUDA admission refuses unsupported softcap K=%s V=%s dk=64 q=%lld\n", ++ ggml_type_name(type_k), ggml_type_name(type_v), (long long) queries); ++ } ++ // CPU reference coverage is separate; a CUDA skip is not a GPU pass. ++ run_case(cpu, target, spec); ++ } ++ } ++ } ++ const std::array, 5> shapes = {{{192, 128, 16}, ++ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; ++ for (const auto & shape : shapes) { ++ for (auto type : {GGML_TYPE_F16, GGML_TYPE_BF16}) { ++ for (int64_t queries : {1, 2}) { ++ run_case(cpu, target, {queries, 256, true, true, false, false, ++ type, type, shape[0], shape[1], 0.0f, shape[2], 4.0f}); ++ } ++ } ++ } ++} ++} // namespace ++ ++int main(int argc, char ** argv) { ++ try { ++ require(argc == 1 || (argc == 3 && std::strcmp(argv[1], "--backend") == 0), ++ "usage: test-flash-attn-rows [--backend DEVICE_NAME]"); ++ ggml_backend_load_all(); ++ using backend_ptr = std::unique_ptr; ++ backend_ptr cpu(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr), ggml_backend_free); ++ require(cpu != nullptr, "CPU reference backend unavailable"); ++ set_threads(cpu.get()); ++ backend_ptr selected(nullptr, ggml_backend_free); ++ if (argc == 3) { ++ selected.reset(open_backend(argv[2])); ++ require(selected != nullptr, "requested backend unavailable"); ++ } else { ++ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)); ++ if (!selected) { ++ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr)); ++ } ++ } ++ const bool selected_cpu = selected && ++ ggml_backend_dev_type(ggml_backend_get_device(selected.get())) == GGML_BACKEND_DEVICE_TYPE_CPU; ++ auto target = selected && !selected_cpu ? selected.get() : cpu.get(); ++ std::printf("rows FA: CPU reference and target=%s; per-request NMSE limit=%.9g\n", ggml_backend_name(target), max_nmse); ++ for (int64_t queries : {1, 2, 4, 31, 32, 64}) { ++ run_case(cpu.get(), target, {queries, 256, true, true}); ++ } ++ run_case(cpu.get(), target, {1, 4352, true, true}); ++ run_case(cpu.get(), target, {4, 256, false, false}); ++ run_case(cpu.get(), target, {31, 256, true, false, true}); ++ run_case(cpu.get(), target, {32, 256, true, true, false, true}); ++ const std::array types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, ++ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}; ++ for (auto type_k : types) { ++ for (auto type_v : types) { ++ for (int64_t queries : {1, 2, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, type_k, type_v}); ++ } ++ } ++ } ++ run_unquantized_vector_cases(cpu.get(), target); ++ run_softcap_capability_cases(cpu.get(), target); ++ const std::array, 13> head_shapes = {{{32, 32}, {64, 64}, {96, 96}, ++ {96, 64}, {128, 128}, {128, 96}, {192, 192}, {192, 128}, {256, 256}, ++ {320, 256}, {512, 512}, {576, 512}, {128, 64}}}; ++ for (const auto & dimensions : head_shapes) { ++ for (auto type : types) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimensions[0], dimensions[1]}); ++ } ++ } ++ } ++ // CUDA's larger-head kernels require zero ALiBi and admitted GQA tile ratios. ++ const std::array, 5> wide_shapes = {{{192, 128, 16}, ++ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; ++ for (const auto & dimensions : wide_shapes) { ++ for (auto type : types) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimensions[0], dimensions[1], 0.0f, dimensions[2]}); ++ } ++ } ++ } ++ for (int64_t dimension : {40, 48, 72, 80, 112}) { ++ for (auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { ++ for (int64_t queries : {1, 32}) { ++ run_case(cpu.get(), target, {queries, 256, true, true, false, false, ++ type, type, dimension, dimension}); ++ } ++ } ++ } ++ return 0; ++ } catch (const std::exception & error) { ++ std::fprintf(stderr, "rows FA test failed: %s\n", error.what()); ++ return 1; ++ } ++} diff --git a/tests/test-graph-contract-fixture.h b/tests/test-graph-contract-fixture.h new file mode 100644 index 000000000..c45915888 @@ -10306,29 +11285,127 @@ index 000000000..b15b5e53a +} diff --git a/tests/test-skippy-kv-cells-contiguous.cpp b/tests/test-skippy-kv-cells-contiguous.cpp new file mode 100644 -index 000000000..0e95c35b2 +index 000000000..d922e73c0 --- /dev/null +++ b/tests/test-skippy-kv-cells-contiguous.cpp -@@ -0,0 +1,20 @@ +@@ -0,0 +1,118 @@ +#include "../src/llama-kv-cells.h" + -+int main() { ++#include ++#include ++#include ++#include ++ ++namespace { ++void check(bool pass, const char * reason) { ++ if (!pass) { throw std::runtime_error(reason); } ++} ++ ++void check_rows(const llama_kv_cells & cells) { ++ const std::vector owners = {0, 1, 2, 3, 4}; ++ const std::vector minima = {0, 2, 4, 1, 0}; ++ for (int cutoff : {0, 1, 2}) { ++ const auto minimum = cutoff == 0 ? std::vector{} : ++ cutoff == 1 ? minima : std::vector(owners.size(), -100); ++ std::vector actual(cells.size() * owners.size(), -2); ++ cells.get_seq_cells(owners, minimum, actual.data(), cells.size()); ++ for (size_t s = 0; s < owners.size(); ++s) { ++ std::vector expected; ++ std::set> positions; ++ for (uint32_t i = 0; i < cells.size(); ++i) { ++ if (cells.is_empty(i) || !cells.seq_has(i, owners[s])) { continue; } ++ positions.emplace(cells.pos_get(i), i); ++ if (minimum.empty() || cells.pos_get(i) >= minimum[s]) { expected.push_back(i); } ++ } ++ check(positions == cells.seq_pos_get(owners[s]), "logical position index differs from physical owners"); ++ expected.resize(cells.size(), -1); ++ check(std::equal(expected.begin(), expected.end(), actual.begin() + s*cells.size()), ++ "row bitmap differs from physical-order owner scan or padding"); ++ } ++ } ++} ++ ++void contiguous_positions() { + llama_kv_cells cells; + cells.resize(8); + for (uint32_t i = 0; i < 4; ++i) { + cells.pos_set(i, static_cast(i)); + cells.seq_add(i, 0); + } -+ if (!cells.seq_pos_is_cell_contiguous(0)) return 1; -+ ++ check(cells.seq_pos_is_cell_contiguous(0), "dense prefix must remain resident-admissible"); ++ check_rows(cells); + cells.mv(1, 4); -+ if (cells.seq_pos_is_cell_contiguous(0)) return 2; ++ check(!cells.seq_pos_is_cell_contiguous(0), "moved prefix must not appear physically contiguous"); ++ check_rows(cells); + cells.mv(4, 1); -+ if (!cells.seq_pos_is_cell_contiguous(0)) return 3; ++ check(cells.seq_pos_is_cell_contiguous(0), "restored physical prefix must regain admission"); ++ check(cells.seq_rm(2, 0) && cells.is_empty(2), "removed sole owner must clear cell"); ++ check(!cells.seq_pos_is_cell_contiguous(0), "prefix hole must reject complete-prefix admission"); ++ check_rows(cells); ++} + -+ if (!cells.seq_rm(2, 0)) return 4; -+ if (cells.seq_pos_is_cell_contiguous(0)) return 5; -+ return 0; ++void shared_ownership_and_restore() { ++ llama_kv_cells cells; ++ cells.resize(192); ++ for (uint32_t i = 0; i < 8; ++i) { ++ cells.pos_set(i, i); ++ for (llama_seq_id owner = 0; owner < 5; ++owner) { cells.seq_add(i, owner); } ++ } ++ for (const auto & item : {std::pair{130, 8}, {63, 10}, {64, 9}}) { ++ cells.pos_set(item.first, item.second); ++ cells.seq_add(item.first, 1); ++ } ++ check(!cells.seq_pos_is_cell_contiguous(1), "scattered tail must reject contiguous resident admission"); ++ check(cells.seq_pos_is_cell_contiguous(4), "parked alias must retain complete prefix admission"); ++ check_rows(cells); ++ for (uint32_t i = 0; i < 8; ++i) { ++ check(!cells.seq_rm(i, 0), "removing one alias must preserve shared cell"); ++ } ++ check_rows(cells); ++ cells.pos_set(191, 40); cells.seq_add(191, 0); ++ cells.rm(191); ++ cells.pos_set(191, 0); cells.seq_add(191, 0); ++ check_rows(cells); ++ cells.mv(64, 65); ++ cells.pos_add(63, 7); ++ cells.pos_div(130, 2); ++ check_rows(cells); ++ check(cells.seq_pos_is_cell_contiguous(4), "other owners' shifts must not invalidate parked prefix"); ++ cells.reset_shift(); ++ const auto sparse = cells.cp(std::vector{130, 65, 0, 191}); ++ const auto contiguous = cells.cp(0, 8); ++ llama_kv_cells restored; ++ restored.resize(192); ++ restored.set(std::vector{64, 127, 129, 190}, sparse); ++ check_rows(restored); ++ restored.set(0, contiguous); ++ check_rows(restored); ++ llama_kv_cells empty; empty.resize(1); ++ restored.set(64, empty); ++ check_rows(restored); ++ check(!cells.seq_keep(0, 4), "keeping parked alias must retain its shared payload"); ++ check(cells.seq_keep(65, 4), "keeping absent alias must clear its cell"); ++ check(cells.seq_pos_is_cell_contiguous(4) && !cells.seq_pos_is_cell_contiguous(1), ++ "keeping a shared owner must update each resident prefix index"); ++ check_rows(cells); ++ check(cells.pos_add(191, -1), "negative logical shift must remove recycled row"); ++ check_rows(cells); ++ cells.reset(); check_rows(cells); ++ cells.resize(65); check_rows(cells); ++ cells.pos_set(64, 0); cells.seq_add(64, 4); check_rows(cells); ++ cells.resize(8); check_rows(cells); ++} ++} // namespace ++ ++int main() { ++ try { ++ contiguous_positions(); ++ shared_ownership_and_restore(); ++ return 0; ++ } catch (const std::exception & error) { ++ std::fprintf(stderr, "KV cell ownership test failed: %s\n", error.what()); ++ return 1; ++ } +} diff --git a/tests/test-skippy-kv-page-export.cpp b/tests/test-skippy-kv-page-export.cpp new file mode 100644 diff --git a/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch b/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch index 4dc41fd716..57b1e2eeff 100644 --- a/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch +++ b/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch @@ -220,10 +220,10 @@ index d8276944d..3a147d14d 100644 + skippy_native_mtp_draft * out_mtp_draft, + skippy_error ** out_error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index f035ea13f..15c48419d 100644 +index cf0838051..b2f394444 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp -@@ -852,7 +852,7 @@ enum skippy_status skippy_trim_session( +@@ -733,7 +733,7 @@ enum skippy_status skippy_trim_session( if (session->signal_history.size() > token_count) { session->signal_history.resize(static_cast(token_count)); } diff --git a/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch b/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch index 80935de3e1..ad2b45ebad 100644 --- a/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch +++ b/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch @@ -23,10 +23,10 @@ resets, instead of attaching rebuilt chains to the backend. 5 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index 38ebae8d7..f44e874d9 100644 +index ba072fe82..db3392ddf 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -158,6 +158,11 @@ struct skippy_session { +@@ -165,6 +165,11 @@ struct skippy_session { // detached -- e.g. so a sampled verify window can output every row -- // it must never be re-attached; only building a fresh chain clears this. bool sampling_backend_retired = false; @@ -61,10 +61,10 @@ index 6fd1240e3..de5fa6ba5 100644 // scheduler may reset and reuse the same chain on every iteration; // attaching it again violates llama_sampler_chain's one-shot init diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index f1de95cc5..36c972d92 100644 +index be612007f..0653347a7 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -392,6 +392,7 @@ enum skippy_status skippy_session_reset( +@@ -389,6 +389,7 @@ enum skippy_status skippy_session_reset( skippy_clear_chat_sampling(session); } skippy_mtp_clear_session_state(session); diff --git a/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch b/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch index c6ffd15514..1a4bb67da3 100644 --- a/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch +++ b/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch @@ -37,7 +37,7 @@ index b9b5259af..df831c43e 100644 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index 799bdca2d..bc4da9a07 100644 +index b47c55f82..c930d9c3b 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -117,6 +117,12 @@ struct skippy_runtime_config { @@ -132,7 +132,7 @@ index 554d2bdd3..e3649e713 100644 const skippy_runtime_config * config, llama_context_params & params); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 60a27669f..7305cc529 100644 +index d6e24cd2a..4082fa198 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -962,10 +962,12 @@ enum skippy_status skippy_model_open_impl( diff --git a/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch b/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch index 478cabc824..9fb10f9a8a 100644 --- a/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch +++ b/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch @@ -5,14 +5,13 @@ Subject: [PATCH 13/15] fix(skippy): take the argmax path for temperature-0 chains that can only pick the top logit --- - src/CMakeLists.txt | 3 +- - src/skippy/chat_sampling.cpp | 43 ++++++++ - src/skippy/runtime_types.h | 4 + - src/skippy/sampling.cpp | 2 + - src/skippy/sampling_argmax.cpp | 136 ++++++++++++++++++++++++++ - src/skippy/sampling_argmax.h | 42 ++++++++ - src/skippy/tests/sampling_history.cpp | 110 ++++++++++++++++++++- - 7 files changed, 338 insertions(+), 2 deletions(-) + src/CMakeLists.txt | 3 +- + src/skippy/chat_sampling.cpp | 43 +++++++++++ + src/skippy/runtime_types.h | 4 + + src/skippy/sampling.cpp | 2 + + src/skippy/sampling_argmax.cpp | 136 +++++++++++++++++++++++++++++++++ + src/skippy/sampling_argmax.h | 42 ++++++++++ + 6 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 src/skippy/sampling_argmax.cpp create mode 100644 src/skippy/sampling_argmax.h @@ -20,7 +19,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c7a99d16c..cd2b536f6 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -50,6 +50,7 @@ add_library(llama +@@ -53,6 +53,7 @@ add_library(llama ${LLAMA_CORE_SOURCES} skippy/activation.cpp skippy/activation_layout.cpp @@ -32,8 +31,8 @@ index c7a99d16c..cd2b536f6 100644 target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) target_link_libraries(skippy-sampling-history PRIVATE llama) function(add_skippy_sampling_history_tests family fixture state) -- foreach(mode grammar penalty) -+ foreach(mode grammar penalty argmax) +- foreach(mode grammar penalty resident) ++ foreach(mode grammar penalty resident argmax) add_test(NAME skippy_sampling_history_${family}_${mode} COMMAND skippy-sampling-history "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) @@ -117,7 +116,7 @@ index f44e874d9..46e907aa0 100644 #include "../llama-context.h" #include "../llama-model.h" -@@ -165,6 +166,9 @@ struct skippy_session { +@@ -172,6 +173,9 @@ struct skippy_session { bool sampling_backend_verifying = false; uint64_t sampling_reuse_hit_count = 0; uint64_t sampling_rebuild_count = 0; @@ -337,154 +336,6 @@ index 000000000..d06000f11 + const float * logits, + int32_t n_vocab, + const skippy_argmax_plan & plan); -diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 9e134586f..4100856f3 100644 ---- a/src/skippy/tests/sampling_history.cpp -+++ b/src/skippy/tests/sampling_history.cpp -@@ -1,5 +1,7 @@ - #include "skippy.h" - #include "../runtime_types.h" -+#include "../sampling_internal.h" -+#include "../sampling_argmax.h" - #include "../runtime_support.h" - #include "llama-model.h" - #include "../../../common/sampling.h" -@@ -287,6 +289,108 @@ void penalty_restore(skippy_model * model, bool full) { - release(restored); - } - -+// Temperature 0 with the defaults and sampler order the serving layer sends. -+skippy_sampling_config temperature_zero_config() { -+ skippy_sampling_config config{}; -+ config.version = 1; -+ config.flags = SKIPPY_SAMPLING_FLAG_ENABLED; -+ config.temperature = 0.0f; -+ config.top_k = 40; -+ config.top_p = 0.95f; -+ config.min_p = 0.05f; -+ config.typical_p = 1.0f; -+ config.top_nsigma = -1.0f; -+ config.dynatemp_exponent = 1.0f; -+ config.repeat_penalty = 1.0f; -+ config.penalty_last_n = 64; -+ config.dry_base = 1.75f; -+ config.dry_allowed_length = 2; -+ config.dry_penalty_last_n = 64; -+ config.xtc_threshold = 0.1f; -+ config.mirostat_entropy = 5.0f; -+ config.mirostat_learning_rate = 0.1f; -+ config.reasoning_budget_tokens = -1; -+ config.sampler_count = 9; -+ for (uint32_t i = 0; i < config.sampler_count; ++i) { -+ config.samplers[i] = i + 1; -+ } -+ return config; -+} -+ -+// The token a freshly built chain selects from the row the last decode sampled. -+llama_token full_chain_token(skippy_session * session) { -+ auto * reference = common_sampler_clone(session->sampler); -+ CHECK(reference != nullptr); -+ common_sampler_reset(reference); -+ for (const llama_token token : session->token_history) { -+ common_sampler_accept(reference, token, true); -+ } -+ const auto token = common_sampler_sample(reference, session->ctx, -1); -+ CHECK(common_sampler_last(session->sampler) == session->token_history.back()); -+ CHECK(session->sampling_accepted_token_count == session->token_history.size()); -+ common_sampler_free(reference); -+ return token; -+} -+ -+// Count the decodes that took the argmax path and check each against the full chain. -+uint64_t argmax_decodes(skippy_model * model, const skippy_sampling_config & sampling, -+ std::vector * predicted) { -+ auto * session = create(model); -+ prefill(session, {1, 2, 3, 4, 5, 6, 7, 8}); -+ const uint64_t before = session->sampling_argmax_count; -+ llama_token previous = 9; -+ for (int step = 0; step < 6; ++step) { -+ previous = decode(session, sampling, previous); -+ CHECK(previous == full_chain_token(session)); -+ predicted->push_back(previous); -+ } -+ const uint64_t taken = session->sampling_argmax_count - before; -+ release(session); -+ return taken; -+} -+ -+void argmax_path(skippy_model * model) { -+ // Repeated biases apply in order to the original logit, without pre-summing. -+ skippy_argmax_plan plan; -+ skippy_prepare_argmax_plan(&plan, {{0, -1e20f}, {1, 0.0f}, {0, 1.0f}, {-1, 4.0f}}, 2); -+ const float logits[] = {1e20f, 0.5f}; -+ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); -+ skippy_prepare_argmax_plan(&plan, {}, 2); -+ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); -+ -+ // Each request can only select the top biased logit, so it must not run the full chain. -+ auto ignore_eos = temperature_zero_config(); -+ ignore_eos.flags |= SKIPPY_SAMPLING_FLAG_IGNORE_EOS; -+ ignore_eos.ignore_eos = 1; -+ auto logit_bias = temperature_zero_config(); -+ logit_bias.logit_bias_count = 2; -+ logit_bias.logit_bias[0] = {7, -3.0f}; -+ logit_bias.logit_bias[1] = {9, 2.5f}; -+ auto inert_penalties = temperature_zero_config(); -+ inert_penalties.presence_penalty = 0.5f; -+ inert_penalties.frequency_penalty = 0.5f; -+ inert_penalties.penalty_last_n = 0; -+ for (const auto & sampling : {ignore_eos, logit_bias, inert_penalties}) { -+ std::vector predicted; -+ const uint64_t taken = argmax_decodes(model, sampling, &predicted); -+ if (taken != predicted.size()) { -+ std::fprintf(stderr, "argmax path taken for %llu of %zu temperature-0 decodes\n", -+ static_cast(taken), predicted.size()); -+ } -+ CHECK(taken == predicted.size()); -+ } -+ -+ // Equal biased maxima keep the full chain's tie order. -+ auto tie = temperature_zero_config(); -+ tie.logit_bias_count = 2; -+ tie.logit_bias[0] = {3, 1e30f}; -+ tie.logit_bias[1] = {5, 1e30f}; -+ std::vector predicted; -+ CHECK(argmax_decodes(model, tie, &predicted) == 0); -+ for (const llama_token token : predicted) { -+ CHECK(token == 3 || token == 5); -+ } -+} - - int32_t stage_layers(skippy_session * session) { - return session->stage_model->model->hparams.n_layer(); -@@ -441,6 +545,7 @@ void adapter_contracts(skippy_model * model) { - error = nullptr; - - config = sampling_config(); -+ config.temperature = 0.8f; - config.ignore_eos = 1; - config.logit_bias_count = 3; - const auto * vocab = llama_model_get_vocab(model->model); -@@ -476,7 +581,8 @@ int main(int argc, char ** argv) { - CHECK(argc == 4); - const bool grammar = std::strcmp(argv[2], "grammar") == 0; - const bool state = std::strcmp(argv[2], "state") == 0; -- CHECK(grammar || state || std::strcmp(argv[2], "penalty") == 0); -+ const bool argmax = std::strcmp(argv[2], "argmax") == 0; -+ CHECK(grammar || state || argmax || std::strcmp(argv[2], "penalty") == 0); - CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); - require_recurrent = std::strcmp(argv[3], "recurrent") == 0; - auto config = skippy_runtime_config_default(); -@@ -491,6 +597,8 @@ int main(int argc, char ** argv) { - // partial side payload is intentionally empty there. - CHECK(require_recurrent); - state_round_trip(model); -+ } else if (argmax) { -+ argmax_path(model); - } else { - for (const bool full : {false, true}) { - if (grammar) { -- 2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch b/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch index d2ca5b97ab..73a2778aa1 100644 --- a/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch +++ b/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch @@ -23,7 +23,7 @@ backend-sampling output limit is restored. 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index bc4da9a07..b570682ef 100644 +index c930d9c3b..856c98f97 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -123,6 +123,10 @@ struct skippy_runtime_config { @@ -56,10 +56,10 @@ index c9a0a226b..3257d7f2c 100644 } } diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 7305cc529..db5a69e38 100644 +index 4082fa198..5bfd47c93 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp -@@ -733,7 +733,13 @@ enum skippy_status skippy_finish_model_open( +@@ -734,7 +734,13 @@ enum skippy_status skippy_finish_model_open( } if (llm_arch_is_recurrent(model->arch) || llm_arch_is_hybrid(model->arch)) { params.n_seq_max = std::max(params.n_seq_max, std::max(2, stage_model->lane_count * 2)); @@ -90,10 +90,10 @@ index 6a1352271..b688fce73 100644 session->sampling_config_valid = false; session->chat_sampling_metadata.clear(); diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 36c972d92..4741f55cb 100644 +index 0653347a7..40110a816 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -390,6 +390,7 @@ enum skippy_status skippy_session_reset( +@@ -387,6 +387,7 @@ enum skippy_status skippy_session_reset( skippy_env_enabled("SKIPPY_DETACH_SAMPLER_ON_RESET"); if (detach_sampler_on_reset || !skippy_reset_reusable_sampling(session)) { skippy_clear_chat_sampling(session); diff --git a/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch b/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch index 9deca54db5..9208e0642f 100644 --- a/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch +++ b/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch @@ -76,10 +76,10 @@ index df831c43e..3448095a1 100644 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/state.h b/include/skippy/state.h -index 1cfaaa5c6..e8d0874a1 100644 +index 0fe373d78..6d9028a18 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h -@@ -173,6 +173,21 @@ LLAMA_API enum skippy_status skippy_retire_verify_checkpoint( +@@ -177,6 +177,21 @@ LLAMA_API enum skippy_status skippy_retire_verify_checkpoint( uint64_t token_count, struct skippy_error ** out_error); @@ -105,7 +105,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cd2b536f6..4f4fc1cd1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -59,6 +59,7 @@ add_library(llama +@@ -62,6 +62,7 @@ add_library(llama skippy/model_source.cpp skippy/session.cpp skippy/verification.cpp @@ -137,7 +137,7 @@ index cd2b536f6..4f4fc1cd1 100644 + add_skippy_verify_rollback_test(qwen4exp qwen4exp-moe.gguf) + # lfm2's fixture slides its attention window, so it checkpoints every window. + add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) - add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) + add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) target_include_directories(skippy-sampling-history PRIVATE .) target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) diff --git a/src/skippy-verify-checkpoint.h b/src/skippy-verify-checkpoint.h @@ -497,7 +497,7 @@ diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h index 46e907aa0..ec9fb94b1 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -121,6 +121,11 @@ struct skippy_verify_checkpoint { +@@ -130,6 +130,11 @@ struct skippy_verify_checkpoint { bool valid = false; int32_t token_start = 0; size_t token_count = 0; @@ -509,7 +509,7 @@ index 46e907aa0..ec9fb94b1 100644 std::vector state; std::vector token_ids; bool has_activation_input = false; -@@ -194,4 +199,16 @@ struct skippy_session { +@@ -201,4 +206,16 @@ struct skippy_session { std::vector pending_activation_exports; bool reset_required = false; std::vector verify_checkpoints; @@ -572,76 +572,20 @@ index 4741f55cb..9d0ba6ee5 100644 SKIPPY_RUNTIME_EVENT_KIND_KV_PRESSURE_CLEARED, static_cast(session->seq_id), diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index 15c48419d..45a53c4ba 100644 +index b2f394444..57b9eea4e 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp -@@ -74,7 +74,7 @@ static void skippy_update_session_state_after_import( - session->signal_history.resize(static_cast(session->n_past)); - } - skippy_mtp_clear_session_state(session); -- session->verify_checkpoints.clear(); -+ skippy_clear_verify_windows(session); - } - - static enum skippy_status skippy_imported_session_position( -@@ -646,7 +646,7 @@ enum skippy_status skippy_import_kv_page( - } - session->n_past = std::max(session->n_past, static_cast(std::min(desc->token_start + desc->token_count, std::numeric_limits::max()))); - skippy_mtp_clear_session_state(session); -- session->verify_checkpoints.clear(); -+ skippy_clear_verify_windows(session); - session->ctx->synchronize(); - return skippy_success(out_error); - } -@@ -742,7 +742,7 @@ enum skippy_status skippy_import_cachegen_kv_page_v1(struct skippy_session * - static_cast(std::min(desc->token_start + desc->token_count, - std::numeric_limits::max()))); - skippy_mtp_clear_session_state(session); -- session->verify_checkpoints.clear(); -+ skippy_clear_verify_windows(session); - session->ctx->synchronize(); - return skippy_success(out_error); - } -@@ -759,17 +759,28 @@ enum skippy_status skippy_retire_verify_checkpoint( - if (!skippy_memory_needs_verify_checkpoint(session->ctx->get_memory())) { - return skippy_success(out_error); - } -- // No checkpoint is taken when the span rolls back in place, so there is -- // nothing to retire. -- if (skippy_verify_window_can_roll_back_in_place(session, static_cast(token_count))) { -+ skippy_verify_checkpoint & inplace = session->inplace_verify_window; -+ if (inplace.valid && static_cast(inplace.token_start) == token_start && -+ inplace.token_count == token_count) { -+ inplace.valid = false; -+ ++session->verify_windows_in_place; - return skippy_success(out_error); - } -- if (!skippy_retire_verify_checkpoint_exact( -- session->verify_checkpoints, token_start, token_count)) { -- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "verify-window checkpoint was not found"); -- return SKIPPY_STATUS_INVALID_ARGUMENT; -+ skippy_verify_checkpoint retired; -+ if (skippy_retire_verify_checkpoint_exact( -+ session->verify_checkpoints, token_start, token_count, &retired)) { -+ if (session->verify_checkpoint_pool.size() < 2) { -+ session->verify_checkpoint_pool.push_back(std::move(retired)); -+ } -+ return skippy_success(out_error); +@@ -726,8 +726,11 @@ enum skippy_status skippy_trim_session( + } } -- return skippy_success(out_error); -+ // A window that could roll back in place may have taken no checkpoint -+ // at all, so there is nothing to retire. -+ if (skippy_verify_window_can_roll_back_in_place(session, static_cast(token_count))) { -+ return skippy_success(out_error); + session->n_past = static_cast(token_count); +- if (session->token_history.size() > token_count) { ++ const bool history_truncated = session->token_history.size() > token_count; ++ if (history_truncated) { + session->token_history.resize(static_cast(token_count)); + } -+ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "verify-window checkpoint was not found"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; - } - - enum skippy_status skippy_trim_session( -@@ -799,6 +810,25 @@ enum skippy_status skippy_trim_session( - skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); - return SKIPPY_STATUS_RUNTIME_ERROR; ++ if (history_truncated || session->sampling_accepted_token_count > token_count) { + skippy_clear_chat_sampling(session); } + // A window held in place rewinds through seq_rm below, to any row after + // its first. Its first row is the committed token the window started diff --git a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch index 7daca3241a..07c5bb0078 100644 --- a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch @@ -121,7 +121,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4f4fc1cd1..d3c86694f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -94,6 +94,7 @@ add_library(llama +@@ -98,6 +98,7 @@ add_library(llama skippy/speculative_decoding.cpp skippy/tokenization.cpp skippy/events.cpp diff --git a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch index aafbc5288d..2a806ebd0a 100644 --- a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch +++ b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch @@ -267,7 +267,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d3c86694f..db01bc2f5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -95,6 +95,8 @@ add_library(llama +@@ -99,6 +99,8 @@ add_library(llama skippy/tokenization.cpp skippy/events.cpp skippy/system_one.cpp @@ -276,7 +276,7 @@ index d3c86694f..db01bc2f5 100644 unicode.h ${LLAMA_MODELS_SOURCES} ) -@@ -123,7 +125,7 @@ set_source_files_properties(${LLAMA_MODELS_SOURCES} +@@ -127,7 +129,7 @@ set_source_files_properties(${LLAMA_MODELS_SOURCES} configure_file(llama-version.h.in ${CMAKE_CURRENT_BINARY_DIR}/llama-version.h @ONLY) diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index 22ad6fa18f..898ad958a4 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -241,7 +241,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index eab1c3a46..ea0cdd178 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -97,6 +97,7 @@ add_library(llama +@@ -101,6 +101,7 @@ add_library(llama skippy/system_one.cpp skippy/laya.cpp ../tools/laya/laya.cpp @@ -249,7 +249,7 @@ index eab1c3a46..ea0cdd178 100644 unicode.h ${LLAMA_MODELS_SOURCES} ) -@@ -123,6 +124,10 @@ set_source_files_properties(${LLAMA_CORE_SOURCES} ../include/llama.h unicode.h . +@@ -127,6 +128,10 @@ set_source_files_properties(${LLAMA_CORE_SOURCES} ../include/llama.h unicode.h . set_source_files_properties(${LLAMA_MODELS_SOURCES} PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 885c560641..7fa4eb13e8 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -147,7 +147,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ea0cdd178..beded64e4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -84,6 +84,7 @@ add_library(llama +@@ -87,6 +87,7 @@ add_library(llama skippy/sampling_config.cpp skippy/chat_sampling.cpp skippy/sampling_vocab.cpp @@ -271,8 +271,8 @@ diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h index ec9fb94b1..cd8a82f7a 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -146,6 +146,8 @@ struct skippy_session { - int32_t preserve_prefix_tokens = 0; +@@ -153,6 +153,8 @@ struct skippy_session { + int32_t borrowed_prefix_tokens = 0; std::vector token_history; std::vector signal_history; + // Recorded by sampling with SKIPPY_SAMPLING_FLAG_LOGPROBS until the caller takes them. @@ -351,7 +351,7 @@ index 7bbf16016..81bc26ff5 100644 skippy_session * session, const llama_token * token_ids, diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index a9251d2c9..13e318534 100644 +index 1e6cf90e1..bc86d41d7 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp @@ -376,6 +376,7 @@ enum skippy_status skippy_session_reset( @@ -362,18 +362,6 @@ index a9251d2c9..13e318534 100644 // Keep a reusable backend sampler attached across reset. Detaching it // makes the next sampled decode reattach the chain and mark the scheduler // for reserve, which rebuilds compute buffers at every request boundary. -diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index 45a53c4ba..1f2e58a37 100644 ---- a/src/skippy/state.cpp -+++ b/src/skippy/state.cpp -@@ -1037,6 +1037,7 @@ enum skippy_status skippy_session_restore_prefix( - session->token_history.assign(token_ids, token_ids + token_count); - } - session->signal_history.clear(); -+ session->token_logprobs.clear(); - skippy_mtp_clear_session_state(session); - skippy_clear_verify_windows(session); - return skippy_success(out_error); diff --git a/src/skippy/workloads.cpp b/src/skippy/workloads.cpp index d3de66cbe..3ca967bf3 100644 --- a/src/skippy/workloads.cpp diff --git a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch index 894d1b02b9..0da41413d3 100644 --- a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch +++ b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch @@ -39,7 +39,7 @@ index beded64e4..0e619d785 100644 # lfm2's fixture slides its attention window, so it checkpoints every window. add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) + add_skippy_verify_rollback_test(glm5-next glm5-next-moe.gguf) - add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) + add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) target_include_directories(skippy-sampling-history PRIVATE .) target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp diff --git a/tools/xtask/src/automation/agentx/container.rs b/tools/xtask/src/automation/agentx/container.rs deleted file mode 100644 index c9276bc0b8..0000000000 --- a/tools/xtask/src/automation/agentx/container.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! Own the Docker daemon's container as well as its attached client process. -use super::{Engine, Model, Profile, command, inputs, write}; -use crate::{command::DynResult, process}; -use serde_json::{Value, json}; -use std::path::{Path, PathBuf}; - -struct Launch { - root: PathBuf, - output: PathBuf, - artifacts: PathBuf, - hf_home: PathBuf, - commit: String, - name: String, - seconds: u64, -} - -pub(super) fn run(engine: Engine, model: &str, profile: Profile, output: PathBuf) -> DynResult<()> { - let launch = prepare(output, model)?; - let image = inspect(&launch)?; - let args = create_args(&launch, &image, engine, model, profile)?; - let spec = command::spec(&launch.root, "docker", &args)?; - if let Err(error) = command::run(&spec, 60, &launch.output.join("container-create")) { - // Creation can succeed at the daemon just as the attached client is cancelled. - let _ = remove(&launch); - return Err(error); - } - let interrupt = match crate::automation::command_interrupt::Interrupt::install() { - Ok(interrupt) => interrupt, - Err(error) => { - remove(&launch)?; - return Err(error.into()); - } - }; - let result = attached(&launch, &interrupt.cancellation()); - // A stopped container remains inspectable until explicitly removed. Cleanup - // gets an independent cancellation token so SIGTERM cannot skip daemon cleanup. - let cleanup = remove(&launch); - let finished = interrupt.finish(); - write( - &launch.artifacts.join("container-lifecycle.json"), - &json!({"container":launch.name,"image":image,"source_commit":launch.commit, - "benchmark_success":result.is_ok(),"removed":cleanup.is_ok()}), - )?; - let result_path = std::env::var_os("JIANYANG_RESULT_PATH").ok_or("JY result path missing")?; - let published = retain_result( - &launch.artifacts.join("container-result.json"), - Path::new(&result_path), - result, - ); - cleanup?; - finished?; - published -} - -fn retain_result(source: &Path, destination: &Path, outcome: DynResult<()>) -> DynResult<()> { - // Failed sweeps still publish valid earlier cells and explicit failure counts. - // A failure before the first cell may have no result at all; retain that error. - match std::fs::copy(source, destination) { - Ok(_) => outcome, - Err(error) if error.kind() == std::io::ErrorKind::NotFound && outcome.is_err() => outcome, - Err(error) => Err(error.into()), - } -} - -fn prepare(output: PathBuf, model_key: &str) -> DynResult { - if std::env::consts::OS != "linux" || std::env::consts::ARCH != "aarch64" { - return Err("AgentX Docker jobs must execute on the Linux ARM64 Spark".into()); - } - let commit = std::env::var("JIANYANG_COMMIT")?; - let run = std::env::var("JIANYANG_RUN_ID")?; - validate_identity(&commit, &run)?; - if !output.is_absolute() { - return Err("container output must be absolute".into()); - } - std::fs::create_dir(&output)?; - let artifacts = PathBuf::from( - std::env::var_os("JIANYANG_ARTIFACT_DIR").ok_or("JY artifact directory missing")?, - ) - .canonicalize()?; - let model = inputs::select_model(&std::env::current_dir()?, model_key)?; - let requested = std::env::var_os("HF_HOME").map(PathBuf::from); - let fallbacks = [ - PathBuf::from("/mnt/lab/huggingface"), - PathBuf::from("/mnt/model-store/hf"), - ]; - let hf_home = resolve_hf_home(requested.as_deref(), &fallbacks, &model)?; - write( - &artifacts.join("hf-home-selection.json"), - &json!({"requested":requested,"selected":hf_home,"model":model.key}), - )?; - let seconds = remaining(std::env::var("JIANYANG_DEADLINE_EPOCH")?.parse()?)?; - Ok(Launch { - root: std::env::current_dir()?, - output, - artifacts, - hf_home, - commit, - name: format!("agentx-{run}"), - seconds, - }) -} - -fn resolve_hf_home( - requested: Option<&Path>, - fallbacks: &[PathBuf], - model: &Model, -) -> DynResult { - let snapshot = format!("models--{}", model.repo.replace('/', "--")); - requested - .into_iter() - .chain(fallbacks.iter().map(PathBuf::as_path)) - .find(|home| { - home.is_absolute() - && home.is_dir() - && !model.files.is_empty() - && model.files.iter().all(|file| { - home.join("hub") - .join(&snapshot) - .join("snapshots") - .join(&model.revision) - .join(&file.name) - .is_file() - }) - }) - .map(Path::to_path_buf) - .ok_or_else(|| { - format!( - "pinned model weights are absent from host HF_HOME for {}", - model.key - ) - .into() - }) -} - -fn validate_identity(commit: &str, run: &str) -> DynResult<()> { - if commit.len() != 40 - || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) - || run.is_empty() - || run.len() > 100 - || !run - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') - { - return Err("invalid JY source/run identity".into()); - } - Ok(()) -} - -fn remaining(deadline: u64) -> DynResult { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH)? - .as_secs(); - deadline - .checked_sub(now + 60) - .filter(|seconds| *seconds > 0) - .ok_or_else(|| "JY deadline has no time left for benchmark and cleanup".into()) -} - -fn inspect(launch: &Launch) -> DynResult { - let spec = command::spec( - &launch.root, - "docker", - &command::strings(&[ - "image", - "inspect", - &format!("mesh-agentx:{}", launch.commit), - ]), - )?; - let log = launch.output.join("image-inspect"); - command::run(&spec, 30, &log)?; - let bytes = std::fs::read(log.with_extension("stdout.log"))?; - let images: Value = serde_json::from_slice(&bytes)?; - let image = &images[0]; - if image["Architecture"] != "arm64" - || image["Config"]["Labels"]["org.opencontainers.image.revision"] != launch.commit - { - return Err("container architecture/source label does not match JY job".into()); - } - let id = image["Id"].as_str().ok_or("image ID missing")?; - if !id.starts_with("sha256:") || id.len() != 71 { - return Err("invalid immutable image ID".into()); - } - std::fs::write(launch.artifacts.join("container-image.json"), bytes)?; - Ok(id.into()) -} - -fn mount(source: &Path, destination: &str) -> DynResult { - let source = source.to_str().ok_or("non-Unicode mount path")?; - if source.contains([',', '\n', '\r']) { - return Err("unsupported Docker mount path".into()); - } - Ok(format!("type=bind,source={source},target={destination}")) -} - -fn create_args( - launch: &Launch, - image: &str, - engine: Engine, - model: &str, - profile: Profile, -) -> DynResult> { - let mut args = command::strings(&[ - "create", - "--name", - &launch.name, - "--gpus", - "all", - "--init", - "--label", - &format!("jianyang.run={}", launch.name), - "--mount", - &mount(&launch.output, "/output")?, - "--mount", - &mount(&launch.artifacts, "/artifacts")?, - "--mount", - &format!( - "{},readonly", - mount( - &launch.hf_home, - launch.hf_home.to_str().ok_or("HF_HOME path")?, - )? - ), - "--env", - &format!("HF_HOME={}", launch.hf_home.display()), - "--env", - "JIANYANG_ARTIFACT_DIR=/artifacts", - "--env", - "JIANYANG_RESULT_PATH=/artifacts/container-result.json", - "--env", - &format!("JIANYANG_COMMIT={}", launch.commit), - "--env", - &format!("AGENTX_CONTAINER_IMAGE={image}"), - ]); - #[cfg(unix)] - { - // SAFETY: getuid/getgid only read the current process's numeric identity. - let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; - args.extend(command::strings(&["--user", &format!("{uid}:{gid}")])); - } - args.extend(command::strings(&[ - image, - &launch.seconds.to_string(), - "/workspace/target/debug/xtask", - "automation", - "agentx", - "run", - "--engine", - engine.label(), - "--model", - model, - "--profile", - profile.label(), - "--output", - "/output/campaign", - ])); - Ok(args) -} - -fn attached(launch: &Launch, cancellation: &process::Cancellation) -> DynResult<()> { - let spec = command::spec( - &launch.root, - "docker", - &command::strings(&["start", "--attach", &launch.name]), - )?; - let report = process::supervise_inherited_closed_stdin( - &spec, - &docker_limits(launch.seconds + 30), - cancellation, - )?; - if report.outcome != process::Outcome::Exited - || !report.cleanup.complete - || report.failure.is_some() - || !report.status.is_some_and(|status| status.success()) - { - return Err("AgentX container failed, timed out, or was cancelled".into()); - } - Ok(()) -} - -fn remove(launch: &Launch) -> DynResult<()> { - let spec = command::spec( - &launch.root, - "docker", - &command::strings(&["container", "rm", "--force", &launch.name]), - )?; - let report = process::supervise_inherited_closed_stdin( - &spec, - &docker_limits(3), - &process::Cancellation::default(), - )?; - if !report.cleanup.complete || !report.status.is_some_and(|status| status.success()) { - return Err("Docker container removal failed".into()); - } - Ok(()) -} - -fn docker_limits(seconds: u64) -> process::Limits { - // JY escalates SIGTERM to SIGKILL after ten seconds. Leave time to remove - // the daemon-owned container after terminating an unresponsive Docker client. - let mut limits = command::limits(seconds); - limits.graceful_shutdown = std::time::Duration::from_secs(1); - limits.forced_shutdown = std::time::Duration::from_secs(1); - limits -} - -#[cfg(test)] -mod tests { - use super::super::FilePin; - use super::*; - - fn test_model(files: &[&str]) -> Model { - Model { - key: "test-model".into(), - family: "dense".into(), - repo: "org/model".into(), - revision: "pinned-revision".into(), - tokenizer: "org/model".into(), - tokenizer_revision: "pinned-revision".into(), - files: files - .iter() - .map(|name| FilePin { - name: (*name).into(), - sha256: "0".repeat(64), - }) - .collect(), - } - } - - fn cache_file(home: &Path, name: &str) { - let path = home - .join("hub/models--org--model/snapshots/pinned-revision") - .join(name); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, b"weight").unwrap(); - } - - #[test] - fn selects_cache_containing_every_pinned_model_file() { - let dir = tempfile::tempdir().unwrap(); - let requested = dir.path().join("empty"); - let fallback = dir.path().join("cached"); - std::fs::create_dir_all(&requested).unwrap(); - let model = test_model(&["BF16/part-1.gguf", "BF16/part-2.gguf"]); - cache_file(&requested, "BF16/part-1.gguf"); - cache_file(&fallback, "BF16/part-1.gguf"); - cache_file(&fallback, "BF16/part-2.gguf"); - assert_eq!( - resolve_hf_home(Some(&requested), std::slice::from_ref(&fallback), &model).unwrap(), - fallback - ); - cache_file(&requested, "BF16/part-2.gguf"); - assert_eq!( - resolve_hf_home(Some(&requested), &[fallback], &model).unwrap(), - requested - ); - } - - #[test] - fn missing_cache_fails_before_container_launch() { - let dir = tempfile::tempdir().unwrap(); - assert!( - resolve_hf_home( - None, - &[dir.path().to_path_buf()], - &test_model(&["model.gguf"]) - ) - .is_err() - ); - } - #[test] - fn failed_container_retains_partial_results_without_becoming_successful() { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("container-result.json"); - let destination = dir.path().join("result.json"); - let partial = r#"{"points":[{"concurrency":1}],"quality":{"sweep":{"cells_incomplete_or_failed":1}}}"#; - std::fs::write(&source, partial).unwrap(); - let result = retain_result(&source, &destination, Err("cell failed".into())); - assert_eq!(result.unwrap_err().to_string(), "cell failed"); - assert_eq!(std::fs::read_to_string(&destination).unwrap(), partial); - assert!(retain_result(&source, &destination, Ok(())).is_ok()); - } - - #[test] - fn missing_results_are_only_allowed_after_failure() { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("missing.json"); - let destination = dir.path().join("result.json"); - assert!(retain_result(&source, &destination, Ok(())).is_err()); - let result = retain_result(&source, &destination, Err("startup failed".into())); - assert_eq!(result.unwrap_err().to_string(), "startup failed"); - assert!(!destination.exists()); - } - - #[test] - fn selected_engine_reaches_container_with_same_host_cache_mount() { - let launch = Launch { - root: "/repo".into(), - output: "/runs/one".into(), - artifacts: "/artifacts/one".into(), - hf_home: "/mnt/lab/huggingface".into(), - commit: "a".repeat(40), - name: "agentx-run_one".into(), - seconds: 600, - }; - for engine in [Engine::Llama, Engine::Skippy] { - let args = - create_args(&launch, "sha256:test", engine, "model", Profile::Smoke).unwrap(); - assert!( - args.windows(2) - .any(|pair| pair == ["--engine", engine.label()]) - ); - assert!(args.windows(2).any(|pair| pair == ["--gpus", "all"])); - assert!(args.iter().any(|arg| arg - == "type=bind,source=/mnt/lab/huggingface,target=/mnt/lab/huggingface,readonly")); - } - } - #[test] - fn rejects_ambiguous_identity_and_mounts() { - assert!(validate_identity(&"a".repeat(40), "run_abc").is_ok()); - assert!(validate_identity("main", "run_abc").is_err()); - assert!(validate_identity(&"a".repeat(40), "../other").is_err()); - assert!(mount(Path::new("/cache,readonly"), "/cache").is_err()); - assert!(remaining(0).is_err()); - } -} diff --git a/tools/xtask/src/automation/agentx/contention_cohort.rs b/tools/xtask/src/automation/agentx/contention_cohort.rs index 3437a848ec..52f93c5579 100644 --- a/tools/xtask/src/automation/agentx/contention_cohort.rs +++ b/tools/xtask/src/automation/agentx/contention_cohort.rs @@ -1,104 +1,9 @@ //! Bounded two-turn sessions for concurrency diagnosis. -use super::{Prepared, comparison_cohort, inputs, trace_context, write}; +use super::Prepared; use crate::command::DynResult; -use serde_json::{Value, json}; -use std::{ - collections::{BTreeMap, BTreeSet}, - io::{BufRead, BufReader}, - path::Path, -}; +use serde_json::Value; pub(super) const SESSIONS: usize = 16; -const OUTPUT_TOKENS_PER_TURN: u64 = 128; -const INPUT_TOKENS_PER_TURN_CAP: u64 = 8192; -const MAX_SECOND_TURN_DELAY_SECS: f64 = 60.0; - -struct Candidate { - id: String, - source_requested_output_tokens: u64, - source_requested_turns: usize, - profile_requested_output_tokens: u64, - line: String, - source_context: Value, - profile_context: Value, -} - -pub(super) fn materialize(source: &Path, destination: &Path) -> DynResult<()> { - let mut seen = BTreeSet::new(); - let mut eligible = Vec::new(); - for line in BufReader::new(std::fs::File::open(source)?).lines() { - let line = line?; - let trace: Value = serde_json::from_str(&line)?; - let id = trace["id"].as_str().ok_or("trace ID missing")?.to_owned(); - if !seen.insert(id.clone()) { - return Err("duplicate contention trace".into()); - } - let source_context = trace_context::describe(&trace, line.as_bytes())?; - if source_context["status"] != "eligible" { - continue; - } - let Some(profile) = two_turn_profile(&trace)? else { - continue; - }; - let turns = comparison_cohort::expected_turns(&id, &trace)?; - let profile_turns = comparison_cohort::expected_turns(&id, &profile)?; - let profile_line = serde_json::to_string(&profile)?; - let profile_context = trace_context::describe(&profile, profile_line.as_bytes())?; - eligible.push(Candidate { - id, - source_requested_output_tokens: turns.values().sum(), - source_requested_turns: turns.len(), - profile_requested_output_tokens: profile_turns.values().sum(), - line: profile_line, - source_context, - profile_context, - }); - } - eligible.sort_by(|a, b| { - a.source_requested_output_tokens - .cmp(&b.source_requested_output_tokens) - .then_with(|| a.id.cmp(&b.id)) - }); - if eligible.len() < SESSIONS { - return Err("fewer than 16 two-turn context-compatible AgentX traces".into()); - } - let selected: Vec<_> = eligible.into_iter().take(SESSIONS).collect(); - let parent = destination.parent().ok_or("contention cohort parent")?; - let audit: Vec<_> = selected - .iter() - .map(|candidate| candidate.profile_context.clone()) - .collect(); - let mut expected = BTreeMap::new(); - for (index, candidate) in selected.iter().enumerate() { - std::fs::write( - destination.join(format!("{index:04}.json")), - &candidate.line, - )?; - let trace: Value = serde_json::from_str(&candidate.line)?; - expected.extend(comparison_cohort::expected_turns(&candidate.id, &trace)?); - } - write(&parent.join("expected-work.json"), &expected)?; - write( - &parent.join("cohort.json"), - &json!({ - "dataset_repo":inputs::DATA_REPO,"dataset_revision":inputs::DATA_REVISION, - "dataset_sha256":inputs::DATA_SHA, - "trace_ids":selected.iter().map(|candidate| &candidate.id).collect::>(), - "trace_context":audit, - "source_trace_context":selected.iter().map(|candidate| &candidate.source_context).collect::>(), - "selection":"16_lowest_source_output_two_root_turns_input8k_output128_v2", - "source_requested_turns":selected.iter().map(|candidate| candidate.source_requested_turns).sum::(), - "source_requested_output_tokens":selected.iter().map(|candidate| candidate.source_requested_output_tokens).sum::(), - "profile_requested_turns":SESSIONS * 2, - "profile_requested_output_tokens":selected.iter().map(|candidate| candidate.profile_requested_output_tokens).sum::(), - "output_tokens_per_turn_cap":OUTPUT_TOKENS_PER_TURN, - "input_tokens_per_turn_cap":INPUT_TOKENS_PER_TURN_CAP, - "max_second_turn_delay_seconds":MAX_SECOND_TURN_DELAY_SECS, - "request_policy":"fixed_16_two_turn_sessions_not_full_agentx_qualification", - }), - ) -} - pub(super) fn configuration(input: &Prepared, port: u16, concurrency: u32) -> DynResult { super::agentic_config::configuration( input, @@ -109,135 +14,10 @@ pub(super) fn configuration(input: &Prepared, port: u16, concurrency: u32) -> Dy ) } -fn two_turn_profile(trace: &Value) -> DynResult> { - let requests = trace["requests"] - .as_array() - .ok_or("missing trace requests")?; - let [first, second, ..] = requests.as_slice() else { - return Ok(None); - }; - if ![first, second] - .iter() - .all(|turn| matches!(turn["type"].as_str(), Some("n" | "s"))) - { - return Ok(None); - } - let (Some(first_at), Some(second_at)) = (first["t"].as_f64(), second["t"].as_f64()) else { - return Ok(None); - }; - if !(0.0..=MAX_SECOND_TURN_DELAY_SECS).contains(&(second_at - first_at)) { - return Ok(None); - } - let block_size = trace["block_size"] - .as_u64() - .ok_or("invalid trace block size")?; - if block_size == 0 { - return Err("zero trace block size".into()); - } - let mut selected = Vec::with_capacity(2); - for turn in [first, second] { - let output = turn["out"].as_u64().ok_or("invalid requested output")?; - let input = turn["in"].as_u64().ok_or("invalid requested input")?; - let capped_input = input.min(INPUT_TOKENS_PER_TURN_CAP); - let mut capped = turn.clone(); - capped["out"] = json!(output.clamp(1, OUTPUT_TOKENS_PER_TURN)); - capped["in"] = json!(capped_input); - if let Some(hashes) = turn["hash_ids"].as_array() { - let blocks = capped_input.div_ceil(block_size) as usize; - capped["hash_ids"] = json!(hashes.iter().take(blocks).collect::>()); - } - selected.push(capped); - } - let mut profile = trace.clone(); - profile["requests"] = json!(selected); - Ok(Some(profile)) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn selects_the_same_bounded_two_turn_traces_independent_of_source_order() { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source.jsonl"); - let rows: Vec<_> = (0..20) - .map(|index| { - json!({"id":format!("trace-{index:02}"),"block_size":64, - "requests":[{"type":"n","t":0,"in":100,"out":20-index}, - {"type":"s","t":1,"in":10000,"out":256,"hash_ids":(0..157).collect::>()}, - {"type":"n","t":2,"in":300,"out":512}]}) - .to_string() - }) - .collect(); - std::fs::write(&source, rows.join("\n")).unwrap(); - let first = dir.path().join("first/traces"); - std::fs::create_dir_all(&first).unwrap(); - materialize(&source, &first).unwrap(); - let first_cohort: Value = serde_json::from_slice( - &std::fs::read(first.parent().unwrap().join("cohort.json")).unwrap(), - ) - .unwrap(); - assert_eq!( - first_cohort["trace_ids"].as_array().unwrap().len(), - SESSIONS - ); - assert_eq!(first_cohort["trace_ids"][0], "trace-19"); - assert_eq!( - first_cohort["source_requested_output_tokens"], - 136 + 16 * 768 - ); - assert_eq!( - first_cohort["profile_requested_output_tokens"], - 136 + 16 * 128 - ); - assert_eq!(first_cohort["profile_requested_turns"], 32); - let expected: BTreeMap = serde_json::from_slice( - &std::fs::read(first.parent().unwrap().join("expected-work.json")).unwrap(), - ) - .unwrap(); - assert_eq!(expected.len(), 32); - assert_eq!(expected.values().sum::(), 136 + 16 * 128); - let first_trace: Value = - serde_json::from_slice(&std::fs::read(first.join("0000.json")).unwrap()).unwrap(); - assert_eq!(first_trace["requests"].as_array().unwrap().len(), 2); - assert_eq!(first_trace["requests"][1]["out"], 128); - assert_eq!(first_trace["requests"][1]["in"], 8192); - assert_eq!( - first_trace["requests"][1]["hash_ids"] - .as_array() - .unwrap() - .len(), - 128 - ); - std::fs::write( - &source, - rows.into_iter().rev().collect::>().join("\n"), - ) - .unwrap(); - let second = dir.path().join("second/traces"); - std::fs::create_dir_all(&second).unwrap(); - materialize(&source, &second).unwrap(); - let second_cohort: Value = serde_json::from_slice( - &std::fs::read(second.parent().unwrap().join("cohort.json")).unwrap(), - ) - .unwrap(); - assert_eq!(first_cohort, second_cohort); - } - - #[test] - fn excludes_delayed_or_branching_first_followups() { - let ordinary = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, - {"type":"s","t":2,"in":200,"out":1}]}); - assert!(two_turn_profile(&ordinary).unwrap().is_some()); - let delayed = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, - {"type":"s","t":61,"in":200,"out":1}]}); - assert!(two_turn_profile(&delayed).unwrap().is_none()); - let branched = json!({"block_size":64,"requests":[{"type":"n","t":0,"in":100,"out":1}, - {"type":"subagent","requests":[]}]}); - assert!(two_turn_profile(&branched).unwrap().is_none()); - } - #[test] fn config_runs_all_sessions_without_scenario_warmup_or_duration() { let models: Vec = serde_json::from_str(include_str!( diff --git a/tools/xtask/src/automation/agentx/final_sweep.rs b/tools/xtask/src/automation/agentx/final_sweep.rs index 525b324c5e..8b6df3ad96 100644 --- a/tools/xtask/src/automation/agentx/final_sweep.rs +++ b/tools/xtask/src/automation/agentx/final_sweep.rs @@ -107,7 +107,7 @@ fn run(request: Request, output: &Path) -> DynResult<()> { let status = if result.is_ok() { "passed" } else { "failed" }; let mut report = json!({"schema_version":1,"campaign":request.campaign,"model_key":request.model_key,"request":request, "backend":request.tools.backend,"status":status,"arms":arms,"error":result.as_ref().err().map(ToString::to_string), - "repeat_order":ORDER,"concurrencies":[1,2,4],"scope":if request.tools.backend==Backend::Cpu{"cpu_diagnostic_not_gpu_performance"}else{"fixed_complete_AgentX_comparison"}, + "repeat_order":ORDER,"concurrencies":[1,2,4],"scope":report_scope(request.tools.backend, request.tools.diagnostic_generation_lanes), "jy_job_id":std::env::var("JIANYANG_JOB_ID").ok(),"jy_run_id":std::env::var("JIANYANG_RUN_ID").ok(), "source_attribution":{"product":request.tools.product_source_commit,"native":request.tools.native_source_commit, "standard_upstream":request.tools.standard_upstream,"automation_binary_sha256":crate::product::digest::file_sha256(&std::env::current_exe()?).map_err(|e|e.error)?}, @@ -122,11 +122,17 @@ fn run(request: Request, output: &Path) -> DynResult<()> { write(&output.join("result.json"), &report)?; result = Err(error); } - if let Some(path) = std::env::var_os("JIANYANG_RESULT_PATH") { - write(Path::new(&path), &report)?; - } result } +pub(super) fn report_scope(backend: Backend, lanes: Option) -> &'static str { + if backend == Backend::Cpu { + "cpu_diagnostic_not_gpu_performance" + } else if lanes.is_some() { + "diagnostic_generation_lanes_AgentX_comparison" + } else { + "fixed_complete_AgentX_comparison" + } +} fn execute(request: &Request, output: &Path, arms: &mut Vec) -> DynResult<()> { admit_host(request.tools.backend, output)?; let model = request.validate()?; diff --git a/tools/xtask/src/automation/agentx/final_sweep_tests.rs b/tools/xtask/src/automation/agentx/final_sweep_tests.rs index 0968d886f5..061df3a19a 100644 --- a/tools/xtask/src/automation/agentx/final_sweep_tests.rs +++ b/tools/xtask/src/automation/agentx/final_sweep_tests.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; pub(super) fn arms() -> Vec { ORDER.into_iter().enumerate().map(|(index,engine)|json!({"index":index+1,"engine":engine,"status":"passed", - "cells":([1,2,4].map(|c|json!({"offered_sessions":c,"output_tok_s":20.0, + "cells":([1,2,4].map(|c|json!({"offered_sessions":c,"output_tok_s":20.0,"ttft":{"p50":1.0,"p95":2.0},"itl":{"p50":0.5}, "cohort":{"selected_cohort_sha256":COHORT_SHA},"phase_outcome":{"errors":0,"cancelled":0}, "completed_work":{"requests":69,"output_tokens":18713,"source_turn_output_sha256":"a".repeat(64)}})))})).collect() } @@ -81,9 +81,14 @@ fn prepared_tree_identity_detects_mutation_and_refuses_directory_links() { #[test] fn manifest_cannot_pair_wrong_source_backend_or_upstream_with_pinned_tools() { let tools = tools(); - let manifest = json!({"runtime":{"backend":{"kind":"cuda"},"skippy_abi":"0.1.76"}, + let abi = crate::native_policy::package_version::abi_version(include_bytes!( + "../../../../../skippy/crates/skippy-ffi/src/lib.rs" + )) + .unwrap() + .to_string(); + let manifest = json!({"runtime":{"backend":{"kind":"cuda"},"skippy_abi":abi}, "build":{"llama_patched_sha":tools.native_source_commit,"llama_patch_digest":tools.native_patch_digest,"llama_upstream_sha":tools.standard_upstream}}); - tools.validate_manifest(&manifest).unwrap(); + tools.validate_manifest(&manifest, &abi).unwrap(); for pointer in [ "/build/llama_patched_sha", "/build/llama_patch_digest", @@ -93,7 +98,30 @@ fn manifest_cannot_pair_wrong_source_backend_or_upstream_with_pinned_tools() { ] { let mut wrong = manifest.clone(); *wrong.pointer_mut(pointer).unwrap() = json!("different"); - assert!(tools.validate_manifest(&wrong).is_err(), "{pointer}"); + assert!(tools.validate_manifest(&wrong, &abi).is_err(), "{pointer}"); + } + assert!(tools.validate_manifest(&manifest, "0.0.0").is_err()); +} + +#[test] +fn prepared_environment_rejects_executable_and_external_pth_entries() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let path = dir.path().join("module-path.pth"); + let tree = Tree { + path: dir.path().into(), + sha256: String::new(), + }; + std::fs::create_dir(dir.path().join("modules")).unwrap(); + std::fs::write(&path, "# local modules\nmodules\n").unwrap(); + assert!(tree.observe().is_ok()); + for content in [ + "import outside\n".into(), + "import\toutside\n".into(), + format!("{}\n", outside.path().display()), + ] { + std::fs::write(&path, content).unwrap(); + assert!(tree.observe().is_err()); } } diff --git a/tools/xtask/src/automation/agentx/hardware.rs b/tools/xtask/src/automation/agentx/hardware.rs index 0e89bd5634..abbe16921f 100644 --- a/tools/xtask/src/automation/agentx/hardware.rs +++ b/tools/xtask/src/automation/agentx/hardware.rs @@ -3,42 +3,6 @@ use super::{Prepared, command, write}; use crate::command::DynResult; use serde_json::{Value, json}; -pub(super) fn admit_execution() -> DynResult<()> { - validate_execution( - std::env::consts::OS, - std::env::consts::ARCH, - std::path::Path::new("/.dockerenv").exists(), - std::env::var("AGENTX_CONTAINER_IMAGE").ok().as_deref(), - std::env::var("JIANYANG_RUN_ID").ok().as_deref(), - std::env::var("JIANYANG_COMMIT").ok().as_deref(), - ) -} - -fn validate_execution( - os: &str, - arch: &str, - in_container: bool, - image: Option<&str>, - run: Option<&str>, - commit: Option<&str>, -) -> DynResult<()> { - match (os, arch) { - ("linux", "aarch64") - if in_container - && image.is_some_and(|value| { - value.strip_prefix("sha256:").is_some_and(|digest| { - digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) - }) => Ok(()), - ("macos", "aarch64") - if run.is_some_and(|value| value.starts_with("run_") && value.len() > 4) - && commit.is_some_and(|value| { - value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) => Ok(()), - _ => Err("AgentX requires the JY GPU container on Spark or a pinned native JY job on Apple Silicon".into()), - } -} - pub(super) fn capture(input: &Prepared) -> DynResult<()> { if input .tools @@ -115,58 +79,6 @@ fn apple_metal(gpu: &Value) -> bool { #[cfg(test)] mod tests { use super::*; - #[test] - fn execution_requires_platform_appropriate_provenance() { - let image = format!("sha256:{}", "a".repeat(64)); - let commit = "b".repeat(40); - assert!(validate_execution("linux", "aarch64", true, Some(&image), None, None).is_ok()); - assert!( - validate_execution( - "linux", - "aarch64", - false, - Some(&image), - Some("run_test"), - Some(&commit) - ) - .is_err() - ); - assert!( - validate_execution("linux", "aarch64", true, Some("sha256:invalid"), None, None) - .is_err() - ); - assert!( - validate_execution( - "macos", - "aarch64", - false, - None, - Some("run_test"), - Some(&commit) - ) - .is_ok() - ); - for (run, revision) in [ - (None, Some(commit.as_str())), - (Some("run_test"), None), - (Some("run_"), Some(commit.as_str())), - (Some("run_test"), Some("main")), - ] { - assert!(validate_execution("macos", "aarch64", false, None, run, revision).is_err()); - } - assert!( - validate_execution( - "windows", - "aarch64", - true, - Some(&image), - Some("run_test"), - Some(&commit) - ) - .is_err() - ); - } - #[test] fn admits_recorded_apple_metal_and_spark_reports() { for field in ["spdisplays_mtlgpufamilysupport", "spdisplays_metal"] { diff --git a/tools/xtask/src/automation/agentx/inputs.rs b/tools/xtask/src/automation/agentx/inputs.rs index c7efd1a7a7..9bd13d2c99 100644 --- a/tools/xtask/src/automation/agentx/inputs.rs +++ b/tools/xtask/src/automation/agentx/inputs.rs @@ -1,7 +1,6 @@ -use super::{Model, Prepared, Profile, command, write}; +use super::Model; use crate::command::DynResult; -use std::io::{BufRead, BufReader}; -use std::path::{Path, PathBuf}; +use std::path::Path; pub(super) const DATA_REPO: &str = "semianalysisai/cc-traces-weka-062126-256k"; pub(super) const DATA_REVISION: &str = "8fecd2fc56694469f758f0afbbb6335ad3043740"; pub(super) const DATA_SHA: &str = @@ -12,62 +11,6 @@ pub(super) fn digest(bytes: &[u8]) -> String { hex::encode(Sha256::digest(bytes)) } -pub(super) fn prepare( - root: PathBuf, - output: PathBuf, - key: &str, - profile: Profile, -) -> DynResult { - let model = select_model(&root, key)?; - let mut weights = None; - for (index, file) in model.files.iter().enumerate() { - let path = download( - &root, - &model.repo, - &model.revision, - &file.name, - false, - &output, - &format!("download-weight-{index}"), - )?; - // Preparation verifies each pin once before any serving cell starts. - verify(&path, &file.sha256)?; - weights.get_or_insert(path); - } - download( - &root, - &model.tokenizer, - &model.tokenizer_revision, - "", - false, - &output, - "download-tokenizer", - )?; - let dataset = download( - &root, - DATA_REPO, - DATA_REVISION, - "traces.jsonl", - true, - &output, - "download-dataset", - )?; - verify(&dataset, DATA_SHA)?; - let traces = output.join("traces"); - materialize(&dataset, &traces, profile)?; - let prepared = Prepared { - tools: None, - root, - output, - weights: weights.ok_or("empty model files")?, - dataset: traces, - model, - profile, - }; - write(&prepared.output.join("inputs.json"), &prepared)?; - Ok(prepared) -} - pub(super) fn select_model(root: &Path, key: &str) -> DynResult { let models: Vec = serde_json::from_slice(&std::fs::read( root.join("skippy/evals/kv-validation/models.json"), @@ -77,58 +20,6 @@ pub(super) fn select_model(root: &Path, key: &str) -> DynResult { .find(|model| model.key == key || model.registry_ref() == key) .ok_or_else(|| "unknown AgentX model".into()) } -fn download( - root: &Path, - repo: &str, - revision: &str, - file: &str, - dataset: bool, - output: &Path, - log_name: &str, -) -> DynResult { - let hf = root.join("skippy/evals/agentx/.venv/bin/hf"); - // Standard HF cache resolution reuses the host's blobs/snapshots and writes - // only missing pins into that same mounted HF_HOME. Never use --local-dir. - let mut args = command::strings(&["download", repo, "--revision", revision, "--quiet"]); - if dataset { - args.extend(command::strings(&["--repo-type", "dataset"])); - } - if !file.is_empty() { - args.push(file.into()); - } else { - args.extend(command::strings(&[ - "--include", - "tokenizer*", - "--include", - "vocab.json", - "--include", - "merges.txt", - "--include", - "config.json", - "--include", - "chat_template*", - ])); - } - let log = output.join(log_name); - let mut spec = command::spec(root, hf.to_str().ok_or("hf path")?, &args)?; - spec.environment.insert( - "HF_HUB_OFFLINE".into(), - crate::process::Value::Public("1".into()), - ); - command::run(&spec, 60, &log)?; - cached_path(&std::fs::read_to_string(log.with_extension("stdout.log"))?) -} - -fn cached_path(stdout: &str) -> DynResult { - let text = stdout.trim(); - let path = PathBuf::from(text); - if text.contains(['\n', '\r']) || !path.is_absolute() || !path.exists() { - return Err("HF download did not return one existing absolute cache path".into()); - } - // Retain the snapshot path rather than canonicalizing to blobs: split GGUF - // loaders and shard verification resolve sibling files in the snapshot. - Ok(path) -} pub(super) fn verify(path: &Path, expected: &str) -> DynResult<()> { let actual = crate::product::digest::file_sha256(path).map_err(|failure| failure.error)?; if actual != expected { @@ -136,120 +27,13 @@ pub(super) fn verify(path: &Path, expected: &str) -> DynResult<()> { } Ok(()) } -fn materialize(source: &Path, destination: &Path, profile: Profile) -> DynResult<()> { - std::fs::create_dir(destination)?; - if profile == Profile::Comparison { - return super::comparison_cohort::materialize(source, destination); - } - if profile == Profile::Contention { - return super::contention_cohort::materialize(source, destination); - } - let limit = if profile == Profile::Smoke { 128 } else { 393 }; - let mut ids = Vec::new(); - let mut trace_context = Vec::new(); - for (index, line) in BufReader::new(std::fs::File::open(source)?) - .lines() - .take(limit) - .enumerate() - { - let line = line?; - let trace: serde_json::Value = serde_json::from_str(&line)?; - ids.push(trace["id"].as_str().ok_or("trace ID missing")?.to_owned()); - trace_context.push(super::trace_context::describe(&trace, line.as_bytes())?); - std::fs::write(destination.join(format!("{index:04}.json")), line)?; - } - if ids.len() != limit { - return Err("AgentX corpus has fewer traces than requested".into()); - } - write( - &destination - .parent() - .ok_or("trace parent")? - .join("cohort.json"), - &serde_json::json!({"dataset_repo":DATA_REPO,"dataset_revision":DATA_REVISION,"dataset_sha256":DATA_SHA,"trace_ids":ids,"trace_context":trace_context}), - ) -} #[cfg(test)] mod tests { use super::*; #[test] - fn smoke_preserves_complete_rows_and_selects_exact_prefix() { - let temp = tempfile::tempdir().unwrap(); - let source = temp.path().join("corpus.jsonl"); - let rows: Vec<_> = (0..129).map(|index| format!(r#"{{"id":"trace-{index}","requests":[{{"type":"subagent","id":"child","requests":[{{"type":"s","in":120000,"out":20000}}]}},{{"type":"n","in":10,"out":100000}}]}}"#)).collect(); - std::fs::write(&source, rows.join("\n")).unwrap(); - let target = temp.path().join("selected"); - materialize(&source, &target, Profile::Smoke).unwrap(); - assert_eq!(std::fs::read_dir(&target).unwrap().count(), 128); - for (index, row) in rows.iter().take(128).enumerate() { - assert_eq!( - std::fs::read_to_string(target.join(format!("{index:04}.json"))).unwrap(), - *row - ); - } - let cohort: serde_json::Value = - serde_json::from_slice(&std::fs::read(temp.path().join("cohort.json")).unwrap()) - .unwrap(); - assert_eq!(cohort["trace_ids"].as_array().unwrap().len(), 128); - assert_eq!(cohort["trace_context"][0]["status"], "unsupported_context"); - } - #[test] - fn corrupted_download_fails_before_use() { + fn corrupted_model_fails_before_use() { let temp = tempfile::NamedTempFile::new().unwrap(); assert!(verify(temp.path(), DATA_SHA).is_err()); } - #[cfg(unix)] - #[test] - fn consecutive_input_commands_retain_independent_outputs() { - use std::os::unix::fs::PermissionsExt; - let root = tempfile::tempdir().unwrap(); - let bin = root.path().join("skippy/evals/agentx/.venv/bin"); - std::fs::create_dir_all(&bin).unwrap(); - let fixture = root.path().join("cached.gguf"); - std::fs::write(&fixture, b"cached weights").unwrap(); - let hf = bin.join("hf"); - std::fs::write( - &hf, - format!("#!/bin/sh\nprintf '%s\\n' '{}'\n", fixture.display()), - ) - .unwrap(); - std::fs::set_permissions(&hf, std::fs::Permissions::from_mode(0o755)).unwrap(); - for name in [ - "download-weight-0", - "download-tokenizer", - "download-dataset", - ] { - assert_eq!( - download( - root.path(), - "org/model", - "pin", - "file", - false, - root.path(), - name - ) - .unwrap(), - fixture - ); - assert!(root.path().join(format!("{name}.stdout.log")).is_file()); - } - } - #[cfg(unix)] - #[test] - fn hf_cache_resolution_preserves_snapshot_symlinks_and_rejects_ambiguous_output() { - let cache = tempfile::tempdir().unwrap(); - let blob = cache.path().join("blob"); - std::fs::write(&blob, b"weights").unwrap(); - let snapshot = cache.path().join("snapshot.gguf"); - std::os::unix::fs::symlink(&blob, &snapshot).unwrap(); - assert_eq!( - cached_path(&format!("{}\n", snapshot.display())).unwrap(), - snapshot - ); - assert!(cached_path(&format!("{}\n{}", blob.display(), snapshot.display())).is_err()); - assert!(cached_path("relative/model.gguf").is_err()); - assert!(cached_path(cache.path().join("missing").to_str().unwrap()).is_err()); - } } diff --git a/tools/xtask/src/automation/agentx/lifecycle.rs b/tools/xtask/src/automation/agentx/lifecycle.rs index 09716c2ca9..1c6755abfa 100644 --- a/tools/xtask/src/automation/agentx/lifecycle.rs +++ b/tools/xtask/src/automation/agentx/lifecycle.rs @@ -305,6 +305,21 @@ fn server( super::prepared_launch::arguments(&mut args, engine, tools); } let mut spec = command::spec(&input.root, binary.to_str().ok_or("server path")?, &args)?; + if engine == "llama" + && let Some(tools) = input.tools.as_ref() + { + // ggml's dynamic backend discovery searches the executable directory + // and cwd. Both must belong to the tree whose bytes were pinned. + spec.executable = super::standard_runtime::admitted_executable( + &spec.executable, + &tools.standard_runtime.path, + )?; + spec.cwd = spec + .executable + .parent() + .ok_or("baseline executable parent missing")? + .into(); + } if engine == "skippy" { spec.arguments.extend([ process::Value::Public("--runtime-bundle".into()), @@ -456,7 +471,14 @@ pub(super) fn execute(input: &Prepared, engine: &str, concurrency: u32) -> DynRe &input.output.join("memory-summary.json"), &serde_json::to_value(memory.finish()?)?, )?; - let clean = report.recovery_success() + let clean = report.members.iter().any(|member| { + member.member == MemberId::Seed + && member + .process + .status + .as_ref() + .is_some_and(expected_server_shutdown) + }) && report.recovery_success() && report.members.len() == 2 && report.members.iter().all(|member| { member.process.cleanup.complete @@ -496,6 +518,21 @@ pub(super) fn execute(input: &Prepared, engine: &str, concurrency: u32) -> DynRe } Ok(()) } +// The servers receive SIGTERM after the worker finishes. Skippy can handle it +// and exit zero; an external llama can retain SIGTERM as its wait status. +// Explicit nonzero exits and other signals are shutdown failures. +fn expected_server_shutdown(status: &std::process::ExitStatus) -> bool { + if status.success() { + return true; + } + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + status.signal() == Some(libc::SIGTERM) + } + #[cfg(not(unix))] + false +} fn launch_identity( input: &Prepared, server: &process::ProcessSpec, @@ -662,6 +699,62 @@ impl Coordinator for Owner { mod tests { use super::*; #[test] + fn pinned_llama_launch_cannot_discover_plugins_in_the_workspace() { + let root = tempfile::tempdir().unwrap(); + let workspace = root.path().join("workspace"); + let runtime = root.path().join("standard"); + std::fs::create_dir(&workspace).unwrap(); + std::fs::create_dir(&runtime).unwrap(); + std::fs::write( + workspace.join("libggml-cpu.so"), + b"untrusted workspace plugin", + ) + .unwrap(); + let binary = runtime.join("llama-server"); + std::fs::write(&binary, b"pinned executable fixture").unwrap(); + let mut tools: super::super::prepared_tools::Tools = serde_json::from_str(include_str!( + "../../../../../skippy/evals/agentx/tools.example.json" + )) + .unwrap(); + tools.llama.path = binary.clone(); + tools.standard_runtime.path = runtime.clone(); + let models: Vec = serde_json::from_str(include_str!( + "../../../../../skippy/evals/kv-validation/models.json" + )) + .unwrap(); + let input = Prepared { + tools: Some(tools), + root: workspace, + output: root.path().join("output"), + model: models[0].clone(), + weights: root.path().join("weights.gguf"), + dataset: root.path().join("traces"), + profile: Profile::Comparison, + }; + let launch = server(&input, "llama", 8080, 1).unwrap(); + assert_eq!(launch.executable, binary.canonicalize().unwrap()); + assert_eq!(launch.cwd, runtime.canonicalize().unwrap()); + for key in ["GGML_BACKEND_PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"] { + assert!(!launch.environment.contains_key(std::ffi::OsStr::new(key))); + } + } + #[cfg(unix)] + #[test] + fn shutdown_accepts_zero_or_expected_sigterm_and_rejects_failures() { + use std::os::unix::process::ExitStatusExt; + for (raw, expected) in [ + (0, true), + (libc::SIGTERM, true), + (256, false), + (libc::SIGKILL, false), + ] { + assert_eq!( + expected_server_shutdown(&std::process::ExitStatus::from_raw(raw)), + expected + ); + } + } + #[test] fn skippy_diagnostic_overrides_are_explicit_and_positive() { assert!(skippy_diagnostic_arguments(None).is_empty()); assert_eq!( diff --git a/tools/xtask/src/automation/agentx/memory.rs b/tools/xtask/src/automation/agentx/memory.rs index 6f289aea27..edd44ad36f 100644 --- a/tools/xtask/src/automation/agentx/memory.rs +++ b/tools/xtask/src/automation/agentx/memory.rs @@ -93,18 +93,42 @@ fn kib_field(text: &str, name: &str) -> Option { } fn cgroup_memory_path() -> Option { - // Docker's cgroup namespace normally mounts this container at the root. - let root = PathBuf::from("/sys/fs/cgroup/memory.current"); - if root.is_file() { - return Some(root); - } let groups = std::fs::read_to_string("/proc/self/cgroup").ok()?; - let relative = groups.lines().find_map(|line| line.strip_prefix("0::"))?; - Some( - Path::new("/sys/fs/cgroup") - .join(relative.trim_start_matches('/')) - .join("memory.current"), - ) + let mounts = std::fs::read_to_string("/proc/self/mountinfo").ok()?; + resolve_cgroup_memory_path(&groups, &mounts) +} + +fn resolve_cgroup_memory_path(groups: &str, mounts: &str) -> Option { + let group = Path::new(groups.lines().find_map(|line| line.strip_prefix("0::"))?); + if !group.is_absolute() + || group + .components() + .any(|part| part == std::path::Component::ParentDir) + { + return None; + } + mounts.lines().find_map(|line| { + let (mount, filesystem) = line.split_once(" - ")?; + if filesystem.split_whitespace().next()? != "cgroup2" { + return None; + } + let fields: Vec<_> = mount.split_whitespace().collect(); + let root = Path::new(*fields.get(3)?); + let mountpoint = Path::new(*fields.get(4)?); + // Ambiguous escaped mount paths remain unavailable rather than sampling + // an ancestor and attributing sibling memory to this campaign. + if !mountpoint.is_absolute() + || mountpoint.to_str()?.contains('\\') + || root.to_str()?.contains('\\') + { + return None; + } + Some( + mountpoint + .join(group.strip_prefix(root).ok()?) + .join("memory.current"), + ) + }) } fn read_sample(pid: u32, elapsed_ms: u128, cgroup: Option<&Path>) -> Sample { @@ -238,6 +262,28 @@ fn sample_loop(file: File, pid: &AtomicU32, stop: &mpsc::Receiver<()>) -> DynRes mod tests { use super::*; #[test] + fn cgroup_memory_resolves_the_exact_group_in_each_mount_namespace() { + let mount = "1 2 0:1 / /sys/fs/cgroup rw - cgroup2 cgroup rw"; + assert_eq!( + resolve_cgroup_memory_path("0::/jobs/campaign", mount), + Some("/sys/fs/cgroup/jobs/campaign/memory.current".into()) + ); + assert_eq!( + resolve_cgroup_memory_path("0::/", mount), + Some("/sys/fs/cgroup/memory.current".into()) + ); + let subtree = "1 2 0:1 /jobs /sys/fs/cgroup rw - cgroup2 cgroup rw"; + assert_eq!( + resolve_cgroup_memory_path("0::/jobs/campaign", subtree), + Some("/sys/fs/cgroup/campaign/memory.current".into()) + ); + assert_eq!( + resolve_cgroup_memory_path("0::/other/campaign", subtree), + None + ); + assert_eq!(resolve_cgroup_memory_path("0::/jobs/../other", mount), None); + } + #[test] fn proc_memory_requires_units_and_never_converts_missing_to_zero() { let status = "VmRSS:\t123 kB\nVmHWM:\t456 kB\nRssAnon:\t7 kB\n"; assert_eq!(kib_field(status, "VmRSS:"), Some(123 * 1024)); diff --git a/tools/xtask/src/automation/agentx/mlflow_export.rs b/tools/xtask/src/automation/agentx/mlflow_export.rs index 6b82987899..24fe15170f 100644 --- a/tools/xtask/src/automation/agentx/mlflow_export.rs +++ b/tools/xtask/src/automation/agentx/mlflow_export.rs @@ -3,7 +3,7 @@ use super::{final_sweep, prepared_tools::File}; use crate::command::DynResult; use serde::{Deserialize, Serialize}; use serde_json::Value; -use std::{collections::BTreeMap, path::Path}; +use std::{collections::BTreeMap, io::Read, path::Path}; pub(super) const EXPERIMENT: &str = "6"; pub(super) const EXPERIMENT_NAME: &str = "agentx-skippy-vs-llama"; @@ -45,6 +45,7 @@ pub(super) struct Child { pub(super) fn run(input: Input, output: &Path) -> DynResult<()> { input.report.verify()?; input.archive.verify()?; + validate_archive(&input.archive, &input.report.sha256)?; let report: Value = serde_json::from_slice(&crate::automation::receipt_files::bounded( &input.report.path, 4 * 1024 * 1024, @@ -53,7 +54,22 @@ pub(super) fn run(input: Input, output: &Path) -> DynResult<()> { crate::automation::receipt_files::fresh(output, &serde_json::to_vec_pretty(&plan)?) } fn build(report: &Value, input: Input) -> DynResult { - if report["status"] != "passed" || report["scope"] != "fixed_complete_AgentX_comparison" { + let lanes = match &report["request"]["tools"]["diagnostic_generation_lanes"] { + Value::Null => None, + value => Some( + value + .as_u64() + .filter(|lanes| (1..=256).contains(lanes)) + .ok_or("invalid diagnostic generation lane count")? as u32, + ), + }; + let backend_kind: super::prepared_tools::Backend = + serde_json::from_value(report["backend"].clone())?; + let expected_scope = final_sweep::report_scope(backend_kind, lanes); + if backend_kind == super::prepared_tools::Backend::Cpu + || report["status"] != "passed" + || report["scope"] != expected_scope + { return Err("MLflow performance publication requires a complete non-CPU campaign".into()); } let arms = report["arms"].as_array().ok_or("arms missing")?; @@ -84,6 +100,13 @@ fn build(report: &Value, input: Input) -> DynResult { tags.insert("ax.model_sha256".into(), selected.files[0].sha256.clone()); tags.insert("ax.category".into(), selected.family.clone()); tags.insert("ax.stage".into(), "final-comparison".into()); + if let Some(lanes) = lanes { + tags.insert( + "ax.capacity_policy".into(), + "diagnostic_generation_lanes".into(), + ); + tags.insert("ax.diagnostic_generation_lanes".into(), lanes.to_string()); + } for (key, pointer) in [ ( "ax.native_source_commit", @@ -133,44 +156,14 @@ fn build(report: &Value, input: Input) -> DynResult { tags.insert(key.into(), value.into()); } } - let key = format!("{campaign}:{source}:{backend}:{model}"); + let diagnostic = lanes.map_or_else(String::new, |lanes| format!(":diagnostic-lanes{lanes}")); + let key = format!("{campaign}:{source}:{backend}:{model}{diagnostic}"); let mut children = Vec::new(); for (index, arm) in arms.iter().enumerate() { let engine = arm["engine"].as_str().ok_or("engine missing")?; let mut metrics = BTreeMap::new(); for cell in arm["cells"].as_array().ok_or("cells missing")? { - let concurrency = cell["offered_sessions"] - .as_u64() - .ok_or("concurrency missing")?; - let prefix = format!("c{concurrency}"); - for (name, pointer) in [ - ("output_tok_s", "/output_tok_s"), - ("ttft_p50_ms", "/ttft/p50"), - ("ttft_p95_ms", "/ttft/p95"), - ("itl_p50_ms", "/itl/p50"), - ("cache_read_tokens_avg", "/cache_read_tokens/avg"), - ( - "peak_process_rss_bytes", - "/memory/sampled_peak_process_rss_bytes", - ), - ( - "peak_process_footprint_bytes", - "/memory/sampled_peak_process_physical_footprint_bytes", - ), - ( - "peak_cuda_process_accounted_bytes", - "/memory/sampled_peak_cuda_process_accounted_memory_bytes", - ), - ] { - if let Some(value) = cell.pointer(pointer).and_then(Value::as_f64) { - if !value.is_finite() || value < 0.0 { - return Err("nonfinite/negative publication metric".into()); - } - metrics.insert(format!("{prefix}.{name}"), value); - } - } - metrics.insert(format!("{prefix}.requests"), 69.0); - metrics.insert(format!("{prefix}.output_tokens"), 18713.0); + metrics.extend(cell_metrics(cell)?); } let mut child_tags = tags.clone(); child_tags.insert("ax.engine".into(), engine.into()); @@ -187,7 +180,7 @@ fn build(report: &Value, input: Input) -> DynResult { experiment_id: EXPERIMENT.into(), expected_experiment_name: EXPERIMENT_NAME.into(), campaign_root: CampaignRoot { - run_key: format!("{campaign}:{source}:root"), + run_key: format!("{campaign}:{source}{diagnostic}:root"), name: campaign.into(), tags: BTreeMap::from([ ("ax.campaign".into(), campaign.into()), @@ -207,6 +200,54 @@ fn build(report: &Value, input: Input) -> DynResult { archive: input.archive, }) } +fn cell_metrics(cell: &Value) -> DynResult> { + let mut metrics = BTreeMap::new(); + let concurrency = cell["offered_sessions"] + .as_u64() + .ok_or("concurrency missing")?; + let prefix = format!("c{concurrency}"); + for pointer in ["/ttft/p50", "/ttft/p95", "/itl/p50"] { + if cell + .pointer(pointer) + .and_then(Value::as_f64) + .is_none_or(|value| !value.is_finite() || value < 0.0) + { + return Err( + format!("missing finite nonnegative publication latency: {pointer}").into(), + ); + } + } + for (name, pointer) in [ + ("output_tok_s", "/output_tok_s"), + ("ttft_p50_ms", "/ttft/p50"), + ("ttft_p95_ms", "/ttft/p95"), + ("itl_p50_ms", "/itl/p50"), + ("cache_read_tokens_avg", "/cache_read_tokens/avg"), + ( + "peak_process_rss_bytes", + "/memory/sampled_peak_process_rss_bytes", + ), + ( + "peak_process_footprint_bytes", + "/memory/sampled_peak_process_physical_footprint_bytes", + ), + ( + "peak_cuda_process_accounted_bytes", + "/memory/sampled_peak_cuda_process_accounted_memory_bytes", + ), + ] { + if let Some(value) = cell.pointer(pointer).and_then(Value::as_f64) { + if !value.is_finite() || value < 0.0 { + return Err("nonfinite/negative publication metric".into()); + } + metrics.insert(format!("{prefix}.{name}"), value); + } + } + metrics.insert(format!("{prefix}.requests"), 69.0); + metrics.insert(format!("{prefix}.output_tokens"), 18713.0); + Ok(metrics) +} + pub(super) fn validate_experiment(value: &Value) -> DynResult<()> { let experiment = &value["experiment"]; if experiment["experiment_id"] != EXPERIMENT @@ -228,6 +269,7 @@ pub(super) fn validate_plan(plan: &Plan) -> DynResult<()> { } plan.report.verify()?; plan.archive.verify()?; + validate_archive(&plan.archive, &plan.report.sha256)?; let report: Value = serde_json::from_slice(&crate::automation::receipt_files::bounded( &plan.report.path, 4 * 1024 * 1024, @@ -245,6 +287,34 @@ pub(super) fn validate_plan(plan: &Plan) -> DynResult<()> { Ok(()) } +fn validate_archive(archive: &File, report_sha256: &str) -> DynResult<()> { + let decoder = flate2::read::GzDecoder::new(std::fs::File::open(&archive.path)?); + let mut archive = tar::Archive::new(decoder); + let mut found = false; + for (index, entry) in archive.entries()?.enumerate() { + if index >= 250_000 { + return Err("AgentX archive exceeds entry bound".into()); + } + let mut entry = entry?; + if entry.path()?.as_ref() != Path::new("agentx/result.json") { + continue; + } + if found || !entry.header().entry_type().is_file() || entry.size() > 4 * 1024 * 1024 { + return Err("AgentX archive requires one bounded regular campaign report".into()); + } + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes)?; + if super::inputs::digest(&bytes) != report_sha256 { + return Err("AgentX archive report differs from publication report".into()); + } + found = true; + } + if !found { + return Err("AgentX archive campaign report missing".into()); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -300,9 +370,60 @@ mod tests { ] { assert!(plan.tags.contains_key(tag), "{tag}"); } + assert!(!plan.tags.contains_key("ax.diagnostic_generation_lanes")); + for pointer in ["/ttft/p50", "/ttft/p95", "/itl/p50"] { + let mut missing = report.clone(); + *missing["arms"][0]["cells"][0].pointer_mut(pointer).unwrap() = Value::Null; + assert!(build(&missing, input()).is_err(), "{pointer}"); + } + let mut diagnostic = report.clone(); + diagnostic["request"]["tools"]["diagnostic_generation_lanes"] = json!(2); + assert!(build(&diagnostic, input()).is_err()); + diagnostic["scope"] = json!("diagnostic_generation_lanes_AgentX_comparison"); + let diagnostic = build(&diagnostic, input()).unwrap(); + assert_eq!(diagnostic.tags["ax.diagnostic_generation_lanes"], "2"); + assert_ne!(diagnostic.run_key, plan.run_key); + assert_ne!(diagnostic.campaign_root.run_key, plan.campaign_root.run_key); report["request"]["tools"]["runtime"]["sha256"] = Value::Null; assert!(build(&report, input()).is_err()); report["scope"] = json!("cpu_diagnostic_not_gpu_performance"); assert!(build(&report, input()).is_err()); } + + #[test] + fn archive_must_contain_exactly_the_published_campaign_report() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("campaign.tar.gz"); + let report = br#"{"campaign":"one","status":"passed"}"#; + let write_archive = |reports: &[&[u8]]| { + let encoder = flate2::write::GzEncoder::new( + std::fs::File::create(&path).unwrap(), + flate2::Compression::fast(), + ); + let mut tar = tar::Builder::new(encoder); + for report in reports { + let mut header = tar::Header::new_gnu(); + header.set_size(report.len() as u64); + header.set_mode(0o600); + header.set_cksum(); + tar.append_data(&mut header, "agentx/result.json", *report) + .unwrap(); + } + tar.into_inner().unwrap().finish().unwrap(); + }; + let archive = File { + path: path.clone(), + sha256: String::new(), + }; + let sha = super::super::inputs::digest(report); + write_archive(&[report]); + validate_archive(&archive, &sha).unwrap(); + assert!( + validate_archive(&archive, &super::super::inputs::digest(b"another campaign")).is_err() + ); + write_archive(&[report, report]); + assert!(validate_archive(&archive, &sha).is_err()); + write_archive(&[]); + assert!(validate_archive(&archive, &sha).is_err()); + } } diff --git a/tools/xtask/src/automation/agentx/mlflow_publish.rs b/tools/xtask/src/automation/agentx/mlflow_publish.rs index d3574e4e0a..240df4a19e 100644 --- a/tools/xtask/src/automation/agentx/mlflow_publish.rs +++ b/tools/xtask/src/automation/agentx/mlflow_publish.rs @@ -229,10 +229,55 @@ fn run_id(run: &Value) -> DynResult<&str> { fn now() -> DynResult { Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()) } + +fn publication_lock( + root: &Path, + tracking_uri: &str, + campaign_key: &str, +) -> DynResult { + if !root.is_absolute() || !root.is_dir() { + return Err( + "AgentX publication lock directory must be an existing absolute shared directory" + .into(), + ); + } + let tracking_root = url::Url::parse(tracking_uri)?.join("/")?; + let key = inputs::digest(&serde_json::to_vec(&( + tracking_root.as_str(), + campaign_key, + ))?); + let path = root.join(format!("agentx-{key}.lock")); + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW).mode(0o600); + } + let file = options.open(path)?; + if !file.metadata()?.is_file() { + return Err("AgentX publication lock must be a regular file".into()); + } + // No indefinite lock wait: concurrent publishers fail before any API write + // and can retry once the existing campaign publication releases the lock. + file.try_lock() + .map_err(|_| "AgentX campaign publication is busy or shared locking failed")?; + // Keep the file in place after unlock so other processes always lock the + // same inode; deleting it would allow concurrent independent lock owners. + Ok(file) +} + pub(super) fn run(plan: Plan, output: &Path) -> DynResult<()> { mlflow_export::validate_plan(&plan)?; std::fs::create_dir(output)?; let mut client = Client::new(output)?; + let lock_root = std::env::var_os("AGENTX_MLFLOW_LOCK_DIR") + .ok_or("AGENTX_MLFLOW_LOCK_DIR must identify the shared publication lock directory")?; + let _lock = publication_lock( + Path::new(&lock_root), + client.base.as_str(), + &plan.campaign_root.run_key, + )?; let existing = client.request( "/api/2.0/mlflow/experiments/get?experiment_id=6", "GET", @@ -284,3 +329,88 @@ pub(super) fn run(plan: Plan, output: &Path) -> DynResult<()> { "plan_sha256":inputs::digest(&serde_json::to_vec(&plan)?)}), ) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn campaign_publications_share_a_lock_across_output_directories() { + let root = tempfile::tempdir().unwrap(); + let first = + publication_lock(root.path(), "https://tracking.example/", "campaign:root").unwrap(); + assert!( + publication_lock(root.path(), "https://tracking.example/", "campaign:root").is_err() + ); + assert!( + publication_lock( + root.path(), + "https://tracking.example/prefix/", + "campaign:root" + ) + .is_err() + ); + assert!(publication_lock(root.path(), "https://tracking.example/", "other:root").is_ok()); + assert!(publication_lock(root.path(), "https://other.example/", "campaign:root").is_ok()); + drop(first); + assert!( + publication_lock(root.path(), "https://tracking.example/", "campaign:root").is_ok() + ); + assert!( + publication_lock( + Path::new("relative"), + "https://tracking.example/", + "campaign:root" + ) + .is_err() + ); + } + + #[test] + fn publication_lock_child() { + let Some(root) = std::env::var_os("AGENTX_LOCK_TEST_ROOT") else { + return; + }; + let busy = std::env::var_os("AGENTX_LOCK_TEST_BUSY").is_some(); + assert_eq!( + publication_lock( + Path::new(&root), + "https://tracking.example/alias/", + "campaign:root" + ) + .is_err(), + busy + ); + } + + #[test] + fn campaign_lock_excludes_an_independent_publication_process() { + let root = tempfile::tempdir().unwrap(); + let lock = + publication_lock(root.path(), "https://tracking.example/", "campaign:root").unwrap(); + let executable = std::env::current_exe().unwrap(); + let mut spec = command::spec( + root.path(), + executable.to_str().unwrap(), + &[ + "--exact".into(), + "automation::agentx::mlflow_publish::tests::publication_lock_child".into(), + "--test-threads=1".into(), + ], + ) + .unwrap(); + spec.environment.insert( + "AGENTX_LOCK_TEST_ROOT".into(), + crate::process::Value::Public(root.path().into()), + ); + spec.environment.insert( + "AGENTX_LOCK_TEST_BUSY".into(), + crate::process::Value::Public("1".into()), + ); + command::run(&spec, 30, &root.path().join("busy-child")).unwrap(); + drop(lock); + spec.environment + .remove(std::ffi::OsStr::new("AGENTX_LOCK_TEST_BUSY")); + command::run(&spec, 30, &root.path().join("released-child")).unwrap(); + } +} diff --git a/tools/xtask/src/automation/agentx/mod.rs b/tools/xtask/src/automation/agentx/mod.rs index 487bb603f1..98beb9ebfb 100644 --- a/tools/xtask/src/automation/agentx/mod.rs +++ b/tools/xtask/src/automation/agentx/mod.rs @@ -6,7 +6,6 @@ mod capacity; mod command; mod comparison_cohort; mod completed_work; -mod container; mod contention_cohort; mod context_support; mod final_sweep; @@ -25,6 +24,7 @@ mod prepared_launch; mod prepared_tools; mod results; mod scheduler_profile; +mod standard_runtime; mod trace_context; mod workload; use crate::{command::DynResult, repository::check_args::Grammar}; @@ -56,15 +56,6 @@ impl Profile { Self::Contention => "contention", } } - fn parse(value: &str) -> DynResult { - match value { - "smoke" => Ok(Self::Smoke), - "benchmark" => Ok(Self::Benchmark), - "comparison" => Ok(Self::Comparison), - "contention" => Ok(Self::Contention), - _ => Err("profile must be smoke, benchmark, comparison or contention".into()), - } - } fn concurrencies(self) -> &'static [u32] { // Offered load is independent of engine-planned serving capacity. match self { @@ -79,13 +70,6 @@ pub(super) enum Engine { Skippy, } impl Engine { - fn parse(value: &str) -> DynResult { - match value { - "llama" => Ok(Self::Llama), - "skippy" => Ok(Self::Skippy), - _ => Err("engine must be llama or skippy".into()), - } - } fn label(self) -> &'static str { match self { Self::Llama => "llama", @@ -141,17 +125,8 @@ pub(crate) fn run(args: &[String]) -> DynResult<()> { return Err("AgentX accepts comparison --input JSON --output DIR or mlflow-export; legacy unpinned launch modes are not admitted".into()); } const GRAMMAR: Grammar = Grammar { - usage: "cargo xtool automation agentx {container|run} --engine {llama|skippy} --model KEY --profile {smoke|benchmark|comparison|contention} --output PATH [--only-concurrency N] | worker --input PATH --port PORT --concurrency N", - values: &[ - "--model", - "--engine", - "--profile", - "--output", - "--input", - "--port", - "--concurrency", - "--only-concurrency", - ], + usage: "cargo xtool automation agentx worker --input PATH --port PORT --concurrency N", + values: &["--input", "--port", "--concurrency"], flags: &["--help"], }; let parsed = GRAMMAR @@ -161,45 +136,6 @@ pub(crate) fn run(args: &[String]) -> DynResult<()> { return crate::repository::check_report::CheckReport::success(GRAMMAR.usage.into()).emit(); } match parsed.positionals.as_slice() { - [verb] if *verb == "container" => { - if parsed.last("--only-concurrency").is_some() { - return Err( - "only-concurrency applies to a native run, not a container launch".into(), - ); - } - container::run( - Engine::parse(parsed.last("--engine").ok_or("missing engine")?)?, - parsed.last("--model").ok_or("missing model")?, - Profile::parse(parsed.last("--profile").ok_or("missing profile")?)?, - PathBuf::from(parsed.last("--output").ok_or("missing output")?), - ) - } - [verb] if *verb == "run" => { - hardware::admit_execution()?; - let root = std::env::current_dir()?; - let profile = Profile::parse(parsed.last("--profile").ok_or("missing profile")?)?; - let output = PathBuf::from(parsed.last("--output").ok_or("missing output")?); - if !output.is_absolute() { - return Err("output must be absolute".into()); - } - std::fs::create_dir(&output)?; - let engine = Engine::parse(parsed.last("--engine").ok_or("missing engine")?)?; - let only_concurrency = parsed - .last("--only-concurrency") - .map(str::parse::) - .transpose()?; - let prepared = inputs::prepare( - root, - output.clone(), - parsed.last("--model").ok_or("missing model")?, - profile, - ); - let result = - prepared.and_then(|prepared| campaign::run(&prepared, engine, only_concurrency)); - let archive = results::archive(&output); - result?; - archive - } [verb] if *verb == "worker" => { let prepared: Prepared = serde_json::from_slice(&std::fs::read( parsed.last("--input").ok_or("missing input")?, diff --git a/tools/xtask/src/automation/agentx/prepared_tools.rs b/tools/xtask/src/automation/agentx/prepared_tools.rs index c53898cfc2..22738fc026 100644 --- a/tools/xtask/src/automation/agentx/prepared_tools.rs +++ b/tools/xtask/src/automation/agentx/prepared_tools.rs @@ -98,6 +98,13 @@ impl Tree { { return Err("prepared trees require regular files or regular-file links".into()); } + if entry + .path() + .extension() + .is_some_and(|extension| extension == "pth") + { + verify_python_path_file(&entry.path(), &root)?; + } } } if count == 0 { @@ -121,6 +128,29 @@ impl Tree { Ok(hex::encode(hash.finalize())) } } + +fn verify_python_path_file(path: &Path, root: &Path) -> DynResult<()> { + let bytes = crate::automation::receipt_files::bounded(&path.canonicalize()?, 1024 * 1024)?; + for line in std::str::from_utf8(&bytes)?.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + // .pth import statements execute arbitrary code before AgentX starts; + // a tree hash cannot establish that they preserve module ownership. + if line.starts_with("import ") || line.starts_with("import\t") { + return Err("prepared environment cannot contain executable .pth imports".into()); + } + let target = path + .parent() + .ok_or(".pth parent missing")? + .join(line) + .canonicalize()?; + if !target.starts_with(root) { + return Err("prepared .pth path escapes its environment".into()); + } + } + Ok(()) +} #[derive(Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub(super) struct Tools { @@ -194,6 +224,7 @@ impl Tools { ] { tree.verify()?; } + super::standard_runtime::verify(&self.llama.path, &self.standard_runtime.path)?; let lock = std::fs::read(root.join("skippy/evals/agentx/uv.lock"))?; if super::inputs::digest(&lock) != self.client_lock.sha256 { return Err("client lock differs from the owned external AgentX lock".into()); @@ -205,16 +236,22 @@ impl Tools { } let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(self.runtime.path.join("manifest.json"))?)?; - self.validate_manifest(&manifest) + let ffi = std::fs::read(root.join("skippy/crates/skippy-ffi/src/lib.rs"))?; + let abi = crate::native_policy::package_version::abi_version(&ffi)?.to_string(); + self.validate_manifest(&manifest, &abi) } - pub(super) fn validate_manifest(&self, manifest: &serde_json::Value) -> DynResult<()> { + pub(super) fn validate_manifest( + &self, + manifest: &serde_json::Value, + abi: &str, + ) -> DynResult<()> { if manifest["runtime"]["backend"]["kind"] != self.backend.name() || manifest["build"]["llama_patched_sha"] != self.native_source_commit || manifest["build"]["llama_patch_digest"] != self.native_patch_digest || manifest["build"]["llama_upstream_sha"] != self.standard_upstream - || manifest["runtime"]["skippy_abi"] != "0.1.76" + || manifest["runtime"]["skippy_abi"] != abi { - return Err("runtime must be exact matching ABI76 backend/native leaf".into()); + return Err("runtime must match the owning FFI ABI, backend and native leaf".into()); } Ok(()) } diff --git a/tools/xtask/src/automation/agentx/standard_runtime.rs b/tools/xtask/src/automation/agentx/standard_runtime.rs new file mode 100644 index 0000000000..827eb4993f --- /dev/null +++ b/tools/xtask/src/automation/agentx/standard_runtime.rs @@ -0,0 +1,355 @@ +//! Admit the baseline's actual native dependency closure without executing it. +use crate::command::DynResult; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; + +struct Imports { + libraries: Vec, + search: Vec, + macho: bool, +} + +pub(super) fn verify(executable: &Path, runtime: &Path) -> DynResult<()> { + let root = runtime.canonicalize()?; + let executable = admitted_executable(executable, &root)?; + let mut pending = vec![executable.clone()]; + pending.extend(runtime_libraries(&root)?); + let mut visited = BTreeSet::new(); + let executable_dir = executable + .parent() + .ok_or("baseline executable parent missing")?; + let main = inspect(&executable)?; + let inherited = search_paths(&main.search, executable_dir, executable_dir, &root)?; + while let Some(path) = pending.pop() { + if !visited.insert(path.clone()) { + continue; + } + if visited.len() > 2048 { + return Err("standard runtime native closure exceeds object bound".into()); + } + let image = inspect(&path)?; + let origin = path.parent().ok_or("baseline library parent missing")?; + let mut search = search_paths(&image.search, origin, executable_dir, &root)?; + // Mach-O uses the run-path stack. ELF shared objects must carry their + // own pinned search paths; RUNPATH is not transitive. + if image.macho { + search.extend(inherited.iter().cloned()); + } + for library in &image.libraries { + if system_library(library, image.macho) { + continue; + } + pending.push(resolve( + library, + &search, + origin, + executable_dir, + &root, + image.macho, + )?); + } + } + Ok(()) +} + +pub(super) fn admitted_executable(executable: &Path, runtime: &Path) -> DynResult { + let path = contained(executable, &runtime.canonicalize()?)?; + if !path.is_file() { + return Err( + "baseline executable must be a regular file in the pinned standard runtime".into(), + ); + } + Ok(path) +} + +fn runtime_libraries(root: &Path) -> DynResult> { + let mut libraries = Vec::new(); + let mut directories = vec![root.to_path_buf()]; + let mut count = 0usize; + // Backends can be opened by ggml rather than DT_NEEDED. Verify their + // dependencies as well, before accepting the tree as an offline baseline. + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory)? { + let entry = entry?; + count += 1; + if count > 250_000 { + return Err("standard runtime exceeds entry bound".into()); + } + if entry.file_type()?.is_dir() { + directories.push(entry.path()); + } else if is_library(&entry.path()) { + libraries.push(contained(&entry.path(), root)?); + } + } + } + Ok(libraries) +} + +fn is_library(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + name.ends_with(".dylib") || name.ends_with(".so") || name.contains(".so.") + }) +} + +fn inspect(path: &Path) -> DynResult { + let bytes = crate::automation::receipt_files::bounded(path, 512 * 1024 * 1024)?; + match goblin::Object::parse(&bytes)? { + goblin::Object::Elf(image) => Ok(Imports { + libraries: image + .libraries + .iter() + .map(|value| (*value).into()) + .collect(), + search: if image.runpaths.is_empty() { + image.rpaths + } else { + image.runpaths + } + .iter() + .flat_map(|paths| paths.split(':').map(str::to_owned)) + .collect(), + macho: false, + }), + goblin::Object::Mach(goblin::mach::Mach::Binary(image)) => Ok(mach_imports(&image)), + goblin::Object::Mach(goblin::mach::Mach::Fat(images)) => { + let cpu = if std::env::consts::ARCH == "aarch64" { + goblin::mach::constants::cputype::CPU_TYPE_ARM64 + } else { + goblin::mach::constants::cputype::CPU_TYPE_X86_64 + }; + let image = images + .find(|arch| arch.is_ok_and(|arch| arch.cputype == cpu)) + .ok_or("standard runtime lacks the host Mach-O architecture")??; + match image { + goblin::mach::SingleArch::MachO(image) => Ok(mach_imports(&image)), + _ => Err("standard runtime Mach-O archive is not a dynamic image".into()), + } + } + _ => Err("standard baseline requires ELF or Mach-O native images".into()), + } +} + +fn mach_imports(image: &goblin::mach::MachO<'_>) -> Imports { + Imports { + libraries: image + .libs + .iter() + .filter(|value| **value != "self") + .map(|value| (*value).into()) + .collect(), + search: image.rpaths.iter().map(|value| (*value).into()).collect(), + macho: true, + } +} + +fn contained(path: &Path, root: &Path) -> DynResult { + let path = path.canonicalize()?; + if !path.starts_with(root) { + return Err("baseline native dependency escapes the pinned standard runtime".into()); + } + Ok(path) +} + +fn expand(path: &str, origin: &Path, executable: &Path) -> DynResult { + for (token, base) in [ + ("${ORIGIN}", origin), + ("$ORIGIN", origin), + ("@loader_path", origin), + ("@executable_path", executable), + ] { + if path == token { + return Ok(base.into()); + } + if let Some(relative) = path.strip_prefix(&format!("{token}/")) { + return Ok(base.join(relative)); + } + } + let path = Path::new(path); + if !path.is_absolute() { + return Err("baseline dependency uses an unbound loader search path".into()); + } + Ok(path.into()) +} + +fn search_paths( + paths: &[String], + origin: &Path, + executable: &Path, + root: &Path, +) -> DynResult> { + paths + .iter() + .map(|path| contained(&expand(path, origin, executable)?, root)) + .collect() +} + +fn resolve( + library: &str, + search: &[PathBuf], + origin: &Path, + executable: &Path, + root: &Path, + macho: bool, +) -> DynResult { + let candidate = if let Some(name) = library.strip_prefix("@rpath/") { + search + .iter() + .map(|dir| dir.join(name)) + .find(|path| path.is_file()) + } else if library.contains('/') { + Some(expand(library, origin, executable)?) + } else if macho { + None + } else { + search + .iter() + .map(|dir| dir.join(library)) + .find(|path| path.is_file()) + } + .ok_or("baseline native dependency is absent from its pinned loader search path")?; + let resolved = contained(&candidate, root)?; + if !resolved.is_file() { + return Err("baseline native dependency is not a regular file".into()); + } + Ok(resolved) +} + +fn system_library(library: &str, macho: bool) -> bool { + if macho { + (library.starts_with("/usr/lib/") || library.starts_with("/System/Library/")) + && !library.split('/').any(|part| matches!(part, "." | "..")) + } else { + crate::native_policy::host_owned_linux_library(library) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn elf(path: &Path, library: Option<&str>, runpath: Option<&str>) { + use goblin::elf::{dynamic, header, program_header}; + let mut bytes = vec![0u8; 1024]; + bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + bytes[16..18].copy_from_slice(&header::ET_DYN.to_le_bytes()); + bytes[18..20].copy_from_slice(&header::EM_AARCH64.to_le_bytes()); + bytes[20..24].copy_from_slice(&1u32.to_le_bytes()); + bytes[32..40].copy_from_slice(&64u64.to_le_bytes()); + bytes[52..54].copy_from_slice(&64u16.to_le_bytes()); + bytes[54..56].copy_from_slice(&56u16.to_le_bytes()); + bytes[56..58].copy_from_slice(&2u16.to_le_bytes()); + bytes[64..68].copy_from_slice(&program_header::PT_LOAD.to_le_bytes()); + bytes[96..104].copy_from_slice(&1024u64.to_le_bytes()); + bytes[104..112].copy_from_slice(&1024u64.to_le_bytes()); + bytes[120..124].copy_from_slice(&program_header::PT_DYNAMIC.to_le_bytes()); + bytes[128..136].copy_from_slice(&176u64.to_le_bytes()); + bytes[136..144].copy_from_slice(&176u64.to_le_bytes()); + let mut strings = vec![0u8]; + let mut tags = vec![(dynamic::DT_STRTAB, 512u64)]; + for (tag, value) in [ + (dynamic::DT_NEEDED, library), + (dynamic::DT_RUNPATH, runpath), + ] { + if let Some(value) = value { + tags.push((tag, strings.len() as u64)); + strings.extend_from_slice(value.as_bytes()); + strings.push(0); + } + } + tags.push((dynamic::DT_STRSZ, strings.len() as u64)); + tags.push((dynamic::DT_NULL, 0)); + bytes[152..160].copy_from_slice(&((tags.len() * 16) as u64).to_le_bytes()); + bytes[160..168].copy_from_slice(&((tags.len() * 16) as u64).to_le_bytes()); + for (index, (tag, value)) in tags.into_iter().enumerate() { + let offset = 176 + index * 16; + bytes[offset..offset + 8].copy_from_slice(&tag.to_le_bytes()); + bytes[offset + 8..offset + 16].copy_from_slice(&value.to_le_bytes()); + } + bytes[512..512 + strings.len()].copy_from_slice(&strings); + std::fs::write(path, bytes).unwrap(); + } + + #[test] + fn inspected_elf_closure_requires_its_actual_needed_library_inside_the_pin() { + let dir = tempfile::tempdir().unwrap(); + let binary = dir.path().join("llama-server"); + let library = dir.path().join("libggml.so"); + elf(&binary, Some("libggml.so"), Some("$ORIGIN")); + elf(&library, None, None); + let imports = inspect(&binary).unwrap(); + assert_eq!(imports.libraries, ["libggml.so"]); + assert_eq!(imports.search, ["$ORIGIN"]); + verify(&binary, dir.path()).unwrap(); + std::fs::remove_file(library).unwrap(); + assert!(verify(&binary, dir.path()).is_err()); + elf(&binary, Some("libggml.so"), Some("/usr/lib")); + assert!(verify(&binary, dir.path()).is_err()); + } + + #[test] + fn baseline_executable_and_plugin_directory_must_be_in_the_hashed_tree() { + let pin = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + let binary = external.path().join("llama-server"); + elf(&binary, None, None); + elf(&external.path().join("libggml-cpu.so"), None, None); + assert!(verify(&binary, pin.path()).is_err()); + let pinned_binary = pin.path().join("llama-server"); + elf(&pinned_binary, None, None); + verify(&pinned_binary, pin.path()).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink(&binary, pin.path().join("external-server")).unwrap(); + assert!(verify(&pin.path().join("external-server"), pin.path()).is_err()); + } + } + + #[test] + fn loader_resolution_rejects_external_and_unreachable_libraries() { + let tree = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + let root = tree.path().canonicalize().unwrap(); + std::fs::write(root.join("libggml.so"), b"library").unwrap(); + std::fs::write(external.path().join("libggml.so"), b"foreign").unwrap(); + let search = search_paths(&["$ORIGIN".into()], &root, &root, &root).unwrap(); + assert_eq!( + resolve("libggml.so", &search, &root, &root, &root, false).unwrap(), + root.join("libggml.so") + ); + assert!(resolve("libggml.so", &[], &root, &root, &root, false).is_err()); + assert!( + search_paths( + &[external.path().to_string_lossy().into()], + &root, + &root, + &root + ) + .is_err() + ); + assert!( + resolve( + external.path().join("libggml.so").to_str().unwrap(), + &search, + &root, + &root, + &root, + false + ) + .is_err() + ); + assert!(!system_library("libggml.so", false)); + assert!(system_library("libc.so.6", false)); + #[cfg(unix)] + { + std::os::unix::fs::symlink( + external.path().join("libggml.so"), + root.join("libforeign.so"), + ) + .unwrap(); + assert!(resolve("libforeign.so", &search, &root, &root, &root, false).is_err()); + } + } +} diff --git a/tools/xtask/src/automation/kv_validation/contract.rs b/tools/xtask/src/automation/kv_validation/contract.rs index da6e1c5f77..536da5e542 100644 --- a/tools/xtask/src/automation/kv_validation/contract.rs +++ b/tools/xtask/src/automation/kv_validation/contract.rs @@ -69,6 +69,9 @@ pub(super) struct Producer { } impl Producer { pub(super) fn verify(&self) -> DynResult<()> { + if cfg!(windows) { + return Err("KV validation supports Linux and macOS only; Windows private graph helpers are not exported".into()); + } if self.schema_version != 1 || !sha(&self.native_source_commit, 40) { return Err("invalid KV producer schema/source".into()); } @@ -95,8 +98,39 @@ impl Producer { self.backend, &self.native_source_commit, )?; + self.verify_serving_runtime()?; Ok(()) } + + fn verify_serving_runtime(&self) -> DynResult<()> { + let temporary = tempfile::tempdir()?; + let runtimes = temporary.path().join("runtime-parent"); + std::fs::create_dir(&runtimes)?; + #[cfg(unix)] + std::os::unix::fs::symlink(&self.runtime_bundle, runtimes.join("selected-runtime"))?; + #[cfg(windows)] + std::os::windows::fs::symlink_dir(&self.runtime_bundle, runtimes.join("selected-runtime"))?; + let test = "frontend::local_generation::tests::recurrent_fixture::kv_validation_dynamic_runtime_identity"; + let text = super::execution::child( + &self.serving_tests.path, + vec![ + "--exact".into(), + test.into(), + "--ignored".into(), + "--nocapture".into(), + "--test-threads=1".into(), + ], + (temporary.path(), temporary.path()), + "serving-runtime-identity", + std::time::Duration::from_secs(30), + &crate::process::Cancellation::default(), + &[( + "MESH_LLM_NATIVE_RUNTIME_BUNDLE_DIR", + runtimes.into_os_string(), + )], + )?; + super::evidence::rust_test(&text, test) + } } #[derive(Deserialize, Serialize)] @@ -108,10 +142,29 @@ pub(super) struct Prepared { pub matrix: Tool, } impl Prepared { - pub(super) fn verify(&self) -> DynResult<()> { - if self.schema_version != 1 || self.catalog_sha256 != CATALOG_SHA { + pub(super) fn read_for_plan(tool: &Tool) -> DynResult { + tool.verify()?; + let prepared: Self = serde_json::from_slice(&crate::automation::receipt_files::bounded( + &tool.path, + 1024 * 1024, + )?)?; + prepared.validate()?; + Ok(prepared) + } + + fn validate(&self) -> DynResult<()> { + if self.schema_version != 1 + || self.catalog_sha256 != CATALOG_SHA + || self.producer.schema_version != 1 + || !sha(&self.producer.native_source_commit, 40) + { return Err("KV prepared receipt catalog/schema mismatch".into()); } + Ok(()) + } + + pub(super) fn verify(&self) -> DynResult<()> { + self.validate()?; self.producer.verify()?; self.matrix.verify() } diff --git a/tools/xtask/src/automation/kv_validation/execution.rs b/tools/xtask/src/automation/kv_validation/execution.rs index 575ee2f47a..6218994068 100644 --- a/tools/xtask/src/automation/kv_validation/execution.rs +++ b/tools/xtask/src/automation/kv_validation/execution.rs @@ -12,11 +12,11 @@ use serde_json::json; use std::{ collections::BTreeMap, ffi::OsString, - path::Path, + path::{Path, PathBuf}, time::{Duration, Instant}, }; #[path = "server.rs"] -mod server; +pub(super) mod server; pub(super) fn environment(extra: &[(&str, OsString)]) -> BTreeMap { let mut env: BTreeMap<_, _> = [ @@ -105,22 +105,36 @@ pub(super) fn run(input: Cell, output: &Path) -> DynResult<()> { let interrupt = crate::automation::command_interrupt::Interrupt::install()?; let deadline = Instant::now() + Duration::from_secs(input.execution_seconds); let result = execute(&input, output, deadline, &interrupt.cancellation()); - let finish = interrupt.finish(); - let passed = result.is_ok() && finish.is_ok() && Instant::now() < deadline; + let finish = interrupt.finish().map_err(Into::into); + finalize(&input, output, deadline, result, finish, archive) +} + +pub(super) fn finalize( + input: &Cell, + output: &Path, + deadline: Instant, + result: DynResult<()>, + finish: DynResult<()>, + archive_evidence: impl FnOnce(&Path) -> DynResult<()>, +) -> DynResult<()> { + // The final result is deliberately outside the archive: only after archive + // traversal, compression and hashing finish can the deadline be evaluated. + let archived = archive_evidence(output); + let passed = result.is_ok() && finish.is_ok() && archived.is_ok() && Instant::now() < deadline; publish( &output.join("result.json"), &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"scope":"KVdtype_dispatch_generic_c1_cache_plus_recurrent_runtime_L3_restart_not_long_c4_process_restart_or_performance"}), )?; - archive(output)?; finish?; result?; + archived?; if !passed { return Err("KV validation deadline exceeded".into()); } Ok(()) } pub(super) fn archive(output: &Path) -> DynResult<()> { - let path = output.with_extension("tar.gz"); + let path = sibling(output, ".tar.gz")?; let archive_name = path .file_name() .and_then(|name| name.to_str()) @@ -151,10 +165,18 @@ pub(super) fn archive(output: &Path) -> DynResult<()> { tar.into_inner()?.finish()?; let sha256 = crate::product::digest::file_sha256(&path).map_err(|e| e.error)?; publish( - &output.with_extension("archive.json"), - &json!({"archive":archive_name,"sha256":sha256,"symlinks":"excluded; selected runtime identity retained in JSON"}), + &sibling(output, ".archive.json")?, + &json!({"archive":archive_name,"sha256":sha256,"final_result":"result.json is published after archiving as a separate sidecar","symlinks":"excluded; selected runtime identity retained in JSON"}), ) } +fn sibling(output: &Path, suffix: &str) -> DynResult { + let mut name = output + .file_name() + .ok_or("KV output requires a directory name")? + .to_os_string(); + name.push(suffix); + Ok(output.with_file_name(name)) +} fn remaining(deadline: Instant) -> DynResult { deadline .saturating_duration_since(Instant::now()) diff --git a/tools/xtask/src/automation/kv_validation/jy_plan.rs b/tools/xtask/src/automation/kv_validation/jy_plan.rs index 95d2ea170d..425c3f81fa 100644 --- a/tools/xtask/src/automation/kv_validation/jy_plan.rs +++ b/tools/xtask/src/automation/kv_validation/jy_plan.rs @@ -1,6 +1,6 @@ //! Manual JY specs using the observed lab/custom schema, not a new CI provider. use super::{ - contract::{self, Backend, Cell, Tool}, + contract::{self, Backend, Cell, Prepared, Tool}, publish, }; use crate::command::DynResult; @@ -52,6 +52,10 @@ impl Fleet { if !contract::sha(&self.prepared.sha256, 64) { return Err("JY prepared receipt SHA required".into()); } + let prepared = Prepared::read_for_plan(&self.prepared)?; + if prepared.producer.backend != self.backend { + return Err("JY fleet backend differs from prepared producer backend".into()); + } let mut ids = BTreeSet::new(); let mut hosts = BTreeSet::new(); for node in &self.nodes { diff --git a/tools/xtask/src/automation/kv_validation/server.rs b/tools/xtask/src/automation/kv_validation/server.rs index 602d90b3fb..0492ae8840 100644 --- a/tools/xtask/src/automation/kv_validation/server.rs +++ b/tools/xtask/src/automation/kv_validation/server.rs @@ -26,6 +26,38 @@ struct Owner { cache_evidence: Option, duplicate_evidence: bool, } + +#[cfg(test)] +pub(in crate::automation::kv_validation) fn verify_captured_client_stdout( + text: &str, +) -> DynResult<()> { + let mut owner = Owner { + server: None, + client: None, + ready: false, + stopping: false, + port: 19337, + cache_evidence: None, + duplicate_evidence: false, + }; + for line in text.lines() { + owner.captured_line( + MemberId::WorkerOne, + ObservedLine { + stream: Stream::Stdout, + bytes: line.as_bytes(), + ending: process::LineEnding::Lf, + }, + ); + } + if owner.duplicate_evidence { + return Err("generic cache client emitted duplicate evidence".into()); + } + owner + .cache_evidence + .ok_or("generic cache client evidence missing")? + .verify() +} impl Coordinator for Owner { type Rejection = String; fn captured_line(&mut self, member: MemberId, line: ObservedLine<'_>) { diff --git a/tools/xtask/src/automation/kv_validation/tests.rs b/tools/xtask/src/automation/kv_validation/tests.rs index 69458b06d9..0ec2f0e653 100644 --- a/tools/xtask/src/automation/kv_validation/tests.rs +++ b/tools/xtask/src/automation/kv_validation/tests.rs @@ -1,5 +1,5 @@ use super::{ - contract::{self, Backend, Cell, Tool}, + contract::{self, Backend, Cell, Prepared, Producer, Tool}, evidence, execution, jy_plan, }; use std::path::PathBuf; @@ -282,10 +282,7 @@ fn accepted_jy_envelope_keeps_all_four_pins_and_never_submits() { source_commit: "1".repeat(40), prepared_image: format!("sha256:{}", "2".repeat(64)), automation: "/opt/xtask".into(), - prepared: Tool { - path: "/opt/prepared.json".into(), - sha256: "3".repeat(64), - }, + prepared: prepared_receipt(dir.path(), Backend::Cuda), nodes: vec![jy_plan::Node { id: "spark-000137".into(), hostname: "spark-james".into(), @@ -319,6 +316,151 @@ fn accepted_jy_envelope_keeps_all_four_pins_and_never_submits() { assert_eq!(std::fs::read_dir(output).unwrap().count(), 5); } +fn prepared_receipt(root: &std::path::Path, backend: Backend) -> Tool { + let tool = Tool { + path: root.join("tool"), + sha256: "3".repeat(64), + }; + let prepared = Prepared { + schema_version: 1, + catalog_sha256: contract::CATALOG_SHA.into(), + producer: Producer { + schema_version: 1, + backend, + workspace: root.into(), + native_source: root.join("native"), + native_source_commit: "4".repeat(40), + runtime_bundle: root.join("runtime"), + runtime_sha256: "5".repeat(64), + cli: tool.clone(), + correctness: tool.clone(), + serving_tests: tool.clone(), + just: root.join("just"), + cmake: root.join("cmake"), + }, + matrix: tool, + }; + let path = root.join("prepared.json"); + let bytes = serde_json::to_vec(&prepared).unwrap(); + std::fs::write(&path, &bytes).unwrap(); + Tool { + path, + sha256: super::hash(&bytes), + } +} + +#[test] +fn jy_plan_refuses_mismatched_backend_or_changed_prepared_receipt_before_writing_jobs() { + let dir = tempfile::tempdir().unwrap(); + let prepared = prepared_receipt(dir.path(), Backend::Cpu); + let mut input = jy_plan::Fleet { + schema_version: 1, + backend: Backend::Cuda, + source_commit: "1".repeat(40), + prepared_image: format!("sha256:{}", "2".repeat(64)), + automation: "/opt/xtask".into(), + prepared, + nodes: vec![jy_plan::Node { + id: "spark-000137".into(), + hostname: "spark-james".into(), + }], + execution_seconds: 1800, + }; + let output = dir.path().join("jobs"); + let error = jy_plan::run( + serde_json::from_value(serde_json::to_value(&input).unwrap()).unwrap(), + &output, + ) + .unwrap_err(); + assert!(error.to_string().contains("backend differs")); + assert!(!output.exists()); + input.backend = Backend::Cpu; + std::fs::write(&input.prepared.path, "{}").unwrap(); + assert!( + jy_plan::run(input, &output) + .unwrap_err() + .to_string() + .contains("SHA-256 mismatch") + ); + assert!(!output.exists()); +} + +#[test] +fn dotted_output_directories_keep_distinct_archive_names() { + let dir = tempfile::tempdir().unwrap(); + for name in ["trial.1", "trial.2"] { + let output = dir.path().join(name); + std::fs::create_dir(&output).unwrap(); + std::fs::write(output.join("evidence.txt"), name).unwrap(); + execution::archive(&output).unwrap(); + let archive = dir.path().join(format!("{name}.tar.gz")); + let receipt: serde_json::Value = serde_json::from_slice( + &std::fs::read(dir.path().join(format!("{name}.archive.json"))).unwrap(), + ) + .unwrap(); + assert_eq!(receipt["archive"], format!("{name}.tar.gz")); + assert_eq!( + receipt["sha256"], + super::hash(&std::fs::read(archive).unwrap()) + ); + } +} + +#[test] +fn final_result_is_published_after_archive_and_rejects_expired_deadline() { + let dir = tempfile::tempdir().unwrap(); + let input = Cell { + schema_version: 1, + prepared: Tool { + path: dir.path().join("prepared.json"), + sha256: "0".repeat(64), + }, + model_key: "qwen3.5-4b-q4-k-m".into(), + model: dir.path().join("model.gguf"), + port: 19337, + execution_seconds: 30, + }; + for (name, elapsed, archive_ok) in [ + ("elapsed", true, true), + ("good", false, true), + ("archive-failure", false, false), + ] { + let output = dir.path().join(name); + std::fs::create_dir(&output).unwrap(); + let deadline = if elapsed { + std::time::Instant::now() + } else { + std::time::Instant::now() + std::time::Duration::from_secs(60) + }; + let result = execution::finalize(&input, &output, deadline, Ok(()), Ok(()), |path| { + assert!( + !path.join("result.json").exists(), + "final status cannot precede archive completion" + ); + if archive_ok { + execution::archive(path) + } else { + Err("fixture archive failure".into()) + } + }); + assert_eq!(result.is_ok(), !elapsed && archive_ok); + let receipt: serde_json::Value = + serde_json::from_slice(&std::fs::read(output.join("result.json")).unwrap()).unwrap(); + assert_eq!( + receipt["status"], + if elapsed || !archive_ok { + "failed" + } else { + "passed" + } + ); + assert_eq!( + receipt["result_location"], + "post_archive_sidecar_not_in_evidence_archive" + ); + } +} + #[cfg(unix)] #[test] fn supervised_child_captures_success_and_refuses_failed_exit() { diff --git a/tools/xtask/src/automation/kv_validation/tests/cache_client.rs b/tools/xtask/src/automation/kv_validation/tests/cache_client.rs new file mode 100644 index 0000000000..2eb5130e1d --- /dev/null +++ b/tools/xtask/src/automation/kv_validation/tests/cache_client.rs @@ -0,0 +1,165 @@ +//! Cross-package executable/collector test; the binary is an explicit input. +use super::execution; +use crate::process::{self, Cancellation, ProcessSpec, RawCaptureOptions, Value}; +use std::{ + io::{Read, Write}, + net::{TcpListener, TcpStream}, + num::NonZeroUsize, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; + +struct Endpoint { + address: String, + stop: Arc, + worker: Option>, +} + +impl Endpoint { + fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("http://{}/v1", listener.local_addr().unwrap()); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = Arc::clone(&stop); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(30); + let mut count = 0; + while !stopped.load(Ordering::Acquire) && Instant::now() < deadline { + match listener.accept() { + Ok((mut stream, _)) => { + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + consume_request(&mut stream); + let content = if count < 2 { "round" } else { "sphere" }; + let cached = if count == 0 { 0 } else { 20 }; + let body = serde_json::json!({ + "choices":[{"message":{"content":content}}], + "usage":{"prompt_tokens":28,"prompt_tokens_details":{"cached_tokens":cached}} + }).to_string(); + write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); + count += 1; + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(2)) + } + Err(error) => panic!("fixture accept: {error}"), + } + } + count + }); + Self { + address, + stop, + worker: Some(worker), + } + } + + fn finish(mut self) -> usize { + self.stop.store(true, Ordering::Release); + self.worker.take().unwrap().join().unwrap() + } +} + +impl Drop for Endpoint { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +fn consume_request(stream: &mut TcpStream) { + let mut bytes = Vec::new(); + let mut chunk = [0; 1024]; + let header_end = loop { + let count = stream.read(&mut chunk).unwrap(); + assert!(count > 0); + bytes.extend_from_slice(&chunk[..count]); + assert!(bytes.len() < 32768); + if let Some(index) = bytes.windows(4).position(|value| value == b"\r\n\r\n") { + break index + 4; + } + }; + let length = std::str::from_utf8(&bytes[..header_end]) + .unwrap() + .lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap(); + assert!(header_end + length < 32768); + while bytes.len() < header_end + length { + let count = stream.read(&mut chunk).unwrap(); + assert!(count > 0); + bytes.extend_from_slice(&chunk[..count]); + } +} + +#[test] +#[ignore = "requires a prebuilt skippy-correctness binary in SKIPPY_KV_CORRECTNESS_TEST_BINARY"] +fn actual_correctness_stdout_is_admitted_by_the_cache_collector() { + let binary = std::env::var_os("SKIPPY_KV_CORRECTNESS_TEST_BINARY") + .expect("explicit prebuilt correctness binary"); + let binary = PathBuf::from(binary).canonicalize().unwrap(); + let root = tempfile::tempdir().unwrap(); + let prompt = root.path().join("prompt.txt"); + std::fs::write(&prompt, "A finite cache prefix.").unwrap(); + let peer = Endpoint::start(); + let arguments = [ + "open-ai-cache-reuse".into(), + "--base-url".into(), + peer.address.clone().into(), + "--model".into(), + "fixture".into(), + "--prompt-file".into(), + prompt.into_os_string(), + "--max-tokens".into(), + "8".into(), + ] + .into_iter() + .map(Value::Public) + .collect(); + // The production observer sees raw lines before log sanitization. Capture + // that same bounded stdout, rather than re-reading redacted diagnostics. + let captured = process::supervise_raw( + &ProcessSpec { + executable: binary, + arguments, + cwd: root.path().into(), + environment: execution::environment(&[( + "MESH_LLM_DATA_DIR", + root.path().join("data").into_os_string(), + )]), + }, + &execution::limits(Duration::from_secs(20)), + &Cancellation::default(), + RawCaptureOptions { + stdout: NonZeroUsize::new(64 * 1024), + stderr: None, + }, + ) + .unwrap(); + assert!(captured.process.success()); + assert!(captured.process.cleanup.complete); + assert!(!captured.process.cleanup.forced); + let stdout = String::from_utf8(captured.stdout.unwrap().as_bytes().to_vec()).unwrap(); + assert_eq!(peer.finish(), 4); + execution::server::verify_captured_client_stdout(&stdout).unwrap(); + assert!(execution::server::verify_captured_client_stdout(&(stdout.clone() + &stdout)).is_err()); + let mut receipt: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap(); + receipt["growing_chat_repeat"]["content"] = serde_json::json!("changed"); + assert!(execution::server::verify_captured_client_stdout(&receipt.to_string()).is_err()); +} diff --git a/tools/xtask/src/native_policy/linux_deps_policy.rs b/tools/xtask/src/native_policy/linux_deps_policy.rs index e528be9b99..b871b6cd17 100644 --- a/tools/xtask/src/native_policy/linux_deps_policy.rs +++ b/tools/xtask/src/native_policy/linux_deps_policy.rs @@ -46,7 +46,7 @@ pub(super) struct Package<'a> { pub(super) arch: Option, } -fn host_owned(name: &str) -> bool { +pub(crate) fn host_owned(name: &str) -> bool { let lower = casefold(name); HOST_LIBRARY_NAMES.contains(&lower.as_str()) || lower.starts_with("linux-vdso") diff --git a/tools/xtask/src/native_policy/mod.rs b/tools/xtask/src/native_policy/mod.rs index c5dc5eca36..403710493b 100644 --- a/tools/xtask/src/native_policy/mod.rs +++ b/tools/xtask/src/native_policy/mod.rs @@ -17,9 +17,10 @@ mod linux_deps_collect; mod linux_deps_elf; mod linux_deps_order; mod linux_deps_policy; +pub(crate) use linux_deps_policy::host_owned as host_owned_linux_library; pub(crate) mod manifest_identity; mod manifest_json; -mod package_version; +pub(crate) mod package_version; mod package_version_command; mod release_matrix; mod runtime_manifest_writer; diff --git a/tools/xtask/tests/migration_lifecycle/just_layout_contracts/recipe-ownership.json b/tools/xtask/tests/migration_lifecycle/just_layout_contracts/recipe-ownership.json index 0e7324e27f..b3d4a2d4b1 100644 --- a/tools/xtask/tests/migration_lifecycle/just_layout_contracts/recipe-ownership.json +++ b/tools/xtask/tests/migration_lifecycle/just_layout_contracts/recipe-ownership.json @@ -39,6 +39,9 @@ "release-runtime-build" ], "just/skippy.just": [ + "agentx-comparison", + "agentx-mlflow-export", + "agentx-setup", "bench-corpus", "competitive-benchmark-build", "competitive-inputs-helper-build", @@ -72,6 +75,9 @@ "skippy-cli-release-build", "skippy-ffi-bindgen-check", "skippy-ffi-bindgen-regen", + "skippy-kv-jy-plan", + "skippy-kv-prepare", + "skippy-kv-validate", "skippy-layer-package-cache", "skippy-layer-package-fetch", "skippy-layer-package-inspect", diff --git a/tools/xtask/tests/migration_repository/support.rs b/tools/xtask/tests/migration_repository/support.rs index 0b204bc896..034ddc6fa7 100644 --- a/tools/xtask/tests/migration_repository/support.rs +++ b/tools/xtask/tests/migration_repository/support.rs @@ -80,9 +80,18 @@ impl Invocation<'_> { } let mut child = command.spawn()?; let mut stdin = child.stdin.take().ok_or("missing stdin pipe")?; - stdin.write_all(self.stdin.unwrap_or_default().as_bytes())?; + let written = stdin.write_all(self.stdin.unwrap_or_default().as_bytes()); drop(stdin); - Ok(child.wait_with_output()?) + let output = child.wait_with_output()?; + if let Err(error) = written { + // Invalid source paths can be rejected before metadata is read. + // Reap the child and let callers check its actual failure status + // and diagnostic instead of replacing that evidence with EPIPE. + if error.kind() != std::io::ErrorKind::BrokenPipe || output.status.success() { + return Err(error.into()); + } + } + Ok(output) } } From 5be9a567db1737677aa8fde0040198a1f3d97409 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 6 Nov 2026 11:10:08 +1100 Subject: [PATCH 28/81] ci(agentx): admit the pinned upstream client environment Record the maintainer-approved external AgentX allowance and bind its manifest, wheel URL and SHA-256, full locked package set and exact setup invocation. Require installed Python 3.12 without managed interpreters or downloads. Keep other Python tooling restrictions intact and reject source, dependency, hash and invocation drift. Document the bounded owner and maintainer decision. --- .../references/maintainer-decisions.md | 18 ++ ci/python-tooling-policy.json | 160 ++++++++++ just/skippy.just | 6 +- skippy/evals/agentx/README.md | 11 + .../ci_validation/python_tooling/policy.rs | 156 +++++++++- .../src/ci_validation/python_tooling/tests.rs | 277 ++++++++++++++++++ 6 files changed, 619 insertions(+), 9 deletions(-) create mode 100644 .agents/skills/manage-ci/references/maintainer-decisions.md diff --git a/.agents/skills/manage-ci/references/maintainer-decisions.md b/.agents/skills/manage-ci/references/maintainer-decisions.md new file mode 100644 index 0000000000..b68f198b5e --- /dev/null +++ b/.agents/skills/manage-ci/references/maintainer-decisions.md @@ -0,0 +1,18 @@ +# Maintainer decisions + +## 2026-11-06: retain the external AgentX client + +James directed: “we must make allowances for agentx.” This answered the proposal +to admit PR #2746's existing pinned upstream client and locked environment, +with setup using an installed Python 3.12 interpreter. + +Source: [James's decision in Reviews](buzz://message?channel=97e27aa1-1281-4752-91a4-24ea085e1a62&id=31a7946c8680288d723e2831e22218e77d3d62c6732e87b70b24ed8605fd52b8). + +The bounded owner is `skippy/evals/agentx/`: its exact upstream AgentX wheel, +dependency manifest, lock and setup invocation are registered in +`ci/python-tooling-policy.json`. Setup does not download an interpreter. +Campaign workers consume the prepared environment offline and verify its bytes. +This decision permits the external client dependency; it does not permit new +repository Python implementations or a general interpreter invocation bypass. +Changing the admitted inputs still requires updating their exact typed policy +and passing the policy's rejection tests and normal repository consistency gate. diff --git a/ci/python-tooling-policy.json b/ci/python-tooling-policy.json index 0ff8bf58ec..1e7032596a 100644 --- a/ci/python-tooling-policy.json +++ b/ci/python-tooling-policy.json @@ -73,6 +73,160 @@ { "name": "typer", "version": "0.27.3" }, { "name": "typing-extensions", "version": "4.16.0" } ] + }, + { + "manifest_path": "skippy/evals/agentx/pyproject.toml", + "lock_path": "skippy/evals/agentx/uv.lock", + "consumer_path": "just/skippy.just", + "consumer_assignment": "AGENTX_PROJECT", + "purpose": "James-approved locked external AgentX 1.0.12.post2 benchmark client; no repository Python implementation", + "project_name": "skippy-agentx-environment", + "project_version": "0.1.0", + "direct_dependencies": [ + { "name": "agentx-harness", "version": "1.0.12.post2" } + ], + "url_packages": [ + { + "name": "agentx-harness", + "version": "1.0.12.post2", + "url": "https://github.com/Mesh-LLM/agentx-harness/releases/download/agentx-v1.0.12.post2/agentx_harness-1.0.12.post2-py3-none-any.whl", + "sha256": "0f9a9e85ec7f9273bfc96de00a492daf9898acfb66cfeeb6aba85a07c89e8a2f" + } + ], + "locked_packages": [ + { "name": "agentx-harness", "version": "1.0.12.post2" }, + { "name": "aiofiles", "version": "24.1.0" }, + { "name": "aiohappyeyeballs", "version": "2.7.1" }, + { "name": "aiohttp", "version": "3.13.5" }, + { "name": "aiosignal", "version": "1.4.0" }, + { "name": "alembic", "version": "1.20.0" }, + { "name": "annotated-doc", "version": "0.0.5" }, + { "name": "annotated-types", "version": "0.8.0" }, + { "name": "anyio", "version": "4.15.1" }, + { "name": "attrs", "version": "26.1.0" }, + { "name": "blinker", "version": "1.9.0" }, + { "name": "brotli", "version": "1.2.0" }, + { "name": "brotlicffi", "version": "1.2.0.2" }, + { "name": "certifi", "version": "2026.7.22" }, + { "name": "cffi", "version": "2.1.1" }, + { "name": "charset-normalizer", "version": "3.5.2" }, + { "name": "choreographer", "version": "1.4.0" }, + { "name": "click", "version": "8.5.0" }, + { "name": "colorama", "version": "0.4.6" }, + { "name": "colorlog", "version": "6.12.0" }, + { "name": "contourpy", "version": "1.4.0" }, + { "name": "crick", "version": "0.0.8" }, + { "name": "cycler", "version": "0.12.1" }, + { "name": "cyclopts", "version": "4.25.3" }, + { "name": "dash", "version": "3.1.1" }, + { "name": "dash-bootstrap-components", "version": "2.0.4" }, + { "name": "datasets", "version": "5.1.0" }, + { "name": "dill", "version": "0.4.1" }, + { "name": "docstring-parser", "version": "0.18.0" }, + { "name": "fastapi", "version": "0.143.3" }, + { "name": "ffmpeg-python", "version": "0.2.0" }, + { "name": "filelock", "version": "4.2.0" }, + { "name": "flask", "version": "3.1.3" }, + { "name": "fonttools", "version": "4.67.0" }, + { "name": "frozenlist", "version": "1.8.0" }, + { "name": "fsspec", "version": "2026.7.0" }, + { "name": "future", "version": "1.0.0" }, + { "name": "h11", "version": "0.16.0" }, + { "name": "hf-xet", "version": "1.7.0" }, + { "name": "httpcore", "version": "1.0.9" }, + { "name": "httptools", "version": "0.9.0" }, + { "name": "httpx", "version": "0.28.1" }, + { "name": "huggingface-hub", "version": "1.33.0" }, + { "name": "idna", "version": "3.20" }, + { "name": "importlib-metadata", "version": "9.0.1" }, + { "name": "iniconfig", "version": "2.3.1" }, + { "name": "itsdangerous", "version": "2.2.0" }, + { "name": "jinja2", "version": "3.1.6" }, + { "name": "jmespath", "version": "1.0.1" }, + { "name": "kaleido", "version": "1.2.0" }, + { "name": "kiwisolver", "version": "1.5.1" }, + { "name": "linkify-it-py", "version": "2.2.0" }, + { "name": "logistro", "version": "2.0.1" }, + { "name": "mako", "version": "1.4.3" }, + { "name": "markdown-it-py", "version": "4.2.0" }, + { "name": "markupsafe", "version": "3.0.4" }, + { "name": "matplotlib", "version": "3.11.2" }, + { "name": "mdit-py-plugins", "version": "0.6.1" }, + { "name": "mdurl", "version": "0.1.2" }, + { "name": "msgspec", "version": "0.22.0" }, + { "name": "multidict", "version": "6.9.1" }, + { "name": "multiprocess", "version": "0.70.19" }, + { "name": "narwhals", "version": "2.27.1" }, + { "name": "nest-asyncio", "version": "1.6.0" }, + { "name": "numpy", "version": "2.5.4" }, + { "name": "nvidia-ml-py", "version": "13.615.71" }, + { "name": "opentelemetry-api", "version": "1.45.1" }, + { "name": "optuna", "version": "5.0.0" }, + { "name": "orjson", "version": "3.11.9" }, + { "name": "packaging", "version": "26.3" }, + { "name": "pandas", "version": "2.3.3" }, + { "name": "pillow", "version": "12.2.0" }, + { "name": "platformdirs", "version": "4.13.3" }, + { "name": "plotly", "version": "6.4.0" }, + { "name": "pluggy", "version": "1.7.0" }, + { "name": "prometheus-client", "version": "0.23.1" }, + { "name": "propcache", "version": "0.5.4" }, + { "name": "protobuf", "version": "7.36.2" }, + { "name": "psutil", "version": "7.0.0" }, + { "name": "pyarrow", "version": "26.0.0" }, + { "name": "pycparser", "version": "3.11" }, + { "name": "pydantic", "version": "2.14.1" }, + { "name": "pydantic-core", "version": "2.50.1" }, + { "name": "pydantic-settings", "version": "2.16.0" }, + { "name": "pygments", "version": "2.21.0" }, + { "name": "pyparsing", "version": "3.3.3" }, + { "name": "pytest", "version": "9.1.1" }, + { "name": "pytest-timeout", "version": "2.4.0" }, + { "name": "python-dateutil", "version": "2.9.0.post0" }, + { "name": "python-dotenv", "version": "1.2.4" }, + { "name": "pytz", "version": "2026.5" }, + { "name": "pyyaml", "version": "6.0.3" }, + { "name": "pyzmq", "version": "26.4.0" }, + { "name": "regex", "version": "2026.9.29" }, + { "name": "requests", "version": "2.34.2" }, + { "name": "retrying", "version": "1.4.2" }, + { "name": "rich", "version": "14.1.0" }, + { "name": "rich-rst", "version": "2.2.0" }, + { "name": "ruamel-yaml", "version": "0.18.17" }, + { "name": "ruamel-yaml-clib", "version": "0.2.15" }, + { "name": "safetensors", "version": "0.8.0" }, + { "name": "scipy", "version": "1.18.1" }, + { "name": "seaborn", "version": "0.13.2" }, + { "name": "sentencepiece", "version": "0.2.2" }, + { "name": "setproctitle", "version": "1.3.8" }, + { "name": "setuptools", "version": "84.0.0" }, + { "name": "shellingham", "version": "1.5.4" }, + { "name": "simplejson", "version": "4.2.0" }, + { "name": "six", "version": "1.17.0" }, + { "name": "soundfile", "version": "0.13.1" }, + { "name": "sqlalchemy", "version": "2.1.5" }, + { "name": "starlette", "version": "1.8.0" }, + { "name": "starlette-compress", "version": "1.8.0" }, + { "name": "textual", "version": "5.3.0" }, + { "name": "tiktoken", "version": "0.14.0" }, + { "name": "tokenizers", "version": "0.23.3" }, + { "name": "tqdm", "version": "4.70.1" }, + { "name": "transformers", "version": "5.20.1" }, + { "name": "typer", "version": "0.27.3" }, + { "name": "typing-extensions", "version": "4.16.0" }, + { "name": "typing-inspection", "version": "0.4.4" }, + { "name": "tzdata", "version": "2026.5" }, + { "name": "urllib3", "version": "2.8.0" }, + { "name": "uvicorn", "version": "0.54.0" }, + { "name": "uvloop", "version": "0.23.0" }, + { "name": "watchfiles", "version": "1.3.0" }, + { "name": "websockets", "version": "17.2" }, + { "name": "werkzeug", "version": "3.1.9" }, + { "name": "xxhash", "version": "4.0.1" }, + { "name": "yarl", "version": "1.25.1" }, + { "name": "zipp", "version": "4.1.1" }, + { "name": "zstandard", "version": "0.25.0" } + ] } ], "external_source_descriptors": [ @@ -220,6 +374,12 @@ "line": "require_cmd uvx", "occurrences": 1, "purpose": "check the optional upstream llama-benchy command before its smoke wrapper" + }, + { + "path": "just/skippy.just", + "line": "uv sync --locked --no-managed-python --no-python-downloads --python 3.12 --project \"$AGENTX_PROJECT\"", + "occurrences": 1, + "purpose": "restore only the reviewed external AgentX wheel and exact lock using preinstalled Python 3.12 without interpreter downloads" } ] } diff --git a/just/skippy.just b/just/skippy.just index c88bd90e94..14acfed5e8 100644 --- a/just/skippy.just +++ b/just/skippy.just @@ -10,7 +10,11 @@ skippy-kv-jy-plan input output: # Install only the locked upstream client environment; final workers stay offline. agentx-setup: - uv sync --locked --managed-python --python 3.12 --project skippy/evals/agentx + #!/usr/bin/env bash + set -euo pipefail + TRUSTED_ROOT="{{justfile_directory()}}" + AGENTX_PROJECT="$TRUSTED_ROOT/skippy/evals/agentx" + uv sync --locked --no-managed-python --no-python-downloads --python 3.12 --project "$AGENTX_PROJECT" agentx-comparison input output: @just automation-run automation agentx comparison --input "{{ input }}" --output "{{ output }}" diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 00b01a4f1b..dcadd8dc8c 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -27,6 +27,17 @@ runtime, tokenizer snapshot and corpus. External directory links/editable environments are refused; internal aliases such as `lib64 -> lib` are pinned without traversal, and regular-file interpreter links are hashed by content. +Setup requires `uv` and an already installed CPython 3.12. `just agentx-setup` +uses `--locked --no-managed-python --no-python-downloads --python 3.12` against +the repository's exact AgentX project; it does not install an interpreter. +The repository's Python-tooling policy admits only this setup invocation and +the reviewed manifest/lock: 132 exact dependency pins plus the virtual project. +The AgentX wheel URL is fixed in both the manifest and lock, with SHA-256 +`0f9a9e85ec7f9273bfc96de00a492daf9898acfb66cfeeb6aba85a07c89e8a2f`. +Changing that wheel or any dependency pin requires an explicit policy update. +This external-client allowance does not permit repository Python source or +additional interpreter/install commands. + Place the tokenizer snapshot in its pinned Hugging Face cache layout and set `HF_HUB_CACHE` (or `HF_HOME`) to that cache before pinning and running. The offline client receives the catalog's repository ID and exact revision; pinning diff --git a/tools/xtask/src/ci_validation/python_tooling/policy.rs b/tools/xtask/src/ci_validation/python_tooling/policy.rs index 126009d96a..233417f4b2 100644 --- a/tools/xtask/src/ci_validation/python_tooling/policy.rs +++ b/tools/xtask/src/ci_validation/python_tooling/policy.rs @@ -28,6 +28,8 @@ pub(super) struct DependencyInput { project_version: String, direct_dependencies: Vec, locked_packages: Vec, + #[serde(default)] + url_packages: Vec, } #[derive(Debug, Deserialize)] @@ -37,6 +39,16 @@ struct PackagePin { version: String, } +/// One reviewed direct wheel; this never grants a registry, host or path pattern. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct UrlPackagePin { + name: String, + version: String, + url: String, + sha256: String, +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct ExternalSourceDescriptor { @@ -112,6 +124,7 @@ pub(super) fn validate_policy_shape(policy: &Policy) -> DynResult<()> { } unique_package_pins(&input.direct_dependencies, &input.manifest_path)?; unique_package_pins(&input.locked_packages, &input.lock_path)?; + validate_url_package_pins(input)?; } for source in &policy.external_source_descriptors { @@ -160,6 +173,37 @@ pub(super) fn validate_policy_shape(policy: &Policy) -> DynResult<()> { Ok(()) } +fn validate_url_package_pins(input: &DependencyInput) -> DynResult<()> { + let mut names = BTreeSet::new(); + for pin in &input.url_packages { + let url = url::Url::parse(&pin.url)?; + let is_pinned = |packages: &[PackagePin]| { + packages + .iter() + .any(|package| package.name == pin.name && package.version == pin.version) + }; + if !names.insert(pin.name.to_ascii_lowercase()) + || !is_pinned(&input.direct_dependencies) + || !is_pinned(&input.locked_packages) + || !is_hex_revision(&pin.sha256, 64) + || url.scheme() != "https" + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + || !url.path().ends_with(".whl") + { + return Err(format!( + "`{}` URL package admission requires one exact direct wheel, HTTPS URL and SHA-256", + input.manifest_path + ) + .into()); + } + } + Ok(()) +} + fn unique_package_pins(pins: &[PackagePin], path: &str) -> DynResult<()> { let mut names = BTreeSet::new(); for pin in pins { @@ -219,6 +263,7 @@ pub(super) fn validate_dependency_input( ) .into()); } + validate_manifest_sources(&manifest, input)?; let lock: toml::Value = toml::from_str(&fs::read_to_string(&lock_path)?)?; let packages = lock @@ -242,7 +287,12 @@ pub(super) fn validate_dependency_input( .and_then(toml::Value::as_str) == Some(".") { - if name != input.project_name || version != input.project_version { + if name != input.project_name + || version != input.project_version + || package_source + .and_then(toml::Value::as_table) + .is_none_or(|source| source.len() != 1) + { return Err(format!( "`{}` has an unexpected virtual project record `{name}=={version}`", input.lock_path @@ -252,18 +302,15 @@ pub(super) fn validate_dependency_input( virtual_project_count += 1; continue; } - let source = package_source - .and_then(|source| source.get("registry")) - .and_then(toml::Value::as_str); - if source != Some("https://pypi.org/simple") { + validate_package_source(package, input, name, version)?; + validate_package_hashes(package, &input.lock_path, name)?; + if !actual.insert((name.to_owned(), version.to_owned())) { return Err(format!( - "`{}` package `{name}` must come from the pinned PyPI registry", + "`{}` repeats locked package `{name}=={version}`", input.lock_path ) .into()); } - validate_package_hashes(package, &input.lock_path, name)?; - actual.insert((name.to_owned(), version.to_owned())); } let expected: BTreeSet<_> = input .locked_packages @@ -296,6 +343,99 @@ pub(super) fn validate_dependency_input( Ok(()) } +fn validate_manifest_sources(manifest: &toml::Value, input: &DependencyInput) -> DynResult<()> { + let sources = manifest + .get("tool") + .and_then(|tool| tool.get("uv")) + .and_then(|uv| uv.get("sources")); + let Some(sources) = sources else { + if input.url_packages.is_empty() { + return Ok(()); + } + return Err(format!( + "`{}` is missing its reviewed direct wheel source", + input.manifest_path + ) + .into()); + }; + let sources = sources + .as_table() + .ok_or("Python package source overrides must be a table")?; + if sources.len() != input.url_packages.len() + || input.url_packages.iter().any(|pin| { + sources + .get(&pin.name) + .and_then(toml::Value::as_table) + .is_none_or(|source| { + source.len() != 1 + || source.get("url").and_then(toml::Value::as_str) != Some(pin.url.as_str()) + }) + }) + { + return Err(format!( + "`{}` package sources differ from the reviewed exact wheel URLs", + input.manifest_path + ) + .into()); + } + Ok(()) +} + +fn validate_package_source( + package: &toml::Value, + input: &DependencyInput, + name: &str, + version: &str, +) -> DynResult<()> { + if let Some(pin) = input + .url_packages + .iter() + .find(|pin| pin.name == name && pin.version == version) + { + let source_matches = package + .get("source") + .and_then(toml::Value::as_table) + .is_some_and(|source| { + source.len() == 1 + && source.get("url").and_then(toml::Value::as_str) == Some(pin.url.as_str()) + }); + let expected_hash = format!("sha256:{}", pin.sha256); + let wheel_matches = package + .get("wheels") + .and_then(toml::Value::as_array) + .is_some_and(|wheels| { + wheels.len() == 1 + && wheels[0].get("url").and_then(toml::Value::as_str) == Some(pin.url.as_str()) + && wheels[0].get("hash").and_then(toml::Value::as_str) + == Some(expected_hash.as_str()) + }); + if !source_matches || !wheel_matches || package.get("sdist").is_some() { + return Err(format!( + "`{}` package `{name}` differs from its reviewed exact wheel URL/SHA-256", + input.lock_path + ) + .into()); + } + return Ok(()); + } + if !package + .get("source") + .and_then(toml::Value::as_table) + .is_some_and(|source| { + source.len() == 1 + && source.get("registry").and_then(toml::Value::as_str) + == Some("https://pypi.org/simple") + }) + { + return Err(format!( + "`{}` package `{name}` must come from the pinned PyPI registry", + input.lock_path + ) + .into()); + } + Ok(()) +} + fn validate_package_hashes(package: &toml::Value, lock_path: &str, name: &str) -> DynResult<()> { let mut hashes = Vec::new(); let mut artifact_count = 0; diff --git a/tools/xtask/src/ci_validation/python_tooling/tests.rs b/tools/xtask/src/ci_validation/python_tooling/tests.rs index 5396c721dc..01e0b25596 100644 --- a/tools/xtask/src/ci_validation/python_tooling/tests.rs +++ b/tools/xtask/src/ci_validation/python_tooling/tests.rs @@ -93,6 +93,283 @@ fn exact_external_project_and_pins_are_admitted() { check_fixture(&root).unwrap(); } +fn agentx_fixture() -> (TempDir, PathBuf) { + let (temporary, root) = fixture(); + let mut policy: serde_json::Value = serde_json::from_str(POLICY).unwrap(); + let reviewed: serde_json::Value = + serde_json::from_str(include_str!("../../../../../ci/python-tooling-policy.json")).unwrap(); + let agentx = reviewed["dependency_inputs"] + .as_array() + .unwrap() + .iter() + .find(|input| input["manifest_path"] == "skippy/evals/agentx/pyproject.toml") + .unwrap(); + policy["dependency_inputs"] + .as_array_mut() + .unwrap() + .push(agentx.clone()); + policy["allowed_invocations"] = serde_json::Value::Array( + reviewed["allowed_invocations"] + .as_array() + .unwrap() + .iter() + .filter(|invocation| invocation["path"] == "just/skippy.just") + .cloned() + .collect(), + ); + write(&root, POLICY_PATH, &serde_json::to_string(&policy).unwrap()); + write( + &root, + "skippy/evals/agentx/pyproject.toml", + include_str!("../../../../../skippy/evals/agentx/pyproject.toml"), + ); + write( + &root, + "skippy/evals/agentx/uv.lock", + include_str!("../../../../../skippy/evals/agentx/uv.lock"), + ); + write( + &root, + "just/skippy.just", + include_str!("../../../../../just/skippy.just"), + ); + (temporary, root) +} + +#[test] +fn reviewed_agentx_wheel_lock_and_preinstalled_interpreter_setup_are_admitted() { + let (_temporary, root) = agentx_fixture(); + check_fixture(&root).unwrap(); +} + +#[test] +fn agentx_manifest_source_override_must_match_its_reviewed_wheel() { + for missing in [false, true] { + let (_temporary, root) = agentx_fixture(); + let path = "skippy/evals/agentx/pyproject.toml"; + let mut manifest: toml::Value = + toml::from_str(&fs::read_to_string(root.join(path)).unwrap()).unwrap(); + if missing { + manifest["tool"]["uv"] + .as_table_mut() + .unwrap() + .remove("sources"); + } else { + manifest["tool"]["uv"]["sources"]["agentx-harness"]["url"] = + toml::Value::String("https://example.org/other.whl".into()); + } + write(&root, path, &toml::to_string(&manifest).unwrap()); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("reviewed") + ); + } +} + +#[test] +fn agentx_source_url_wheel_url_and_valid_but_different_hash_are_rejected() { + for field in [ + "source-url", + "wheel-url", + "wheel-hash", + "extra-wheel", + "sdist", + ] { + let (_temporary, root) = agentx_fixture(); + let path = "skippy/evals/agentx/uv.lock"; + let mut lock: toml::Value = + toml::from_str(&fs::read_to_string(root.join(path)).unwrap()).unwrap(); + let agentx = lock["package"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|package| package["name"].as_str() == Some("agentx-harness")) + .unwrap(); + match field { + "source-url" => { + agentx["source"]["url"] = + toml::Value::String("https://example.org/other.whl".into()) + } + "wheel-url" => { + agentx["wheels"][0]["url"] = + toml::Value::String("https://example.org/other.whl".into()) + } + "wheel-hash" => { + agentx["wheels"][0]["hash"] = + toml::Value::String(format!("sha256:{}", "e".repeat(64))) + } + "extra-wheel" => { + let extra = agentx["wheels"][0].clone(); + agentx["wheels"].as_array_mut().unwrap().push(extra); + } + "sdist" => { + let sdist = agentx["wheels"][0].clone(); + agentx.as_table_mut().unwrap().insert("sdist".into(), sdist); + } + _ => unreachable!(), + } + write(&root, path, &toml::to_string(&lock).unwrap()); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("reviewed exact wheel URL/SHA-256"), + "{field}" + ); + } +} + +#[test] +fn registry_admission_cannot_hide_a_second_package_source() { + let (_temporary, root) = fixture(); + let path = "ci/llama-canary/jinja/uv.lock"; + let source = fs::read_to_string(root.join(path)).unwrap().replacen( + "source = { registry = \"https://pypi.org/simple\" }", + "source = { registry = \"https://pypi.org/simple\", url = \"https://example.org/other.whl\" }", 1); + write(&root, path, &source); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("pinned PyPI registry") + ); +} + +#[test] +fn agentx_lock_rejects_missing_extra_and_duplicate_transitive_packages() { + for change in ["missing", "extra", "duplicate"] { + let (_temporary, root) = agentx_fixture(); + let path = "skippy/evals/agentx/uv.lock"; + let mut lock: toml::Value = + toml::from_str(&fs::read_to_string(root.join(path)).unwrap()).unwrap(); + let packages = lock["package"].as_array_mut().unwrap(); + let index = packages + .iter() + .position(|package| package["name"].as_str() == Some("aiofiles")) + .unwrap(); + match change { + "missing" => { + packages.remove(index); + } + "extra" => { + let mut extra = packages[index].clone(); + extra["name"] = toml::Value::String("unreviewed-package".into()); + packages.push(extra); + } + "duplicate" => { + packages.push(packages[index].clone()); + } + _ => unreachable!(), + } + write(&root, path, &toml::to_string(&lock).unwrap()); + let error = check_fixture(&root).unwrap_err().to_string(); + assert!( + error.contains("locked package set differs") + || error.contains("repeats locked package"), + "{change}: {error}" + ); + } +} + +#[test] +fn agentx_url_admission_does_not_allow_other_transitive_sources_or_versions() { + for source_override in [false, true] { + let (_temporary, root) = agentx_fixture(); + let path = "skippy/evals/agentx/uv.lock"; + let mut lock: toml::Value = + toml::from_str(&fs::read_to_string(root.join(path)).unwrap()).unwrap(); + let package = lock["package"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|package| package["name"].as_str() == Some("aiofiles")) + .unwrap(); + if source_override { + package["source"] = toml::Value::Table(toml::map::Map::from_iter([( + "url".into(), + toml::Value::String("https://example.org/aiofiles.whl".into()), + )])); + } else { + package["version"] = toml::Value::String("99.0.0".into()); + } + write(&root, path, &toml::to_string(&lock).unwrap()); + let error = check_fixture(&root).unwrap_err().to_string(); + assert!( + if source_override { + error.contains("pinned PyPI registry") + } else { + error.contains("locked package set differs") + }, + "{error}" + ); + } +} + +#[test] +fn agentx_admission_keeps_python_source_and_command_occurrences_closed() { + let (_temporary, root) = agentx_fixture(); + write(&root, "skippy/evals/agentx/local-harness.py", "pass\n"); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("repository Python source is forbidden") + ); + fs::remove_file(root.join("skippy/evals/agentx/local-harness.py")).unwrap(); + let setup = fs::read_to_string(root.join("just/skippy.just")).unwrap(); + write( + &root, + "just/skippy.just", + &setup.replace("--no-python-downloads ", ""), + ); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("unreviewed Python tooling invocation") + ); + let (_temporary, root) = agentx_fixture(); + let setup = fs::read_to_string(root.join("just/skippy.just")).unwrap(); + write( + &root, + "just/skippy.just", + &format!( + "{setup}\nextra-client-install:\n uv sync --locked --no-managed-python --no-python-downloads --python 3.12 --project \"$AGENTX_PROJECT\"\n" + ), + ); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("exceeds its reviewed occurrence count") + ); +} + +#[test] +fn url_wheel_admission_must_pin_a_direct_dependency_and_a_valid_digest() { + for field in ["name", "sha256", "url"] { + let (_temporary, root) = agentx_fixture(); + let mut policy: serde_json::Value = + serde_json::from_str(&fs::read_to_string(root.join(POLICY_PATH)).unwrap()).unwrap(); + policy["dependency_inputs"][1]["url_packages"][0][field] = serde_json::json!(match field { + "name" => "aiofiles", + "sha256" => "not-a-sha256", + "url" => "http://example.org/unpinned.whl", + _ => unreachable!(), + }); + write(&root, POLICY_PATH, &serde_json::to_string(&policy).unwrap()); + assert!( + check_fixture(&root) + .unwrap_err() + .to_string() + .contains("exact direct wheel"), + "{field}" + ); + } +} + #[test] fn locked_project_must_match_its_consumed_assignment() { let (_temporary, root) = fixture(); From 3ea4eef7048e793d9bc2cc50bf548be17c68a3bc Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 6 Nov 2026 12:35:13 +1100 Subject: [PATCH 29/81] fix(skippy): preserve fair admission and native boundaries Keep HTTP lane admission independent of the native runtime mutex and retain FIFO reservations for blocking binary waiters. Hash model inputs concurrently with Unix model loading while preserving strong fingerprint checks. Resolve compacted DiffusionGemma logits on every host sampling entry, accept the exact ASR duration limit, and add real native regressions to the canonical build. Regenerate the native certificate without changing ABI 0.1.79. Document offline AgentX setuptools-hook preparation and restore blocking mode for accepted cache-test sockets. --- .../src/frontend/backend/runtime_admission.rs | 100 ++++++++- .../src/frontend/backend/tests.rs | 2 + .../src/frontend/generation/server.rs | 8 +- .../src/frontend/generation/types.rs | 2 + .../local_generation/linear_decode.rs | 2 + .../src/frontend/local_generation/tests.rs | 4 + .../tests/recurrent_fixture.rs | 2 + .../src/frontend/tests/multimodal.rs | 2 + .../src/frontend/tests/support.rs | 2 + .../skippy-serving/src/runtime_state.rs | 71 +++--- .../src/runtime_state/lane_admission.rs | 183 +++++++++++++--- .../src/runtime_state/model_content.rs | 138 +++++++++++- skippy/docs/PROMPT_CACHE.md | 11 +- skippy/evals/agentx/README.md | 17 ++ ...03-llama-port-diffusiongemma-support.patch | 187 ++++++++++++++-- ...-add-diffusiongemma-system-one-reads.patch | 2 +- ...skippy-query-diffusion-canvas-length.patch | 2 +- ...dels-add-laya-decision-model-support.patch | 2 +- ...-parse-implicit-reasoning-continuati.patch | 2 +- ...0008-models-add-qwen3-moe-native-mtp.patch | 2 +- ...kippy-add-whisper-speech-recognition.patch | 207 +++++++++++++++--- ...rd-per-token-logprobs-while-sampling.patch | 2 +- ...pose-glm5-next-stage-graph-semantics.patch | 2 +- ...skippy-add-clef-joint-decision-reads.patch | 2 +- skippy/scripts/build-llama.sh | 2 + .../kv_validation/tests/cache_client.rs | 1 + .../full_replay.rs | 2 + 27 files changed, 820 insertions(+), 139 deletions(-) diff --git a/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs b/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs index 0bf24d0bc9..9cb5edcd2a 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/runtime_admission.rs @@ -1,7 +1,6 @@ //! Bound frontend work by the execution lanes shared with binary stage clients. use super::{StageOpenAiBackend, generation_queue_timeout_error, request_cancelled_error}; use crate::runtime_state::lane_admission::RuntimeLanePermit; -use crate::runtime_state::panic_recovery::lock_runtime; use skippy_inference_api::{CancellationToken, InferenceError, InferenceResult}; use std::time::Instant; @@ -11,7 +10,9 @@ impl StageOpenAiBackend { admission_started: Instant, cancellation: &CancellationToken, ) -> InferenceResult { - let lanes = lock_runtime(&self.runtime).lane_admission(); + if cancellation.is_cancelled() { + return Err(request_cancelled_error()); + } let deadline = if self.generation_admission_timeout.is_zero() { None } else { @@ -23,6 +24,11 @@ impl StageOpenAiBackend { })?, ) }; + if deadline.is_some_and(|deadline| Instant::now() >= deadline) { + return Err(generation_queue_timeout_error( + self.generation_admission_timeout, + )); + } let timeout = async { if let Some(deadline) = deadline { tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await; @@ -34,7 +40,95 @@ impl StageOpenAiBackend { biased; () = cancellation.cancelled() => Err(request_cancelled_error()), () = timeout => Err(generation_queue_timeout_error(self.generation_admission_timeout)), - permit = lanes.acquire() => permit.map_err(|error| InferenceError::backend(format!("{error:#}"))), + permit = self.runtime_lane_admission.acquire() => permit.map_err(|error| InferenceError::backend(format!("{error:#}"))), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime_state::RuntimeState; + use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, + thread, + time::Duration, + }; + + struct HeldRuntime { + released: Arc, + release: Option>, + worker: Option>, + } + + impl Drop for HeldRuntime { + fn drop(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } + } + + fn hold_runtime(runtime: Arc>) -> HeldRuntime { + let (held_tx, held_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let released = Arc::new(AtomicBool::new(false)); + let observed = released.clone(); + let worker = thread::spawn(move || { + let runtime = runtime.lock().unwrap(); + held_tx.send(()).unwrap(); + // A regressed synchronous lock releases eventually and fails the + // state assertion, instead of hanging this single-thread runtime. + let _ = release_rx.recv_timeout(Duration::from_secs(5)); + drop(runtime); + observed.store(true, Ordering::Release); + }); + held_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + HeldRuntime { + released, + release: Some(release_tx), + worker: Some(worker), } } + + #[tokio::test] + async fn cancellation_stays_responsive_while_native_runtime_is_locked() { + let backend = super::super::tests::hooks_test_backend(None); + let _active = backend + .runtime_lane_admission + .try_acquire() + .unwrap() + .unwrap(); + let held = hold_runtime(backend.runtime.clone()); + let cancellation = CancellationToken::new(); + let mut waiting = Box::pin(backend.acquire_runtime_lane(Instant::now(), &cancellation)); + assert!(futures_util::poll!(&mut waiting).is_pending()); + assert!(!held.released.load(Ordering::Acquire)); + cancellation.cancel(); + assert!(waiting.await.is_err()); + assert!(!held.released.load(Ordering::Acquire)); + } + + #[tokio::test] + async fn expired_deadline_is_checked_while_native_runtime_is_locked() { + let backend = super::super::tests::hooks_test_backend(None); + let held = hold_runtime(backend.runtime.clone()); + let cancellation = CancellationToken::new(); + let started = Instant::now() + .checked_sub(backend.generation_admission_timeout + Duration::from_secs(1)) + .unwrap(); + let mut waiting = Box::pin(backend.acquire_runtime_lane(started, &cancellation)); + assert!(matches!( + futures_util::poll!(&mut waiting), + std::task::Poll::Ready(Err(_)) + )); + assert!(!held.released.load(Ordering::Acquire)); + } } diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs index b3f04c0137..4316066614 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs @@ -337,8 +337,10 @@ pub(super) fn hooks_test_backend( let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone()) .expect("iteration scheduler for hook lifecycle tests"); + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); StageOpenAiBackend { runtime: runtime.clone(), + runtime_lane_admission, workload: Default::default(), config: config.clone(), telemetry, diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index 07772d0cb7..c5fb78bcb9 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -427,9 +427,12 @@ fn embedded_openai_backend_with_state_kind( args.telemetry.emit("stage.kv_payload_selected", attrs); } let ctx_size = usize::try_from(args.config.ctx_size).unwrap_or(usize::MAX); - let generation_token_budget = { + let (generation_token_budget, runtime_lane_admission) = { let mut runtime = crate::runtime_state::panic_recovery::lock_runtime(&args.runtime); - GenerationTokenBudget::shared_for_runtime(&mut runtime, ctx_size) + ( + GenerationTokenBudget::shared_for_runtime(&mut runtime, ctx_size), + runtime.lane_admission(), + ) }; let iteration_scheduler = match iteration_scheduler { Some(iteration_scheduler) => iteration_scheduler, @@ -444,6 +447,7 @@ fn embedded_openai_backend_with_state_kind( }; let stage_backend = Arc::new(StageOpenAiBackend { runtime: args.runtime, + runtime_lane_admission, workload: Default::default(), config: args.config.clone(), telemetry: args.telemetry.clone(), diff --git a/skippy/crates/skippy-serving/src/frontend/generation/types.rs b/skippy/crates/skippy-serving/src/frontend/generation/types.rs index 4ebd78718d..ea6d2ef39d 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/types.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/types.rs @@ -49,6 +49,8 @@ pub(in crate::frontend) struct GenerationSessionLockEntry { #[derive(Clone)] pub(in crate::frontend) struct StageOpenAiBackend { pub(in crate::frontend) runtime: Arc>, + pub(in crate::frontend) runtime_lane_admission: + Arc, pub(in crate::frontend) workload: Arc, pub(in crate::frontend) config: StageConfig, pub(in crate::frontend) telemetry: Telemetry, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs index ef0a023008..c65fc0ce14 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs @@ -420,8 +420,10 @@ mod tests { telemetry.clone(), ) .unwrap(); + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + runtime_lane_admission, workload: Default::default(), config: stage_config.clone(), telemetry, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index b806a43676..7a80d13c6a 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -347,8 +347,10 @@ fn local_generation_signal_window_uses_configured_value() { let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone()) .unwrap(); + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime, + runtime_lane_admission, workload: Default::default(), config, telemetry, @@ -841,8 +843,10 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error let speculative = SpeculativeDecodeConfig::default(); let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + runtime_lane_admission, workload: Default::default(), config, telemetry, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index 2d346be75d..f1315b7766 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -153,8 +153,10 @@ pub(super) fn recurrent_test_backend_with_lanes( let speculative = SpeculativeDecodeConfig::default(); let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + runtime_lane_admission, workload: Default::default(), config, telemetry, diff --git a/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs b/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs index 3e16ec0b23..7332a76220 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs @@ -655,7 +655,9 @@ async fn real_multimodal_split_smoke_when_fixture_is_set() -> Result<()> { None, telemetry.clone(), )?; + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { + runtime_lane_admission, speculation_governor: None, runahead_governor: None, runtime, diff --git a/skippy/crates/skippy-serving/src/frontend/tests/support.rs b/skippy/crates/skippy-serving/src/frontend/tests/support.rs index 3d5064f109..f75696369c 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/support.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/support.rs @@ -136,8 +136,10 @@ pub(super) fn local_openai_backend( ); let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; + let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); Ok(StageOpenAiBackend { runtime, + runtime_lane_admission, workload: Default::default(), telemetry, config, diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index ad17680747..e492cdf0ff 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -379,25 +379,27 @@ pub fn load_runtime_with_overrides( ) -> Result>>> { reject_legacy_serving_package(config)?; let runtime_config = runtime_config_from_stage_config(config, overrides)?; - let content = model_content::VerifiedModelContent::observe(config) - .ok() - .flatten(); - let admitted_model_parts = config .model_part_paths .iter() .map(std::path::PathBuf::from) .collect::>(); - let model = match config.load_mode { - _ if !admitted_model_parts.is_empty() => { - open_stage_model_from_parts(&admitted_model_parts, &runtime_config)? - } - _ => { - let Some(model_path) = config.model_path.as_ref().map(std::path::Path::new) else { - return Ok(None); - }; - open_stage_model(model_path, &runtime_config)? - } + let (model, content) = model_content::VerifiedModelContent::verify_during_load(config, || { + let model = match config.load_mode { + _ if !admitted_model_parts.is_empty() => { + open_stage_model_from_parts(&admitted_model_parts, &runtime_config)? + } + _ => { + let Some(model_path) = config.model_path.as_ref().map(std::path::Path::new) else { + return Ok(None); + }; + open_stage_model(model_path, &runtime_config)? + } + }; + Ok(Some(model)) + })?; + let Some(model) = model else { + return Ok(None); }; Ok(Some(runtime_from_verified_model( config, @@ -413,11 +415,8 @@ fn runtime_from_verified_model( observer: Option>, content: Option, ) -> Result>> { - // Re-stat after open before publishing proof. No filesystem work takes the - // runtime lock, and frontends reuse this proof without rehashing weights. - let content = content - .filter(|proof| proof.still_matches(config)) - .map(Arc::new); + // Verification and its post-open file checks finished outside this lock. + let content = content.map(Arc::new); let runtime = runtime_from_loaded_model(config, model, observer)?; panic_recovery::lock_runtime(&runtime).verified_model_content = content; Ok(runtime) @@ -468,27 +467,29 @@ pub fn load_runtime_with_overrides_and_open_events( ) -> Result>>> { reject_legacy_serving_package(config)?; let runtime_config = runtime_config_from_stage_config(config, overrides)?; - let content = model_content::VerifiedModelContent::observe(config) - .ok() - .flatten(); - let admitted_model_parts = config .model_part_paths .iter() .map(std::path::PathBuf::from) .collect::>(); - let model = match config.load_mode { - _ if !admitted_model_parts.is_empty() => open_stage_model_from_parts_with_events( - &admitted_model_parts, - &runtime_config, - model_open_events, - )?, - _ => { - let Some(model_path) = config.model_path.as_ref().map(std::path::Path::new) else { - return Ok(None); - }; - open_stage_model_with_events(model_path, &runtime_config, model_open_events)? - } + let (model, content) = model_content::VerifiedModelContent::verify_during_load(config, || { + let model = match config.load_mode { + _ if !admitted_model_parts.is_empty() => open_stage_model_from_parts_with_events( + &admitted_model_parts, + &runtime_config, + model_open_events, + )?, + _ => { + let Some(model_path) = config.model_path.as_ref().map(std::path::Path::new) else { + return Ok(None); + }; + open_stage_model_with_events(model_path, &runtime_config, model_open_events)? + } + }; + Ok(Some(model)) + })?; + let Some(model) = model else { + return Ok(None); }; Ok(Some(runtime_from_verified_model( config, diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs index 4390c63b2f..3c7aaaff2e 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_admission.rs @@ -1,27 +1,49 @@ //! One execution-lane reservation owner shared by HTTP and binary frontends. use anyhow::{Result, bail}; +use std::future::Future; use std::sync::{Arc, Condvar, Mutex}; +use std::task::{Context, Poll, Wake, Waker}; use std::time::Duration; use tokio::sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError}; #[derive(Debug)] pub(crate) struct RuntimeLaneAdmission { permits: Arc, - changed: Condvar, - waiting: Mutex<()>, capacity: usize, } #[derive(Debug)] pub(crate) struct RuntimeLanePermit { - permit: Option, - owner: Arc, + _permit: OwnedSemaphorePermit, +} + +#[derive(Default)] +struct BlockingLaneWaiter { + notified: Mutex, + changed: Condvar, +} + +impl Wake for BlockingLaneWaiter { + fn wake(self: Arc) { + *self + .notified + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = true; + self.changed.notify_one(); + } } -impl Drop for RuntimeLanePermit { - fn drop(&mut self) { - drop(self.permit.take()); - self.owner.changed.notify_all(); +impl BlockingLaneWaiter { + fn wait(&self) { + let notified = self + .notified + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut notified, _) = self + .changed + .wait_timeout_while(notified, Duration::from_millis(50), |notified| !*notified) + .unwrap_or_else(std::sync::PoisonError::into_inner); + *notified = false; } } @@ -30,8 +52,6 @@ impl RuntimeLaneAdmission { let capacity = usize::try_from(capacity).unwrap_or(usize::MAX).max(1); Arc::new(Self { permits: Arc::new(Semaphore::new(capacity)), - changed: Condvar::new(), - waiting: Mutex::new(()), capacity, }) } @@ -42,18 +62,12 @@ impl RuntimeLaneAdmission { pub(crate) async fn acquire(self: &Arc) -> Result { let permit = self.permits.clone().acquire_owned().await?; - Ok(RuntimeLanePermit { - permit: Some(permit), - owner: self.clone(), - }) + Ok(RuntimeLanePermit { _permit: permit }) } pub(crate) fn try_acquire(self: &Arc) -> Result> { match self.permits.clone().try_acquire_owned() { - Ok(permit) => Ok(Some(RuntimeLanePermit { - permit: Some(permit), - owner: self.clone(), - })), + Ok(permit) => Ok(Some(RuntimeLanePermit { _permit: permit })), Err(TryAcquireError::NoPermits) => Ok(None), Err(TryAcquireError::Closed) => bail!("runtime lane admission closed"), } @@ -64,22 +78,20 @@ impl RuntimeLaneAdmission { self: &Arc, cancelled: impl Fn() -> bool, ) -> Result { - let mut waiting = self - .waiting - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + // Keep one queued future across cancellation polls so blocking peers + // retain their FIFO position alongside asynchronous HTTP waiters. + let mut acquisition = std::pin::pin!(self.permits.clone().acquire_owned()); + let waiter = Arc::new(BlockingLaneWaiter::default()); + let waker = Waker::from(Arc::clone(&waiter)); + let mut context = Context::from_waker(&waker); loop { if cancelled() { bail!("binary runtime lane admission cancelled"); } - if let Some(permit) = self.try_acquire()? { - return Ok(permit); + match acquisition.as_mut().poll(&mut context) { + Poll::Ready(permit) => return Ok(RuntimeLanePermit { _permit: permit? }), + Poll::Pending => waiter.wait(), } - waiting = self - .changed - .wait_timeout(waiting, Duration::from_millis(50)) - .unwrap_or_else(std::sync::PoisonError::into_inner) - .0; } } } @@ -89,3 +101,116 @@ impl super::RuntimeState { Arc::clone(&self.runtime_lane_admission) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + mpsc, + }; + use std::thread; + + struct BlockingAcquisition { + queued: mpsc::Receiver<()>, + finished: mpsc::Receiver, + worker: thread::JoinHandle>, + } + + fn queue_blocking( + lanes: Arc, + cancelled: Arc, + ) -> BlockingAcquisition { + let (queued_tx, queued) = mpsc::channel(); + let (finished_tx, finished) = mpsc::channel(); + let worker = thread::spawn(move || { + let polls = AtomicUsize::new(0); + let result = lanes.acquire_blocking(|| { + // The second cancellation poll follows a Pending poll of the + // acquisition future, so its FIFO position already exists. + if polls.fetch_add(1, Ordering::AcqRel) == 1 { + let _ = queued_tx.send(()); + } + cancelled.load(Ordering::Acquire) + }); + let _ = finished_tx.send(result.is_ok()); + result + }); + BlockingAcquisition { + queued, + finished, + worker, + } + } + + #[tokio::test] + async fn blocking_waiter_keeps_fifo_position_between_async_waiters() { + let lanes = RuntimeLaneAdmission::new(1); + let active = lanes.try_acquire().unwrap().unwrap(); + let mut older_http = Box::pin(lanes.acquire()); + assert!(futures_util::poll!(&mut older_http).is_pending()); + let binary = queue_blocking(lanes.clone(), Arc::new(AtomicBool::new(false))); + binary.queued.recv_timeout(Duration::from_secs(5)).unwrap(); + let mut newer_http = Box::pin(lanes.acquire()); + assert!(futures_util::poll!(&mut newer_http).is_pending()); + + drop(active); + let older = tokio::time::timeout(Duration::from_secs(5), older_http) + .await + .unwrap() + .unwrap(); + assert!(binary.finished.try_recv().is_err()); + assert!(futures_util::poll!(&mut newer_http).is_pending()); + drop(older); + assert!( + binary + .finished + .recv_timeout(Duration::from_secs(5)) + .unwrap() + ); + assert!(futures_util::poll!(&mut newer_http).is_pending()); + let binary = binary.worker.join().unwrap().unwrap(); + drop(binary); + let newer = tokio::time::timeout(Duration::from_secs(5), newer_http) + .await + .unwrap() + .unwrap(); + drop(newer); + assert!(lanes.try_acquire().unwrap().is_some()); + } + + #[tokio::test] + async fn cancelled_blocking_waiter_removes_its_fifo_reservation() { + let lanes = RuntimeLaneAdmission::new(1); + let active = lanes.try_acquire().unwrap().unwrap(); + let cancelled = Arc::new(AtomicBool::new(false)); + let binary = queue_blocking(lanes.clone(), cancelled.clone()); + binary.queued.recv_timeout(Duration::from_secs(5)).unwrap(); + let mut http = Box::pin(lanes.acquire()); + assert!(futures_util::poll!(&mut http).is_pending()); + cancelled.store(true, Ordering::Release); + assert!( + !binary + .finished + .recv_timeout(Duration::from_secs(5)) + .unwrap() + ); + assert!(binary.worker.join().unwrap().is_err()); + drop(active); + let admitted = tokio::time::timeout(Duration::from_secs(5), http) + .await + .unwrap() + .unwrap(); + drop(admitted); + assert!(lanes.try_acquire().unwrap().is_some()); + } + + #[tokio::test] + async fn blocking_acquisition_can_be_polled_inside_an_existing_runtime() { + let lanes = RuntimeLaneAdmission::new(1); + let permit = lanes.acquire_blocking(|| false).unwrap(); + assert!(lanes.try_acquire().unwrap().is_none()); + drop(permit); + assert!(lanes.try_acquire().unwrap().is_some()); + } +} diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs index 885c4f0b3c..f8accb87c1 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -6,13 +6,15 @@ use std::{ fs::{File, Metadata}, io::{BufReader, Read}, path::{Path, PathBuf}, - time::SystemTime, + time::{Instant, SystemTime}, }; +type ObservedFiles = Vec<(String, PathBuf, FileStamp)>; + #[derive(Clone)] pub(crate) struct VerifiedModelContent { digest: String, - files: Vec<(String, PathBuf, FileStamp)>, + files: ObservedFiles, } #[derive(Clone, PartialEq, Eq)] @@ -44,7 +46,34 @@ impl FileStamp { } impl VerifiedModelContent { + /// Unix captures strong file stamps before native open, then hashes on a + /// scoped worker while the caller loads the model. Other platforms retain + /// the sequential read so weak timestamps cannot authorize a raced load. + pub(crate) fn verify_during_load( + config: &StageConfig, + load: impl FnOnce() -> Result, + ) -> Result<(T, Option)> { + #[cfg(unix)] + let (model, content) = match Self::observe_files(config).ok().flatten() { + Some(files) => verify_alongside_load(load, || Self::from_observed(files))?, + None => (load()?, None), + }; + #[cfg(not(unix))] + let (model, content) = { + let content = Self::observe(config).ok().flatten(); + (load()?, content) + }; + Ok((model, content.filter(|proof| proof.still_matches(config)))) + } + + #[cfg(any(not(unix), test))] pub(crate) fn observe(config: &StageConfig) -> Result> { + Self::observe_files(config)? + .map(Self::from_observed) + .transpose() + } + + fn observe_files(config: &StageConfig) -> Result> { if !crate::kv_integration::KvStageIntegration::cache_enabled_for_stage(config) { return Ok(None); } @@ -52,15 +81,22 @@ impl VerifiedModelContent { if files.is_empty() { return Ok(None); } - Self::from_files(files).map(Some) + capture_files(files).map(Some) } + #[cfg(any(not(unix), test))] fn from_files(files: Vec<(String, PathBuf)>) -> Result { + Self::from_observed(capture_files(files)?) + } + + fn from_observed(files: ObservedFiles) -> Result { + let started = Instant::now(); + let mut verified_bytes = 0_u64; let mut digest = Sha256::new(); digest.update(b"skippy-loaded-model-content-v1\0"); let mut observed = Vec::with_capacity(files.len()); let mut buffer = vec![0; 1024 * 1024]; - for (name, path) in files { + for (name, path, stamp) in files { let file = File::open(&path) .with_context(|| format!("open model content {}", path.display()))?; let before = file.metadata()?; @@ -68,7 +104,10 @@ impl VerifiedModelContent { before.is_file(), "model content proof requires regular files" ); - let stamp = FileStamp::read(&before); + ensure!( + FileStamp::read(&before) == stamp, + "model content changed before verification" + ); digest.update((name.len() as u64).to_le_bytes()); digest.update(name.as_bytes()); digest.update(stamp.bytes.to_le_bytes()); @@ -79,6 +118,7 @@ impl VerifiedModelContent { break; } digest.update(&buffer[..count]); + verified_bytes = verified_bytes.saturating_add(count as u64); } ensure!( FileStamp::read(&reader.get_ref().metadata()?) == stamp, @@ -91,6 +131,13 @@ impl VerifiedModelContent { .iter() .map(|byte| format!("{byte:02x}")) .collect(); + tracing::info!( + target: "skippy::cache", + verified_bytes, + file_count = observed.len(), + elapsed_ms = started.elapsed().as_millis() as u64, + "hashed model content" + ); Ok(Self { digest, files: observed, @@ -137,6 +184,38 @@ impl VerifiedModelContent { } } +fn capture_files(files: Vec<(String, PathBuf)>) -> Result { + files + .into_iter() + .map(|(name, path)| { + let metadata = path.metadata()?; + ensure!( + metadata.is_file(), + "model content proof requires regular files" + ); + Ok((name, path, FileStamp::read(&metadata))) + }) + .collect() +} + +#[cfg(unix)] +fn verify_alongside_load( + load: impl FnOnce() -> Result, + verify: impl FnOnce() -> Result + Send, +) -> Result<(T, Option)> { + std::thread::scope(|scope| { + let verification = std::thread::Builder::new() + .name("skippy-model-content".into()) + .spawn_scoped(scope, verify) + .ok(); + let model = load(); + let content = verification + .and_then(|verification| verification.join().ok()) + .and_then(Result::ok); + model.map(|model| (model, content)) + }) +} + fn source_files(config: &StageConfig) -> Result> { let mut files = if config.model_part_paths.is_empty() { let Some(path) = config.model_path.as_deref().map(Path::new) else { @@ -214,6 +293,55 @@ fn checkpoint_files(root: &Path) -> Result> { mod tests { use super::*; + #[cfg(unix)] + #[test] + fn model_open_and_content_verification_progress_concurrently() { + use std::{sync::mpsc, time::Duration}; + let (started, observed_start) = mpsc::channel(); + let (opened, observed_open) = mpsc::channel(); + let (model, content) = verify_alongside_load( + || { + observed_start.recv_timeout(Duration::from_secs(5))?; + opened.send(())?; + Ok("loaded") + }, + move || { + started.send(())?; + observed_open.recv_timeout(Duration::from_secs(5))?; + Ok(VerifiedModelContent { + digest: "proof".into(), + files: Vec::new(), + }) + }, + ) + .unwrap(); + assert_eq!(model, "loaded"); + assert_eq!(content.unwrap().digest, "proof"); + } + + #[test] + fn content_changes_during_model_open_disable_persistent_reuse() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("model.gguf"); + std::fs::write(&path, b"old weights").unwrap(); + let config = StageConfig { + model_path: Some(path.to_string_lossy().into_owned()), + kv_cache: Some( + serde_json::from_value(serde_json::json!({"mode":"lookup-record"})).unwrap(), + ), + ..StageConfig::default() + }; + let (_, unchanged) = VerifiedModelContent::verify_during_load(&config, || Ok(())).unwrap(); + assert!(unchanged.is_some()); + let (model, proof) = VerifiedModelContent::verify_during_load(&config, || { + std::fs::write(&path, b"new weights")?; + Ok("loaded") + }) + .unwrap(); + assert_eq!(model, "loaded"); + assert!(proof.is_none()); + } + #[test] fn unchanged_declared_digest_cannot_hide_changed_weight_bytes() { let root = tempfile::tempdir().unwrap(); diff --git a/skippy/docs/PROMPT_CACHE.md b/skippy/docs/PROMPT_CACHE.md index 95ea3b9d0a..b5e6b3988f 100644 --- a/skippy/docs/PROMPT_CACHE.md +++ b/skippy/docs/PROMPT_CACHE.md @@ -43,12 +43,15 @@ Run and topology instance IDs do not fragment the namespace. Equivalent placements can reuse state when the numerical model and state layout match. Persistent reuse also binds its cache keys to verified bytes of the model inputs -actually opened by the runtime. Serving hashes those files once around model -loading, including every shard and any checkpoint, projector or importance -matrix inputs. File fingerprints must remain unchanged through the load. Unix +actually opened by the runtime, including every shard and any checkpoint, +projector or importance matrix inputs. On Unix, serving captures strong file +fingerprints before open and hashes on a scoped worker concurrently with model +loading. Fingerprints must remain unchanged before hashing, after hashing, and +after model open. Verification logs the byte count and elapsed time. Unix frontends reuse that strong fingerprint proof. Platforms without equivalent file identity and change-time evidence recheck bytes after load and at backend -construction; requests do not rehash weights. Declared model or +construction, retaining the pre-load hash instead of overlapping it with load; +requests do not rehash weights. Declared model or manifest digests alone cannot authorize disk reuse. Integrations constructed from a raw stage configuration without loaded-content proof keep their native in-memory cache, but disable L3 and the L3-backed host tier. diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index dcadd8dc8c..a46001da9e 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -153,6 +153,23 @@ use a diagnostic scope and distinct MLflow run keys and capacity tags, so they cannot replace an automatic-capacity comparison. Prepared environments reject executable `.pth` hooks and path entries outside the pinned environment; remove unsupported hooks while preparing the offline environment before pinning it. +In particular, the locked setuptools wheel installs `distutils-precedence.pth`, +which imports `_distutils_hack` and is rejected by `pin`. For the Linux/macOS +environment created by `just agentx-setup`, remove that specific hook before +pinning (replace the absolute path with the prepared environment you own): + +```bash +client_environment=/absolute/path/to/skippy/evals/agentx/.venv +test -f "$client_environment/pyvenv.cfg" +site_packages="$client_environment/lib/python3.12/site-packages" +test -d "$site_packages" +rm -f -- "$site_packages/distutils-precedence.pth" +``` + +This preparation is for the offline benchmark client, not a package-building +environment. A later dependency sync may reinstall the hook, so prepare and pin +again after syncing. Other executable hooks remain rejected; inspect them +individually rather than removing every `.pth` file or weakening admission. The prepared llama executable and every non-system native dependency are inspected as ELF or Mach-O before a baseline is admitted. Loader search paths and resolved libraries must stay inside `standard_runtime`; ELF shared objects need their own diff --git a/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch b/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch index 691aa355cd..85a6c27c40 100644 --- a/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch +++ b/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch @@ -13,7 +13,7 @@ Subject: [PATCH] llama: port DiffusionGemma support .../diffusion-gemma-server.cpp | 189 ++++ .../diffusion-gemma-visual-server.cpp | 388 ++++++++ examples/diffusion/diffusion-cli.cpp | 548 +++++++++-- - examples/diffusion/diffusion.cpp | 289 ++++++ + examples/diffusion/diffusion.cpp | 291 ++++++ examples/diffusion/diffusion.h | 38 + ggml/src/ggml-cuda/diffusion-sampling.cu | 178 ++++ ggml/src/ggml-cuda/diffusion-sampling.cuh | 19 + @@ -37,6 +37,7 @@ Subject: [PATCH] llama: port DiffusionGemma support create mode 100644 ggml/src/ggml-cuda/diffusion-sampling.cuh create mode 100644 src/models/diffusion-gemma.cpp create mode 100644 src/models/gemma4-common.h + create mode 100644 src/skippy/tests/diffusion_host_fallback.cpp diff --git a/common/arg.cpp b/common/arg.cpp index 69be4a61e..66cdb9919 100644 @@ -1685,7 +1686,7 @@ index c64611356..7f036913a 100644 llama_free(ctx); diff --git a/examples/diffusion/diffusion.cpp b/examples/diffusion/diffusion.cpp -index 0ff57d953..cf5c0e149 100644 +index 0ff57d953..f752c18b6 100644 --- a/examples/diffusion/diffusion.cpp +++ b/examples/diffusion/diffusion.cpp @@ -8,7 +8,9 @@ @@ -1759,7 +1760,7 @@ index 0ff57d953..cf5c0e149 100644 llama_token_data_array cur_p = { candidates.data(), -@@ -404,3 +432,264 @@ void diffusion_generate(llama_context * ctx, +@@ -404,3 +432,266 @@ void diffusion_generate(llama_context * ctx, n_generated = params.max_length; } @@ -1829,7 +1830,6 @@ index 0ff57d953..cf5c0e149 100644 + // canvas, reading the cached prefix - instead of re-decoding [prompt|canvas] every step. + // The canvas logits row base is re-resolved from output_ids after each decode below: a capped + // n_outputs_max compacts the flagged canvas rows to 0, while an uncapped pass keeps them at n_input. -+ int32_t logit_off = params.kv_cache ? 0 : n_input; + if (params.kv_cache) { + llama_diffusion_set_sc(model, nullptr, 0.0f, 1.0f, false); + // Chunked causal PREFILL: feed the prompt in ubatch-sized chunks, each writing its K/V to the store and @@ -1905,18 +1905,8 @@ index 0ff57d953..cf5c0e149 100644 + + // Stage-1: when on, skip the 268 MB logits D2H + host reductions and sample on the GPU from sc_dev. + const bool gpu_reduce = dev_sc && device_sample_ok; -+ const bool want_logits = !gpu_reduce; -+ const float * logits = nullptr; // canvas rows packed: [C or max_length, n_vocab] -+ if (want_logits) { -+ logits = llama_get_logits(ctx); -+ const float * first_canvas = llama_get_logits_ith(ctx, params.kv_cache ? 0 : n_input); -+ if (first_canvas == nullptr) { -+ LOG_ERR("%s: canvas logits row missing at step %d\n", __func__, step_idx); -+ decode_failed = true; -+ break; -+ } -+ logit_off = (int32_t) (first_canvas - logits) / n_vocab; -+ } else { ++ const float * logits = nullptr; // first canvas row, resolved before host use ++ if (gpu_reduce) { + llama_synchronize(ctx); // sc_dev write must complete before we read it + } + @@ -1929,7 +1919,7 @@ index 0ff57d953..cf5c0e149 100644 + // per position: argmax, entropy of softmax(raw/t), and a multinomial sample; stash raw row for SC + auto worker = [&](int32_t p0, int32_t p1) { + for (int32_t pos = p0; pos < p1; pos++) { -+ const float * row = logits + (size_t) (logit_off + pos) * n_vocab; ++ const float * row = logits + (size_t) pos * n_vocab; + float m = -INFINITY; int32_t amax = 0; + for (int32_t v = 0; v < n_vocab; v++) { + const float z = row[v] * temp_inv; @@ -1959,6 +1949,13 @@ index 0ff57d953..cf5c0e149 100644 + } + }; + auto run_host_worker = [&]() { ++ // Resolve output_ids on every host entry, including the first device-sampling fallback. ++ // n_outputs_max can compact canvas rows to zero instead of their batch-token offset. ++ logits = llama_get_logits_ith(ctx, params.kv_cache ? 0 : n_input); ++ if (logits == nullptr) { ++ LOG_ERR("%s: canvas logits row missing at step %d\n", __func__, step_idx); ++ return false; ++ } + std::vector pool; + const int32_t chunk = (C + (int32_t) nth - 1) / (int32_t) nth; + for (unsigned ti = 0; ti < nth; ti++) { @@ -1967,6 +1964,7 @@ index 0ff57d953..cf5c0e149 100644 + if (p0 < p1) { pool.emplace_back(worker, p0, p1); } + } + for (auto & th : pool) { th.join(); } ++ return true; + }; + + if (gpu_reduce) { @@ -1980,11 +1978,16 @@ index 0ff57d953..cf5c0e149 100644 + LOG_WRN("%s: on-device sampling unsupported on this backend; using host sampling\n", __func__); + device_sample_ok = false; + } -+ if (!logits) { logits = llama_get_logits(ctx); } -+ run_host_worker(); ++ if (!run_host_worker()) { ++ decode_failed = true; ++ break; ++ } + } + } else { -+ run_host_worker(); ++ if (!run_host_worker()) { ++ decode_failed = true; ++ break; ++ } + } + + // accept the lowest-entropy positions within the MI bound (sum of strictly-earlier entropies <= bound) @@ -2368,6 +2371,31 @@ index 8e39fdf48..3380a0eae 100644 LLAMA_API int32_t llama_model_n_ctx_train (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd_inp (const struct llama_model * model); +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index a4fbfac19..eeb0553e6 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -223,6 +223,20 @@ if (LLAMA_STAGE_BUILD_TESTS) + target_compile_features(skippy-model-fixture-generator PRIVATE cxx_std_17) + target_include_directories(skippy-model-fixture-generator PRIVATE .) + target_link_libraries(skippy-model-fixture-generator PRIVATE llama-common) ++ ++ set(DIFFUSION_FALLBACK_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/diffusion-fallback-models") ++ file(MAKE_DIRECTORY "${DIFFUSION_FALLBACK_FIXTURE_DIR}") ++ add_test(NAME skippy_generate_diffusion_fallback COMMAND skippy-model-fixture-generator ++ --arch "^diffusion-gemma$" --seed 42 --out "${DIFFUSION_FALLBACK_FIXTURE_DIR}") ++ set_tests_properties(skippy_generate_diffusion_fallback PROPERTIES FIXTURES_SETUP diffusion-fallback-model) ++ add_executable(skippy-diffusion-host-fallback ++ skippy/tests/diffusion_host_fallback.cpp ../examples/diffusion/diffusion.cpp) ++ target_include_directories(skippy-diffusion-host-fallback PRIVATE . ../examples/diffusion) ++ target_compile_features(skippy-diffusion-host-fallback PRIVATE cxx_std_17) ++ target_link_libraries(skippy-diffusion-host-fallback PRIVATE llama-common) ++ add_test(NAME skippy_diffusion_host_fallback COMMAND skippy-diffusion-host-fallback ++ "${DIFFUSION_FALLBACK_FIXTURE_DIR}/diffusion-gemma-moe.gguf") ++ set_tests_properties(skippy_diffusion_host_fallback PROPERTIES FIXTURES_REQUIRED diffusion-fallback-model) + set(MTP_WIDTH_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/mtp-width-models") + file(MAKE_DIRECTORY "${MTP_WIDTH_FIXTURE_DIR}") + add_test(NAME skippy_generate_mtp_width COMMAND skippy-model-fixture-generator diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index e659ba84a..a3e3d0cbb 100644 --- a/src/llama-arch.cpp @@ -3576,6 +3604,123 @@ index 8f6c3160d..00538e6b0 100644 struct llama_model_gemma4_assistant : public llama_model_base { llama_model_gemma4_assistant(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; +diff --git a/src/skippy/tests/diffusion_host_fallback.cpp b/src/skippy/tests/diffusion_host_fallback.cpp +new file mode 100644 +index 000000000..3d714fb1a +--- /dev/null ++++ b/src/skippy/tests/diffusion_host_fallback.cpp +@@ -0,0 +1,111 @@ ++#include "diffusion.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace { ++constexpr int prompt_size = 4; ++constexpr int canvas_size = 16; ++ ++struct observation { ++ llama_context * ctx; ++ bool device; ++ bool valid = true; ++ int steps = 0; ++}; ++ ++bool observe_step(int32_t step, int32_t total, const llama_token * tokens, int32_t count, void * user) { ++ auto & seen = *static_cast(user); ++ const int vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(seen.ctx))); ++ const float * canvas = llama_get_logits_ith(seen.ctx, prompt_size); ++ // Enforce the regression's layout: only the canvas is output, packed from row zero. ++ seen.valid &= count == prompt_size + canvas_size && canvas == llama_get_logits(seen.ctx); ++ if (!canvas) { ++ seen.valid = false; ++ return false; ++ } ++ const float inv_temp = 1.0f / (0.4f + (0.8f - 0.4f) * float(total - step) / float(total)); ++ for (int pos = 0; pos < canvas_size; ++pos) { ++ const float * row = llama_get_logits_ith(seen.ctx, prompt_size + pos); ++ seen.valid &= row == canvas + size_t(pos) * vocab; ++ if (!row) { ++ seen.valid = false; ++ return false; ++ } ++ float maximum = -INFINITY; ++ int argmax = 0; ++ for (int v = 0; v < vocab; ++v) { ++ const float value = row[v] * inv_temp; ++ if (value > maximum) { ++ maximum = value; ++ argmax = v; ++ } ++ } ++ seen.valid &= tokens[prompt_size + pos] == argmax; ++ } ++ if (seen.device) { ++ // A CPU-resident model must take the unsupported-device fallback, even in a CUDA build. ++ std::vector draws(canvas_size, 0.5f), entropy(canvas_size); ++ std::vector argmax(canvas_size), sampled(canvas_size); ++ seen.valid &= !llama_diffusion_device_sample(llama_get_model(seen.ctx), draws.data(), argmax.data(), ++ entropy.data(), sampled.data(), canvas_size, inv_temp); ++ } ++ ++seen.steps; ++ return seen.valid; ++} ++ ++bool run(llama_model * model, bool device) { ++ auto context_params = llama_context_default_params(); ++ context_params.n_ctx = 128; ++ context_params.n_batch = 32; ++ context_params.n_ubatch = 32; ++ context_params.n_outputs_max = canvas_size; ++ context_params.n_threads = 2; ++ context_params.n_threads_batch = 2; ++ llama_context * ctx = llama_init_from_model(model, context_params); ++ if (!ctx) { ++ return false; ++ } ++ observation seen { ctx, device }; ++ const std::vector prompt { 1, 2, 3, 4 }; ++ std::vector output(prompt_size + canvas_size, -1); ++ diffusion_eb_params params; ++ params.max_length = int(output.size()); ++ params.max_denoising_steps = 2; ++ params.confidence_threshold = -1.0f; ++ params.seed = 42; ++ params.gpu_sampling = device; ++ params.gpu_sample_reduce = device; ++ params.step_callback = observe_step; ++ params.step_callback_user_data = &seen; ++ int32_t generated = 0; ++ diffusion_generate_entropy_bound(ctx, prompt.data(), output.data(), prompt_size, params, generated); ++ const bool ok = seen.valid && seen.steps == 2 && generated == int(output.size()) && ++ std::equal(prompt.begin(), prompt.end(), output.begin()); ++ llama_free(ctx); ++ return ok; ++} ++} // namespace ++ ++int main(int argc, char ** argv) { ++ if (argc != 2) { ++ return 1; ++ } ++ llama_backend_init(); ++ ggml_backend_load_all(); ++ auto params = llama_model_default_params(); ++ params.n_gpu_layers = 0; ++ llama_model * model = llama_model_load_from_file(argv[1], params); ++ const bool ok = model && run(model, false) && run(model, true); ++ if (model) { ++ llama_model_free(model); ++ } ++ llama_backend_free(); ++ if (!ok) { ++ std::fprintf(stderr, "compacted diffusion host/device-fallback logits mismatch\n"); ++ } ++ return ok ? 0 : 1; ++} diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index d12706299..d7d1a9024 100644 --- a/tests/test-llama-archs.cpp @@ -3631,5 +3776,5 @@ index d12706299..d7d1a9024 100644 if (moe && !moe_implemented(arch)) { continue; -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch index 07c5bb0078..ad035181e7 100644 --- a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch @@ -391,5 +391,5 @@ index 000000000..d0c51d87a + } +} -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch b/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch index 0d2e75d437..d1c00f91b5 100644 --- a/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch +++ b/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch @@ -68,5 +68,5 @@ index d0c51d87a..9cbe792ae 100644 struct skippy_model * model, const llama_token * prompt_tokens, -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch index 2a806ebd0a..c294b2a3dc 100644 --- a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch +++ b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch @@ -2807,5 +2807,5 @@ index 000000000..8a713d563 +// run one forward pass; returns 0 on success, non-zero on failure +LLAMA_API int laya_encode(laya_context * ctx, const laya_batch & batch, laya_result & result); -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch b/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch index 0d5661f1f6..0b407568d6 100644 --- a/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch +++ b/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch @@ -42,5 +42,5 @@ index 98dfc4b65..f19c533b9 100644 // generation prompt, so the output starts at " to=". tst.test(" to=special_function<|message|>" + call_markup) -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch b/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch index 779d43af41..4b9f52d1e0 100644 --- a/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch +++ b/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch @@ -478,5 +478,5 @@ index d7d1a9024..89b5135a4 100644 glm_dsa_indexshare_fixture::DEFAULT, 256, 8, false, 2 + dense_mtp_depth, 256); -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index 898ad958a4..5b1845464b 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -16,15 +16,19 @@ SKIPPY_FEATURE_SPEECH_RECOGNITION clear, and report UNSUPPORTED. Bumps the Skippy ABI to 0.1.72. --- - include/skippy.h | 1 + - include/skippy/asr.h | 172 +++++++++++++++ - include/skippy/common.h | 4 +- - src/CMakeLists.txt | 37 ++++ - src/skippy/abi.cpp | 6 +- - src/skippy/asr.cpp | 465 ++++++++++++++++++++++++++++++++++++++++ - 6 files changed, 683 insertions(+), 2 deletions(-) + include/skippy.h | 1 + + include/skippy/asr.h | 172 +++++++++ + include/skippy/common.h | 4 +- + src/CMakeLists.txt | 44 +++ + src/skippy/abi.cpp | 6 +- + src/skippy/asr.cpp | 447 +++++++++++++++++++++++ + src/skippy/asr_decode.h | 50 +++ + src/skippy/tests/asr_decode_boundary.cpp | 81 ++++ + 8 files changed, 803 insertions(+), 2 deletions(-) create mode 100644 include/skippy/asr.h create mode 100644 src/skippy/asr.cpp + create mode 100644 src/skippy/asr_decode.h + create mode 100644 src/skippy/tests/asr_decode_boundary.cpp diff --git a/include/skippy.h b/include/skippy.h index ac091dd24..4e33847d9 100644 @@ -299,6 +303,20 @@ index eab1c3a46..ea0cdd178 100644 if (LLAMA_STAGE_BUILD_TESTS) target_compile_definitions(llama PRIVATE LLAMA_STAGE_BUILD_TESTS) +@@ -240,6 +277,13 @@ if (LLAMA_STAGE_BUILD_TESTS) + add_test(NAME skippy_diffusion_host_fallback COMMAND skippy-diffusion-host-fallback + "${DIFFUSION_FALLBACK_FIXTURE_DIR}/diffusion-gemma-moe.gguf") + set_tests_properties(skippy_diffusion_host_fallback PROPERTIES FIXTURES_REQUIRED diffusion-fallback-model) ++ ++ add_executable(skippy-asr-decode-boundary skippy/tests/asr_decode_boundary.cpp) ++ target_include_directories(skippy-asr-decode-boundary PRIVATE .) ++ target_include_directories(skippy-asr-decode-boundary SYSTEM PRIVATE ../vendor) ++ target_compile_features(skippy-asr-decode-boundary PRIVATE cxx_std_17) ++ target_link_libraries(skippy-asr-decode-boundary PRIVATE llama) ++ add_test(NAME skippy_asr_decode_boundary COMMAND skippy-asr-decode-boundary) + set(MTP_WIDTH_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/mtp-width-models") + file(MAKE_DIRECTORY "${MTP_WIDTH_FIXTURE_DIR}") + add_test(NAME skippy_generate_mtp_width COMMAND skippy-model-fixture-generator diff --git a/src/skippy/abi.cpp b/src/skippy/abi.cpp index f806cdbdc..ed9825df3 100644 --- a/src/skippy/abi.cpp @@ -318,10 +336,10 @@ index f806cdbdc..ed9825df3 100644 void skippy_error_free(struct skippy_error * error) { diff --git a/src/skippy/asr.cpp b/src/skippy/asr.cpp new file mode 100644 -index 000000000..680549066 +index 000000000..a0c619289 --- /dev/null +++ b/src/skippy/asr.cpp -@@ -0,0 +1,465 @@ +@@ -0,0 +1,447 @@ +#include "skippy/asr.h" +#include "skippy/errors.h" + @@ -358,7 +376,7 @@ index 000000000..680549066 +#define MA_NO_ENGINE +#define MA_NO_GENERATION +#define MA_API static -+#include "miniaudio/miniaudio.h" ++#include "asr_decode.h" +#endif + +struct skippy_asr_model { @@ -470,7 +488,7 @@ index 000000000..680549066 + return stat(path, &info) == 0 ? static_cast(info.st_size) : 0; +} + -+enum class decode_outcome { ok, failed, too_long }; ++using skippy_asr_detail::decode_outcome; + +decode_outcome decode_audio(const uint8_t * data, size_t len, std::vector & samples) { + ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 1, SKIPPY_ASR_SAMPLE_RATE); @@ -482,26 +500,8 @@ index 000000000..680549066 + return decode_outcome::failed; + } + // Read in chunks: VBR MP3 cannot always report its length up front. -+ constexpr ma_uint64 chunk = SKIPPY_ASR_SAMPLE_RATE; -+ decode_outcome outcome = decode_outcome::ok; -+ for (;;) { -+ if (samples.size() >= static_cast(SKIPPY_ASR_MAX_SAMPLES)) { -+ outcome = decode_outcome::too_long; -+ break; -+ } -+ const size_t offset = samples.size(); -+ samples.resize(offset + chunk); -+ ma_uint64 read = 0; -+ const ma_result result = ma_decoder_read_pcm_frames(&decoder, samples.data() + offset, chunk, &read); -+ samples.resize(offset + read); -+ if (result == MA_AT_END || (result == MA_SUCCESS && read < chunk)) { -+ break; -+ } -+ if (result != MA_SUCCESS) { -+ outcome = decode_outcome::failed; -+ break; -+ } -+ } ++ const decode_outcome outcome = skippy_asr_detail::read_bounded_audio( ++ decoder, samples, static_cast(SKIPPY_ASR_MAX_SAMPLES), SKIPPY_ASR_SAMPLE_RATE); + ma_decoder_uninit(&decoder); + return outcome; +} @@ -787,6 +787,149 @@ index 000000000..680549066 +extern "C" void skippy_asr_result_free(struct skippy_asr_result * result) { + delete result; +} +diff --git a/src/skippy/asr_decode.h b/src/skippy/asr_decode.h +new file mode 100644 +index 000000000..c56a5ea9c +--- /dev/null ++++ b/src/skippy/asr_decode.h +@@ -0,0 +1,50 @@ ++#pragma once ++ ++#if defined(_WIN32) && !defined(NOMINMAX) ++#define NOMINMAX ++#endif ++#include "miniaudio/miniaudio.h" ++ ++#include ++#include ++ ++namespace skippy_asr_detail { ++ ++enum class decode_outcome { ok, failed, too_long }; ++ ++// The production limit and read chunk are supplied by the ASR contract. Keeping the ++// decoder loop independent of Whisper also permits small, real audio boundary tests. ++inline decode_outcome read_bounded_audio(ma_decoder & decoder, std::vector & samples, ++ size_t limit, ma_uint64 chunk) { ++ if (samples.size() > limit) { ++ return decode_outcome::too_long; ++ } ++ if (chunk == 0) { ++ return decode_outcome::failed; ++ } ++ while (samples.size() < limit) { ++ const size_t offset = samples.size(); ++ const ma_uint64 request = (std::min)(chunk, limit - offset); ++ samples.resize(offset + static_cast(request)); ++ ma_uint64 read = 0; ++ const ma_result result = ma_decoder_read_pcm_frames(&decoder, samples.data() + offset, request, &read); ++ samples.resize(offset + static_cast(read)); ++ if (result == MA_AT_END || (result == MA_SUCCESS && read < request)) { ++ return decode_outcome::ok; ++ } ++ if (result != MA_SUCCESS) { ++ return decode_outcome::failed; ++ } ++ } ++ // A successful full read does not establish EOF. Probe one frame without growing ++ // the sample buffer: the inclusive maximum is valid only if no further frame exists. ++ float extra = 0.0f; ++ ma_uint64 read = 0; ++ const ma_result result = ma_decoder_read_pcm_frames(&decoder, &extra, 1, &read); ++ if (read != 0) { ++ return decode_outcome::too_long; ++ } ++ return result == MA_AT_END || result == MA_SUCCESS ? decode_outcome::ok : decode_outcome::failed; ++} ++ ++} // namespace skippy_asr_detail +diff --git a/src/skippy/tests/asr_decode_boundary.cpp b/src/skippy/tests/asr_decode_boundary.cpp +new file mode 100644 +index 000000000..a5b1ff113 +--- /dev/null ++++ b/src/skippy/tests/asr_decode_boundary.cpp +@@ -0,0 +1,81 @@ ++// Use the same file-local decoder implementation as ASR, without a Whisper model. ++#define ma_atomic_global_lock skippy_asr_test_ma_atomic_global_lock ++#define MINIAUDIO_IMPLEMENTATION ++#define MA_NO_ENCODING ++#define MA_NO_DEVICE_IO ++#define MA_NO_RESOURCE_MANAGER ++#define MA_NO_NODE_GRAPH ++#define MA_NO_ENGINE ++#define MA_NO_GENERATION ++#define MA_API static ++#include "../asr_decode.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace { ++void le16(std::vector & wav, size_t offset, uint16_t value) { ++ wav[offset] = uint8_t(value); ++ wav[offset + 1] = uint8_t(value >> 8); ++} ++ ++void le32(std::vector & wav, size_t offset, uint32_t value) { ++ le16(wav, offset, uint16_t(value)); ++ le16(wav, offset + 2, uint16_t(value >> 16)); ++} ++ ++bool check(size_t frames, size_t limit) { ++ // A real mono PCM WAV, just a few frames long. Samples remain recognizable ++ // after decoding so boundary checks also detect skipped/duplicated frames. ++ std::vector wav(44 + frames * 2, 0); ++ std::memcpy(wav.data(), "RIFF", 4); ++ le32(wav, 4, uint32_t(wav.size() - 8)); ++ std::memcpy(wav.data() + 8, "WAVEfmt ", 8); ++ le32(wav, 16, 16); ++ le16(wav, 20, 1); ++ le16(wav, 22, 1); ++ le32(wav, 24, 16000); ++ le32(wav, 28, 32000); ++ le16(wav, 32, 2); ++ le16(wav, 34, 16); ++ std::memcpy(wav.data() + 36, "data", 4); ++ le32(wav, 40, uint32_t(frames * 2)); ++ for (size_t i = 0; i < frames; ++i) { ++ le16(wav, 44 + i * 2, uint16_t((i + 1) * 1024)); ++ } ++ auto config = ma_decoder_config_init(ma_format_f32, 1, 16000); ++ ma_decoder decoder; ++ if (ma_decoder_init_memory(wav.data(), wav.size(), &config, &decoder) != MA_SUCCESS) { ++ return false; ++ } ++ std::vector samples; ++ const auto outcome = skippy_asr_detail::read_bounded_audio(decoder, samples, limit, 4); ++ ma_decoder_uninit(&decoder); ++ const auto expected = frames > limit ? skippy_asr_detail::decode_outcome::too_long : ++ skippy_asr_detail::decode_outcome::ok; ++ bool valid = outcome == expected && samples.size() == (std::min)(frames, limit); ++ for (size_t i = 0; i < samples.size(); ++i) { ++ valid &= std::fabs(samples[i] - float(i + 1) / 32.0f) < 1e-6f; ++ } ++ if (!valid) { ++ std::fprintf(stderr, "audio frames=%zu limit=%zu: outcome=%d retained=%zu\n", ++ frames, limit, int(outcome), samples.size()); ++ } ++ return valid; ++} ++} // namespace ++ ++int main() { ++ // Exercise a chunk-aligned limit (requires an EOF probe) and an unaligned ++ // limit (requires capping the last read). No large allocation or model needed. ++ for (size_t limit : { size_t(8), size_t(7) }) { ++ for (size_t frames : { limit - 1, limit, limit + 1 }) { ++ if (!check(frames, limit)) { ++ return 1; ++ } ++ } ++ } ++ return 0; ++} -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 7fa4eb13e8..0cf24fb8cb 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -375,5 +375,5 @@ index d3de66cbe..3ca967bf3 100644 namespace { -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch index 0da41413d3..c7d1053be7 100644 --- a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch +++ b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch @@ -406,5 +406,5 @@ index 89b5135a4..682a1b061 100644 saver.save(path); require_fixture_written(path); -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch index 5f4ebfb536..3a63909f16 100644 --- a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch @@ -775,5 +775,5 @@ index 000000000..6ccd39221 + }); +} -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index e35afa4c92..bcf0f8404d 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -528,6 +528,8 @@ if [[ "$LLAMA_STAGE_WORKLOAD_ORACLE" == "ON" ]]; then fi if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then BUILD_TARGETS+=( + skippy-asr-decode-boundary + skippy-diffusion-host-fallback skippy-graph-build-inputs skippy-hardware-application-probe skippy-model-fixture-generator diff --git a/tools/xtask/src/automation/kv_validation/tests/cache_client.rs b/tools/xtask/src/automation/kv_validation/tests/cache_client.rs index 2eb5130e1d..a8d9c83631 100644 --- a/tools/xtask/src/automation/kv_validation/tests/cache_client.rs +++ b/tools/xtask/src/automation/kv_validation/tests/cache_client.rs @@ -33,6 +33,7 @@ impl Endpoint { while !stopped.load(Ordering::Acquire) && Instant::now() < deadline { match listener.accept() { Ok((mut stream, _)) => { + stream.set_nonblocking(false).unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index c4b4423ef9..c64e31cace 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -224,6 +224,8 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( assert!(contains(configure, flag)); } for target in [ + "skippy-asr-decode-boundary", + "skippy-diffusion-host-fallback", "skippy-graph-build-inputs", "skippy-selected-logits", "skippy-hardware-application-probe", From cfa7587ea003e55af5c61ef163d5d6ae5986a25f Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 6 Nov 2026 13:45:32 +1100 Subject: [PATCH 30/81] fix: address cache and AgentX review findings --- .agents/skills/manage-ci/SKILL.md | 10 +- .../manage-ci/references/current-inventory.md | 15 + .github/actions/plan-ci/action.yml | 6 +- ci/ci.md | 15 + mesh/website/src/docs/pages/skippy-api.md | 4 +- .../crates/skippy-ffi/src/bindings/skippy.rs | 50 +- skippy/crates/skippy-ffi/src/lib.rs | 12 +- .../src/binary_transport/binary_kv.rs | 54 +- .../binary_kv/restore_preparation.rs | 78 + .../binary_messaging/connection.rs | 13 +- .../binary_messaging/control_messages.rs | 6 +- .../restore_prefill_decode.rs | 6 +- .../src/binary_transport/stage_execution.rs | 6 +- .../skippy-serving/src/frontend/backend.rs | 1 - .../src/frontend/local_generation/tests.rs | 152 - .../local_generation/tests/durable_prefix.rs | 299 +- .../tests/recurrent_fixture.rs | 2 +- .../token_generation/cache_prefill.rs | 21 +- .../token_generation/kv_restore.rs | 15 +- .../frontend/prefix_cache/split_restore.rs | 9 +- .../src/frontend/system_one/causal/cache.rs | 9 +- .../src/frontend/tests/cache_publication.rs | 1 - .../src/kv_integration/exact_state.rs | 35 +- .../exact_state/resident_preference.rs | 181 +- .../exact_state/resident_preference/tests.rs | 237 + .../src/kv_integration/exact_state/restore.rs | 26 +- .../skippy-serving/src/kv_integration/mod.rs | 1 + .../skippy-serving/src/runtime_state.rs | 2 + .../src/runtime_state/model_content.rs | 127 +- .../docs/design/INDEXED_ATTENTION_STATUS.md | 209 +- skippy/evals/kv-validation/README.md | 8 +- ...ippy-define-graph-derived-native-ABI.patch | 54 +- ...ize-admitted-stages-from-live-graphs.patch | 988 ++-- ...rate-live-stage-planning-and-executi.patch | 3760 +--------------- ...e-native-runtime-and-backend-support.patch | 12 +- ...cover-live-graph-and-state-contracts.patch | 1854 +------- ...native-MTP-state-across-verify-trims.patch | 4 +- ...re-attaching-backend-samplers-betwee.patch | 8 +- ...e-routed-experts-of-a-block-range-in.patch | 4 +- ...equest-local-KV-indices-in-flash-att.patch | 3975 ----------------- ...the-argmax-path-for-temperature-0-ch.patch | 171 +- ...rrent-rollback-for-speculative-verif.patch | 10 +- ...-back-staged-verify-windows-in-place.patch | 88 +- ...03-llama-port-diffusiongemma-support.patch | 187 +- ...-add-diffusiongemma-system-one-reads.patch | 4 +- ...skippy-query-diffusion-canvas-length.patch | 2 +- ...dels-add-laya-decision-model-support.patch | 6 +- ...-parse-implicit-reasoning-continuati.patch | 2 +- ...0008-models-add-qwen3-moe-native-mtp.patch | 2 +- ...kippy-add-whisper-speech-recognition.patch | 10 +- ...rd-per-token-logprobs-while-sampling.patch | 20 +- ...pose-glm5-next-stage-graph-semantics.patch | 4 +- ...skippy-add-clef-joint-decision-reads.patch | 2 +- todo.md | 69 + .../automation/agentx/final_sweep_tests.rs | 181 + .../src/automation/agentx/prepared_tools.rs | 59 + .../src/automation/kv_validation/evidence.rs | 29 + .../src/automation/kv_validation/execution.rs | 43 +- .../src/automation/kv_validation/tests.rs | 30 + 59 files changed, 2621 insertions(+), 10567 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/binary_transport/binary_kv/restore_preparation.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs delete mode 100644 skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 2ae328da08..47b379786a 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -137,8 +137,14 @@ Python-free or remove legacy validation before its Rust replacement passes. Retained external Python dependencies have bounded owners: the admitted external Python SDK and its locked client environments, llama.cpp's upstream Jinja and FP8 conversion tests -using the trusted controller's `ci/llama-canary/jinja/uv.lock`, and the optional llama-benchy wrapper with -an immutable default source commit. These interfaces do not authorize new +using the trusted controller's `ci/llama-canary/jinja/uv.lock`, the optional +llama-benchy wrapper with an immutable default source commit, and the pinned +external AgentX client environment under `skippy/evals/agentx/`. AgentX setup +uses an installed Python 3.12 interpreter without interpreter downloads; +prepared campaign workers remain offline. Its exact dependency inputs, +upstream wheel identity, and setup invocation belong to the typed policy below. +See [the November 6 AgentX maintainer decision](references/maintainer-decisions.md). +These interfaces do not authorize new repository Python implementations. The canary Jinja environment belongs to its run's state directory and must use a preinstalled interpreter; dependency restoration must not download an interpreter or skip upstream tests. Freeze the diff --git a/.agents/skills/manage-ci/references/current-inventory.md b/.agents/skills/manage-ci/references/current-inventory.md index b5b9b70509..1e5f911e65 100644 --- a/.agents/skills/manage-ci/references/current-inventory.md +++ b/.agents/skills/manage-ci/references/current-inventory.md @@ -1,5 +1,19 @@ # MeshLLM CI inventory +Manual KV validation lives in `automation kv-validation` and the thin +`skippy-kv-*` Just recipes. It prepares one external native test harness against +an exact packaged runtime, then reuses producer artifacts for the four pinned +AgentX models. Its explicit Linux JY CPU/CUDA specs use the accepted lab/custom +schema; Metal runs natively through the same local owner. This foundation is +not selected by ordinary CI and does not qualify deferred long-c4/L3/performance +checks. See `skippy/evals/kv-validation/README.md`. + +The optional AgentX comparison owner consumes the pinned external client and +locked environment in `skippy/evals/agentx/`. The November 6 maintainer decision +admits this bounded dependency through `ci/python-tooling-policy.json`. +`agentx-setup` uses installed Python 3.12 without interpreter downloads; +campaign workers use prepared inputs offline. This adds no required CI lane. + Every workflow disables Rust debug information for the dev, test, release and bench profiles through workflow- or job-level `CARGO_PROFILE__DEBUG=0`. Reusable workflows set their own environment, and the Linux test, client and @@ -12,6 +26,7 @@ checks are preserved. Cache epoch `v5` invalidates the previous namespace. Batch jobs report filesystem space before each package and target/compiler-cache sizes after the test step, including failures. + The standalone C++ facade paths `skippy/skippy_api/**` and `skippy/skippy-api-rs/**` have additive tooling ownership. Their catalog-only admission is a protected-main prerequisite before dependent branches adopt the diff --git a/.github/actions/plan-ci/action.yml b/.github/actions/plan-ci/action.yml index f97dc900bd..6f1e5d2272 100644 --- a/.github/actions/plan-ci/action.yml +++ b/.github/actions/plan-ci/action.yml @@ -199,11 +199,13 @@ runs: exit 1 fi manifest_root=$(mktemp -d "$RUNNER_TEMP/mesh-ci-manifests.XXXXXX") - # BSD tar can stop after end markers before git writes its padding. - # Finish the producer first so pipefail cannot mistake SIGPIPE for drift. + # BSD tar may stop at end-of-archive before Git writes its final + # padding. Materialize the archive so pipefail cannot reject valid + # manifests because the producer receives SIGPIPE. manifest_archive=$(mktemp "$RUNNER_TEMP/mesh-ci-manifest-archive.XXXXXX") git archive --format=tar "$SOURCE_SHA" -- ci/ownership.yml ci/slices.yml > "$manifest_archive" tar -x -f "$manifest_archive" -C "$manifest_root" + rm "$manifest_archive" profile=pr-ready if [[ "$DRAFT" == "true" ]]; then profile=pr-draft diff --git a/ci/ci.md b/ci/ci.md index 72c5dee35c..4405eebc6e 100644 --- a/ci/ci.md +++ b/ci/ci.md @@ -1,5 +1,19 @@ # MeshLLM CI topology +`automation kv-validation` is an explicit manual diagnostic surface, separate +from the five required PR/main lanes. One backend producer prepares matching +tools and the external indexed-attention model harness once; four model jobs +reuse the immutable prepared image. The Linux JY adapter emits CPU/CUDA custom +jobs without dispatching them. Native Metal uses the local worker command. +No automatic GPU/model fan-out or required-check topology changes accompany +this foundation. See `skippy/evals/kv-validation/README.md` for its bounded scope. + +The optional AgentX comparison uses a separately prepared, pinned upstream +client environment. Its manifest, lock, wheel identity and setup invocation are +admitted by `ci/python-tooling-policy.json` under the November 6 maintainer +decision. Setup requires installed Python 3.12; workers remain offline. The +allowance changes no required-check topology or generic Python tooling policy. + All workflows disable Rust debug information with workflow- or job-level `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0`, `CARGO_PROFILE_RELEASE_DEBUG=0` and `CARGO_PROFILE_BENCH_DEBUG=0`. @@ -13,6 +27,7 @@ before each package and retained target/compiler-cache sizes even when tests fai The upstream canary sets the environment in each executing job and its reusable family-pass workflow separately. + ## Standalone C++ API qualification The protected catalog admits `skippy/skippy_api/**` and diff --git a/mesh/website/src/docs/pages/skippy-api.md b/mesh/website/src/docs/pages/skippy-api.md index dc93d75e49..b5244bcef9 100644 --- a/mesh/website/src/docs/pages/skippy-api.md +++ b/mesh/website/src/docs/pages/skippy-api.md @@ -9,7 +9,7 @@ description: Generated reference for the capability-oriented Skippy C ABI. This reference is generated from the patched llama.cpp public headers. It documents the native C ABI used by Skippy's Rust FFI layer and staged runtime. The ABI is experimental and versioned for lockstep native/Rust builds. -Current generated surface: **21 headers** and **131 exported functions**. +Current generated surface: **21 headers** and **134 exported functions**. ## Quick navigation @@ -199,7 +199,7 @@ Current generated surface: **21 headers** and **131 exported functions**.
- state.h17 functions + state.h20 functions
skippy_model_memory_cache_capabilities skippy_export_state diff --git a/skippy/crates/skippy-ffi/src/bindings/skippy.rs b/skippy/crates/skippy-ffi/src/bindings/skippy.rs index 903025aeaa..6f28bcc65a 100644 --- a/skippy/crates/skippy-ffi/src/bindings/skippy.rs +++ b/skippy/crates/skippy-ffi/src/bindings/skippy.rs @@ -510,7 +510,7 @@ pub struct skippy_runtime_config { pub glm_dsa_compact_flash_min_kv: i32, #[doc = " @brief Whether K/V tensors are offloaded to the compute backend (mirrors upstream `offload_kqv`)."] pub kv_offload: i32, - #[doc = " @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO derives the setting from lane count; recurrent and hybrid models force it true."] + #[doc = " @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO enables unified caching at every lane count. Explicit false selects non-unified caching, except recurrent and hybrid models force it true."] pub kv_unified: i32, #[doc = " @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`)."] pub swa_full: i32, @@ -1327,6 +1327,10 @@ pub enum skippy_memory_cache_capability { Resident = 1, KvRecurrent = 2, FullState = 4, + #[doc = " Resident prefixes restore only their exact saved recurrent checkpoint boundary."] + ResidentCheckpoint = 8, + #[doc = " Complete resident prefixes contain attention cells in addition to any recurrent state."] + ResidentAttention = 16, } unsafe extern "C" { #[doc = " @brief Returns complete cache representations admitted by the built graph and loaded memory.\n Graph state effects restrict the loaded memory adapters' complete export capabilities.\n Full-state serialization is admitted explicitly too. Zero means no complete\n cache representation is available; callers cannot supply capability labels."] @@ -1454,7 +1458,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Exports recurrent state for models that maintain recurrent memory."] + #[doc = " @brief Exports only recurrent memory; attention pages are exported independently."] pub fn skippy_export_recurrent_state( session: *mut skippy_session, output: *mut ::std::os::raw::c_void, @@ -1475,7 +1479,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Imports recurrent state into a session."] + #[doc = " @brief Imports recurrent-only state into a session."] pub fn skippy_import_recurrent_state( session: *mut skippy_session, input: *const ::std::os::raw::c_void, @@ -1545,7 +1549,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Saves a session prefix into a resident cache sequence."] + #[doc = " @brief Retains shared attention cells and an immutable recurrent checkpoint owned by the cache.\n Recurrent memory requires token_count equal to the current session position."] pub fn skippy_session_save_prefix( session: *mut skippy_session, cache_seq_id: i32, @@ -1554,7 +1558,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Restores a session prefix from a resident cache sequence."] + #[doc = " @brief Shares retained attention cells and restores a private mutable recurrent row.\n Token identity must match; recurrent prefixes require the exact saved boundary."] pub fn skippy_session_restore_prefix( session: *mut skippy_session, cache_seq_id: i32, @@ -1563,6 +1567,42 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +unsafe extern "C" { + #[doc = " @brief Exports a cache-owned attention page for cold offload without claiming or restoring an execution lane."] + pub fn skippy_session_export_resident_kv_page( + session: *mut skippy_session, + cache_seq_id: i32, + layer_start: i32, + layer_end: i32, + token_start: u64, + token_count: u64, + out_desc: *mut skippy_kv_page_desc, + output: *mut ::std::os::raw::c_void, + output_capacity: usize, + out_bytes: *mut usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors."] + pub fn skippy_session_export_resident_recurrent_state( + session: *mut skippy_session, + cache_seq_id: i32, + output: *mut ::std::os::raw::c_void, + output_capacity: usize, + out_bytes: *mut usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool."] + pub fn skippy_session_resident_prefix_bytes( + session: *mut skippy_session, + cache_seq_id: i32, + out_bytes: *mut u64, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Reports physically occupied cells in the session's unified KV cache."] pub fn skippy_session_memory_used_cells( diff --git a/skippy/crates/skippy-ffi/src/lib.rs b/skippy/crates/skippy-ffi/src/lib.rs index f95afe6682..aacbd2291e 100644 --- a/skippy/crates/skippy-ffi/src/lib.rs +++ b/skippy/crates/skippy-ffi/src/lib.rs @@ -268,12 +268,14 @@ pub use static_bindings::{ skippy_session_begin_external_decode, skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, skippy_session_create, skippy_session_create_from_resident_prefix, skippy_session_drop_sequence, skippy_session_embed, - skippy_session_encode_prompt, skippy_session_end_external_decode, skippy_session_free, - skippy_session_last_token_signal, skippy_session_llama_context, + skippy_session_encode_prompt, skippy_session_end_external_decode, + skippy_session_export_resident_kv_page, skippy_session_export_resident_recurrent_state, + skippy_session_free, skippy_session_last_token_signal, skippy_session_llama_context, skippy_session_memory_used_cells, skippy_session_position, skippy_session_rerank, - skippy_session_reset, skippy_session_restore_prefix, skippy_session_restore_token_history, - skippy_session_sample_current, skippy_session_save_prefix, skippy_session_sequence_id, - skippy_session_set_position, skippy_session_signal_window, skippy_session_take_token_logprobs, + skippy_session_reset, skippy_session_resident_prefix_bytes, skippy_session_restore_prefix, + skippy_session_restore_token_history, skippy_session_sample_current, + skippy_session_save_prefix, skippy_session_sequence_id, skippy_session_set_position, + skippy_session_signal_window, skippy_session_take_token_logprobs, skippy_session_verify_rollback_counts, skippy_stage_plan_describe_v1, skippy_stage_plan_free, skippy_stage_plan_profile_at_v1, skippy_stage_plan_resident_tensor_at_v1, skippy_stage_plan_state_at_v1, skippy_stage_plan_string_v1, diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_kv.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_kv.rs index cfec2b9c41..324f26e58c 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_kv.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_kv.rs @@ -9,7 +9,7 @@ use crate::{ runtime_state::RuntimeState, telemetry::{Telemetry, lifecycle_attrs}, }; -use anyhow::Result; +use anyhow::{Context, Result}; use serde_json::{Value, json}; use skippy_metrics::attr; use skippy_protocol::{ @@ -19,9 +19,14 @@ use skippy_protocol::{ use skippy_runtime::ActivationFrame; use super::kv_eviction::BinaryProactiveEviction; +mod restore_preparation; use super::stage_execution::{ binary_message_base, binary_message_request_id, elapsed_ms, stage_mask, }; +pub(in crate::binary_transport) use restore_preparation::{ + PreparedBinaryPrefill, PreparedPrefixControl, prepare_binary_prefill, + prepare_prefix_cache_control, +}; #[derive(Default)] pub(in crate::binary_transport) struct BinaryKvLookupResult { @@ -135,16 +140,17 @@ pub(super) fn binary_message_kv_attrs( pub(in crate::binary_transport) fn maybe_prefix_cache_control( config: &StageConfig, runtime: &mut RuntimeState, - kv: Option<&Arc>, + prepared: Option<&PreparedPrefixControl>, telemetry: &Telemetry, session_id: &str, message: &StageWireMessage, token_ids: &[i32], ) -> BinaryPrefixCacheControlResult { let mut result = BinaryPrefixCacheControlResult::default(); - let Some(kv) = kv else { + let Some(prepared) = prepared else { return result; }; + let kv = &prepared.kv; if !kv.should_lookup() || token_ids.is_empty() { return result; } @@ -208,13 +214,11 @@ pub(in crate::binary_transport) fn maybe_prefix_cache_control( WireMessageKind::RestorePrefill | WireMessageKind::TryRestorePrefill | WireMessageKind::TryRestorePrefillDecode => { - let restore = restore_binary_prefix( - kv, - runtime, - session_id, - std::slice::from_ref(&identity), - token_ids, - ); + let restore = prepared + .exact + .as_ref() + .context("missing prepared binary exact-state lookup") + .and_then(|exact| restore_binary_prefix(kv, runtime, session_id, exact, token_ids)); match restore { Ok(Some(restored)) if restored.token_count >= token_ids.len() => { result.hit = true; @@ -285,17 +289,17 @@ fn restore_binary_prefix( kv: &KvStageIntegration, runtime: &mut RuntimeState, session_id: &str, - identities: &[PrefillKvIdentity], + prepared: &crate::kv_integration::PreparedExactStateRestore, token_ids: &[i32], ) -> Result> { - match kv.restore_exact_state(runtime, session_id, identities)? { + match kv.restore_prepared_exact_state(runtime, session_id, prepared, None)? { Some(restored) => Ok(Some(BinaryRestoredPrefix::exact( restored.page_id, restored.token_count, restored.entries, ))), None => kv - .restore_resident_prefix(runtime, session_id, identities, token_ids) + .restore_resident_prefix(runtime, session_id, prepared.identities(), token_ids) .map(|restored| { restored.map(|restored| { BinaryRestoredPrefix::resident( @@ -322,17 +326,17 @@ pub(in crate::binary_transport) fn emit_binary_proactive_eviction( pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( config: &StageConfig, runtime: &mut RuntimeState, - kv: Option<&Arc>, + prepared: Option, telemetry: &Telemetry, session_id: &str, message: &StageWireMessage, token_ids: &[i32], - activation_width: i32, ) -> BinaryKvLookupResult { let mut result = BinaryKvLookupResult::default(); - let Some(kv) = kv else { + let Some(prepared) = prepared else { return result; }; + let kv = &prepared.kv; if !message.kind.is_prefill() || message.kind.requires_predicted_reply() || !kv.should_lookup() @@ -341,8 +345,7 @@ pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( return result; } let token_start = message.pos_start.max(0) as u64; - let base = binary_message_base(config, session_id, message); - let identities = kv.lookup_identities(config, &base, token_start, token_ids); + let identities = &prepared.identities; let mut attrs = binary_message_kv_attrs(config, kv, session_id, message, token_ids.len()); attrs.insert( "skippy.kv.lookup_candidates".to_string(), @@ -363,9 +366,7 @@ pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( return result; } if config.downstream.is_some() { - let Some(activation) = - kv.restore_resident_activation(config, &base, token_start, token_ids, activation_width) - else { + let Some(activation) = prepared.activation else { result.stats.kv_lookup_misses += 1; attrs.insert( "skippy.kv.lookup_ms".to_string(), @@ -378,13 +379,8 @@ pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( telemetry.emit("stage.binary_kv_lookup_decision", attrs); return result; }; - let prefix_restore = restore_binary_prefix( - kv, - runtime, - session_id, - std::slice::from_ref(&activation.identity), - token_ids, - ); + let prefix_restore = + restore_binary_prefix(kv, runtime, session_id, &prepared.exact, token_ids); match prefix_restore { Ok(Some(restored)) if restored.token_count >= token_ids.len() => { result.restored_tokens = restored.token_count; @@ -474,7 +470,7 @@ pub(in crate::binary_transport) fn maybe_lookup_binary_prefill( } } } - let prefix_restore = restore_binary_prefix(kv, runtime, session_id, &identities, token_ids); + let prefix_restore = restore_binary_prefix(kv, runtime, session_id, &prepared.exact, token_ids); match prefix_restore { Ok(Some(restored)) => { result.restored_tokens = restored.token_count; diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_kv/restore_preparation.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_kv/restore_preparation.rs new file mode 100644 index 0000000000..07fa733753 --- /dev/null +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_kv/restore_preparation.rs @@ -0,0 +1,78 @@ +//! Disk metadata preparation before binary work enters the runtime scheduler. +use super::*; +use crate::kv_integration::{PreparedExactStateRestore, ResidentActivationRestore}; + +pub(in crate::binary_transport) struct PreparedPrefixControl { + pub(super) kv: Arc, + pub(super) exact: Option, +} + +pub(in crate::binary_transport) struct PreparedBinaryPrefill { + pub(super) kv: Arc, + pub(super) identities: Vec, + pub(super) activation: Option, + pub(super) exact: PreparedExactStateRestore, +} + +pub(in crate::binary_transport) fn prepare_prefix_cache_control( + config: &StageConfig, + kv: Option<&Arc>, + session_id: &str, + message: &StageWireMessage, + tokens: &[i32], +) -> Option { + let kv = kv?; + let restoring = matches!( + message.kind, + WireMessageKind::RestorePrefill + | WireMessageKind::TryRestorePrefill + | WireMessageKind::TryRestorePrefillDecode + ); + let exact = (restoring + && kv.should_lookup() + && !tokens.is_empty() + && (message.pos_start <= 0 || message.kind == WireMessageKind::TryRestorePrefillDecode)) + .then(|| { + let base = binary_message_base(config, session_id, message); + let identity = kv.prefill_identity(config, &base, 0, tokens); + kv.prepare_exact_state_restore(&[identity], false) + }); + Some(PreparedPrefixControl { + kv: Arc::clone(kv), + exact, + }) +} + +pub(in crate::binary_transport) fn prepare_binary_prefill( + config: &StageConfig, + kv: Option<&Arc>, + session_id: &str, + message: &StageWireMessage, + tokens: &[i32], + activation_width: i32, +) -> Option { + let kv = kv?; + let start = message.pos_start.max(0) as u64; + let base = binary_message_base(config, session_id, message); + let identities = kv.lookup_identities(config, &base, start, tokens); + let activation = (config.downstream.is_some() && start == 0) + .then(|| kv.restore_resident_activation(config, &base, start, tokens, activation_width)) + .flatten(); + let candidates: &[PrefillKvIdentity] = if config.downstream.is_some() { + activation + .as_ref() + .map(|hit| std::slice::from_ref(&hit.identity)) + .unwrap_or_default() + } else if start == 0 { + &identities + } else { + &[] + }; + let exact = kv.prepare_exact_state_restore(candidates, false); + Some(PreparedBinaryPrefill { + kv: Arc::clone(kv), + identities, + activation, + exact, + }) +} diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs index 75fbdc5a1c..edf6309fe8 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/connection.rs @@ -29,6 +29,7 @@ use crate::binary_transport::binary_kv::add_binary_record_stats; use crate::binary_transport::binary_kv::emit_binary_proactive_eviction; use crate::binary_transport::binary_kv::maybe_lookup_binary_prefill; use crate::binary_transport::binary_kv::maybe_record_binary_full_prefill; +use crate::binary_transport::binary_kv::prepare_binary_prefill; use crate::binary_transport::direct_return; use crate::binary_transport::direct_return::PredictionReturnSinks; use crate::binary_transport::forwarded_stage_message_timed; @@ -452,7 +453,14 @@ fn handle_binary_connection_messages( && !token_ids.is_empty(); let lookup_result = if lookup_needed { let lookup_config = config.clone(); - let lookup_kv = kv.cloned(); + let prepared = prepare_binary_prefill( + config, + kv, + &session_key, + &message, + &token_ids, + output_activation_width, + ); let lookup_telemetry = telemetry.clone(); let lookup_session_key = session_key.clone(); let lookup_token_ids = token_ids.clone(); @@ -470,12 +478,11 @@ fn handle_binary_connection_messages( let lookup_result = maybe_lookup_binary_prefill( &lookup_config, runtime, - lookup_kv.as_ref(), + prepared, &lookup_telemetry, &lookup_session_key, &message, &lookup_token_ids, - output_activation_width, ); Ok((message, auto_align, lookup_result)) }) diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/control_messages.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/control_messages.rs index 09d23028b7..d7bf4ea315 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/control_messages.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging/control_messages.rs @@ -8,7 +8,7 @@ use super::summary::BinaryRequestSummary; use crate::binary_transport::WireCondition; use crate::binary_transport::binary_kv::{ accumulate_shared_prefill_tokens, maybe_prefix_cache_control, maybe_record_binary_full_prefill, - take_shared_prefill_tokens, + prepare_prefix_cache_control, take_shared_prefill_tokens, }; use crate::binary_transport::direct_return::PredictionReturnSinks; use crate::binary_transport::peer_sampling::runtime_sampling_config; @@ -381,7 +381,7 @@ pub(super) fn handle_prefix_cache_control( let token_ids = token_sideband_or_fill(&message).context("read prefix cache control token sideband")?; let scheduler_config = config.clone(); - let scheduler_kv = kv.cloned(); + let prepared = prepare_prefix_cache_control(config, kv, session_key, &message, &token_ids); let scheduler_telemetry = telemetry.clone(); let scheduler_session_key = session_key.to_string(); let scheduler_message = message.clone(); @@ -391,7 +391,7 @@ pub(super) fn handle_prefix_cache_control( Ok(maybe_prefix_cache_control( &scheduler_config, runtime, - scheduler_kv.as_ref(), + prepared.as_ref(), &scheduler_telemetry, &scheduler_session_key, &scheduler_message, diff --git a/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs b/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs index d330b04c41..ea85d8c2d9 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/restore_prefill_decode.rs @@ -22,7 +22,7 @@ use super::{ use super::{ binary_kv::{ add_binary_record_stats, emit_binary_proactive_eviction, maybe_prefix_cache_control, - maybe_record_binary_full_prefill, + maybe_record_binary_full_prefill, prepare_prefix_cache_control, }, binary_messaging::reply::configure_prediction_return_stream, direct_return::PredictionReturnSinks, @@ -91,7 +91,7 @@ pub(super) fn handle_binary_restore_prefill_decode_control( let (prefix_tokens, current_token) = restore_decode_sideband(&message)?; let lookup_config = config.clone(); - let lookup_kv = kv.cloned(); + let prepared = prepare_prefix_cache_control(config, kv, session_id, &message, prefix_tokens); let lookup_telemetry = telemetry.clone(); let lookup_session_id = session_id.to_string(); let lookup_message = message.clone(); @@ -101,7 +101,7 @@ pub(super) fn handle_binary_restore_prefill_decode_control( Ok(maybe_prefix_cache_control( &lookup_config, runtime, - lookup_kv.as_ref(), + prepared.as_ref(), &lookup_telemetry, &lookup_session_id, &lookup_message, diff --git a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs index 39b3b281be..1a2c600a10 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs @@ -847,8 +847,10 @@ fn execute_binary_stage_message( )) } WireMessageKind::VerifyWindow => { - let sampling = - runtime_sampling_config(message.sampling.as_ref(), runtime.kv_pool_tokens()); + let sampling = runtime_sampling_config( + message.sampling.as_ref(), + runtime.context_tokens_per_lane(), + ); let native_mtp_tokens = if dflash_drafts { 0 } else { diff --git a/skippy/crates/skippy-serving/src/frontend/backend.rs b/skippy/crates/skippy-serving/src/frontend/backend.rs index 6d22130678..982b7bf5aa 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend.rs @@ -36,7 +36,6 @@ use crate::frontend::generation::completion_response_from_generated_text; use crate::frontend::generation::ensure_requested_model; use crate::frontend::generation::generation_event_to_completion_chunk; use crate::frontend::generation::generation_event_to_inference_event; -use crate::frontend::generation::generation_predicted_wait_error; use crate::frontend::generation::generation_queue_timeout_error; use crate::frontend::generation::generation_response_from_generated_text; use crate::frontend::generation::template_exposes_reasoning; diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index 7a80d13c6a..b8fe337fc6 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -173,158 +173,6 @@ fn wait_for_receipts(sink: &RecordingReceiptSink, expected: usize) { panic!("timed out waiting for {expected} generation receipts"); } -const RECURRENT_TEST_CHECKPOINT_RAM_BYTES: u64 = 8 * 1024 * 1024 * 1024; - -fn recurrent_test_backend( - run_id: &str, - backend_model_id: &str, - ctx_size: usize, - batch_size: u32, - default_max_tokens: u32, - token_budget: usize, -) -> Result<(StageOpenAiBackend, SpeculativeDecodeConfig)> { - skippy_runtime::test_support::require_native_runtime(); - let model_path = std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_MODEL").ok_or_else(|| { - anyhow::anyhow!("SKIPPY_RECURRENT_CACHE_TEST_MODEL is required for this ignored test") - })?; - let layer_count = - std::env::var_os("SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS").ok_or_else(|| { - anyhow::anyhow!( - "SKIPPY_RECURRENT_CACHE_TEST_MODEL_LAYERS is required for this ignored test" - ) - })?; - let layer_count = layer_count - .to_string_lossy() - .parse::() - .map_err(|error| anyhow::anyhow!("invalid recurrent cache test layer count: {error}"))?; - let config = StageConfig { - run_id: run_id.to_string(), - topology_id: run_id.to_string(), - model_id: std::env::var("SKIPPY_RECURRENT_CACHE_TEST_MODEL_ID") - .unwrap_or_else(|_| "unsloth/Qwen3.5-0.8B-GGUF:Q6_K".to_string()), - package_ref: None, - manifest_sha256: None, - source_model_path: None, - source_model_sha256: None, - source_model_bytes: None, - materialized_path: None, - materialized_pinned: false, - model_path: Some(model_path.to_string_lossy().into_owned()), - projector_path: None, - stage_id: "stage-0".to_string(), - stage_index: 0, - layer_start: 0, - layer_end: layer_count, - ctx_size: u32::try_from(ctx_size) - .map_err(|error| anyhow::anyhow!("invalid recurrent test context size: {error}"))?, - lane_count: 1, - n_batch: Some(batch_size), - n_ubatch: Some(batch_size), - n_gpu_layers: std::env::var("SKIPPY_RECURRENT_CACHE_TEST_GPU_LAYERS") - .ok() - .map(|value| value.parse::()) - .transpose() - .map_err(|error| anyhow::anyhow!("invalid recurrent cache GPU layer count: {error}"))? - .unwrap_or(0), - mmap: Some(true), - mlock: false, - repack: false, - op_offload: None, - no_host_buffer: false, - check_tensors: false, - direct_io: false, - main_gpu: None, - split_mode: skippy_protocol::SplitMode::Auto, - host_expert_layers: None, - cache_type_k: "f16".to_string(), - cache_type_v: "f16".to_string(), - flash_attn_type: Default::default(), - kv_offload: None, - kv_unified: None, - swa_full: None, - cache_idle_slots: None, - resident_tensor_names: Vec::new(), - selected_device: None, - kv_cache: Some(StageKvCacheConfig { - exact_max_bytes: None, - mode: StageKvCacheMode::LookupRecord, - max_entries: 8, - max_bytes: 0, - l2_max_bytes: RECURRENT_TEST_CHECKPOINT_RAM_BYTES, - codec: skippy_protocol::StageKvCacheCodec::Native, - min_tokens: 1, - shared_prefix_stride_tokens: 1, - shared_prefix_record_limit: 0, - }), - native_mtp_enabled: false, - load_mode: LoadMode::RuntimeSlice, - bind_addr: "127.0.0.1:0".to_string(), - upstream: None, - downstream: None, - ..StageConfig::default() - }; - let runtime = load_runtime(&config)? - .ok_or_else(|| anyhow::anyhow!("recurrent cache test runtime was not loaded"))?; - let kv = KvStageIntegration::from_loaded_model( - &config, - crate::runtime_state::loaded_model_state_kind(Some(&runtime)), - crate::runtime_state::loaded_memory_cache_capabilities(Some(&runtime)), - None, - )? - .map(Arc::new) - .ok_or_else(|| anyhow::anyhow!("recurrent cache test did not enable KV integration"))?; - assert!( - kv.records_resident_prefixes(), - "fixture must exercise native prefix ownership" - ); - assert!( - kv.resident_requires_checkpoint(), - "fixture requires recurrent native memory" - ); - assert_eq!( - kv.resident_checkpoint_max_bytes, - RECURRENT_TEST_CHECKPOINT_RAM_BYTES - ); - assert_eq!(kv.resident_config.max_entries, 8); - let telemetry = Telemetry::new(None, 1, config.clone(), TelemetryLevel::Off); - let speculative = SpeculativeDecodeConfig::default(); - let iteration_scheduler = - IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; - let backend = StageOpenAiBackend { - runtime: runtime.clone(), - workload: Default::default(), - config, - telemetry, - model_id: backend_model_id.to_string(), - default_max_tokens, - request_defaults: EmbeddedOpenAiRequestDefaults::default().into(), - thinking: None, - ctx_size, - mode: InferenceBackendMode::LocalRuntime, - draft: None, - speculative_window: 0, - adaptive_speculative_window: false, - ngram_max: 0, - speculative: speculative.clone(), - speculation_governor: None, - runahead_governor: None, - generation_limit: Arc::new(GenerationConcurrencyController::fixed(1)), - generation_queue_depth: Arc::new(AtomicUsize::new(0)), - generation_queue_limit: 1, - generation_admission_timeout: std::time::Duration::from_secs(10), - generation_service_estimator: Arc::new(crate::frontend::GenerationServiceEstimator::new(1)), - generation_session_locks: Arc::new(Mutex::new(std::collections::BTreeMap::new())), - generation_token_budget: Arc::new(GenerationTokenBudget::new(token_budget)), - hook_policy: None, - generation_receipt: None, - generation_lifecycle: None, - linear_proposal_ingress: None, - kv: Some(kv), - iteration_scheduler, - }; - Ok((backend, speculative)) -} - #[test] fn single_prefill_sample_requires_prompt_to_fit_session_batch() { assert!(!prompt_fits_single_prefill_sample(0, 2048)); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index dcbc05dbff..a4a62de004 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -1,7 +1,9 @@ //! A fresh runtime must restore cold-evicted native state from committed L3. use super::*; +use sha2::{Digest, Sha256}; use skippy_cache::{L3CacheManager, StoreLimits}; use skippy_protocol::MessageBase; +use std::fmt::Write as _; use std::{path::Path, time::Instant}; fn backend_with_disk(root: &Path, disk_bytes: u64) -> Result { @@ -53,10 +55,215 @@ fn identity( #[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] fn native_cold_prefix_survives_runtime_restart() -> Result<()> { let root = tempfile::tempdir()?; + let expected = capture_and_commit(root.path())?; + require_restored_prefix(root.path(), &expected) +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn longer_durable_checkpoint_restores_despite_a_short_native_prefix() -> Result<()> { + let root = tempfile::tempdir()?; + let case = checkpoint_preference_case(root.path())?; + let CheckpointPreferenceCase { + backend, + tokens, + attention, + recurrent, + .. + } = case; + let kv = backend.kv.as_ref().unwrap(); + let long = identity(&backend, &tokens); + let mut rt = backend.runtime.lock().unwrap(); + let location = kv + .l3 + .as_ref() + .unwrap() + .locate_longest(&long.namespace, &tokens, 64)? + .unwrap(); + assert_eq!(location.token_count, 64); + let located_desc: skippy_runtime::RuntimeKvPageDesc = + serde_json::from_str(location.kv_desc_json.as_deref().unwrap())?; + located_desc.validate_payload(location.kv_bytes as usize)?; + let candidates = [identity(&backend, &tokens[..16]), long]; + let restored = kv + .restore_exact_state(&mut rt, "target", &candidates)? + .unwrap_or_else(|| { + panic!("a short RAM hit must not hide the longer L3 checkpoint: {location:?}") + }); + assert_eq!(restored.source, "l3"); + assert_eq!(restored.token_count, tokens.len()); + assert_eq!( + rt.export_kv_page("target", 0, tokens.len() as u64)?.payload, + attention + ); + assert_eq!(rt.export_recurrent_state("target")?, recurrent); + Ok(()) +} + +struct CheckpointPreferenceCase { + backend: StageOpenAiBackend, + tokens: Vec, + attention: Vec, + recurrent: Vec, + descriptor: skippy_runtime::RuntimeKvPageDesc, +} + +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn failed_long_l3_import_rolls_back_then_reuses_the_short_native_owner() -> Result<()> { + let root = tempfile::tempdir()?; + let case = checkpoint_preference_case(root.path())?; + let backend = case.backend; + let kv = backend.kv.as_ref().unwrap(); + let long = identity(&backend, &case.tokens); + // Correct attention metadata and bytes force the failure into recurrent import. + kv.l3.as_ref().unwrap().spill( + &long.namespace, + &case.tokens, + &skippy_cache::ExactStatePayload::kv_recurrent(case.attention, vec![0]), + Some(serde_json::to_string(&case.descriptor)?), + None, + )?; + { + let mut rt = backend.runtime.lock().unwrap(); + assert!( + kv.restore_exact_state( + &mut rt, + "bad-import-probe", + &[identity(&backend, &case.tokens[..16]), long.clone()] + ) + .is_err(), + "fixture must reach a native import error, not an early metadata miss" + ); + assert_eq!(rt.session_token_count("bad-import-probe"), Some(0)); + assert_eq!(rt.canonical_session_position("bad-import-probe")?, 0); + rt.drop_session_timed("bad-import-probe")?; + assert!( + rt.canonical_session_position("bad-import-probe").is_err(), + "an absent or discarded lane must not satisfy the clean retry gate" + ); + } + let mut prompt = case.tokens; + prompt.push(11); + let ids = InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some("l3-failure-fallback"), + true, + None, + ); + let sampling = SamplingConfig { + enabled: false, + ..Default::default() + }; + let stats = backend.generate_local_tokens( + LocalGeneration { + prompt_token_ids: &prompt, + recurrent_cache_prefix_token_ids: None, + max_tokens: 1, + sampling: &sampling, + chat_sampling_metadata: None, + speculative: &SpeculativeDecodeConfig::default(), + native_mtp_enabled: false, + hook_request: None, + hook_runtime: None, + cancellation: None, + ids: &ids, + }, + |_| Ok(TokenControl::Continue), + )?; + assert_eq!( + stats.cached_prompt_tokens, 32, + "a failed longer durable restore must not discard the resident fallback" + ); + assert_eq!(kv.radix.lock().unwrap().stats().resident_pinned_tokens, 0); + Ok(()) +} + +fn checkpoint_preference_case(root: &Path) -> Result { + let backend = backend_with_disk(root, 1 << 30)?; + let kv = backend.kv.as_ref().unwrap(); + let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(8); + let long = identity(&backend, &tokens); + let (attention, recurrent, descriptor) = { + let mut rt = backend.runtime.lock().unwrap(); + rt.prefill("long-source", &tokens[..16])?; + let shorter = rt.export_kv_page("long-source", 0, 16)?; + let shorter_recurrent = rt.export_recurrent_state("long-source")?; + kv.l3.as_ref().unwrap().spill( + &long.namespace, + &tokens[..16], + &skippy_cache::ExactStatePayload::kv_recurrent(shorter.payload, shorter_recurrent), + Some(serde_json::to_string(&shorter.desc)?), + None, + )?; + rt.prefill("long-source", &tokens[16..])?; + let page = rt.export_kv_page("long-source", 0, tokens.len() as u64)?; + let attention = page.payload; + let descriptor = page.desc; + let recurrent = rt.export_recurrent_state("long-source")?; + kv.record_resident_prefix(&mut rt, "long-source", &long, &tokens)? + .unwrap(); + rt.drop_session_timed("long-source")?; + rt.ensure_session_active("eviction")?; + assert_eq!( + kv.evict_resident_prefix_for_tokens(&mut rt, "eviction", u64::MAX)? + .evicted_entries, + 1 + ); + rt.drop_session_timed("eviction")?; + (attention, recurrent, descriptor) + }; + let l3 = kv.l3.as_ref().unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + while !l3 + .locate_longest(&long.namespace, &tokens, 64)? + .is_some_and(|location| location.token_count == tokens.len() as u64) + { + anyhow::ensure!( + Instant::now() < deadline, + "long checkpoint was not committed" + ); + thread::sleep(Duration::from_millis(2)); + } + let short = identity(&backend, &tokens[..32]); + let mut rt = backend.runtime.lock().unwrap(); + rt.prefill("short-source", &tokens[..32])?; + kv.record_resident_prefix(&mut rt, "short-source", &short, &tokens[..32])? + .unwrap(); + rt.drop_session_timed("short-source")?; + assert_eq!(kv.probe_resident_prefix(&long).unwrap().token_count, 32); + drop(rt); + Ok(CheckpointPreferenceCase { + backend, + tokens, + attention, + recurrent, + descriptor, + }) +} + +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +struct PrefixReference { + seed_process_id: u32, + attention_sha256: String, + recurrent_sha256: String, + predictions: Vec, +} + +fn digest(bytes: &[u8]) -> String { + let mut text = String::with_capacity(64); + for byte in Sha256::digest(bytes) { + write!(&mut text, "{byte:02x}").unwrap(); + } + text +} + +fn capture_and_commit(root: &Path) -> Result { let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(8); let inputs = [11, 12, 13, 14]; - let (expected_kv, expected_recurrent, expected_output, stored) = { - let backend = backend_with_disk(root.path(), 1 << 30)?; + let reference = { + let backend = backend_with_disk(root, 1 << 30)?; let kv = backend.kv.as_ref().expect("disk cache enabled"); let stored = identity(&backend, &tokens); let (attention, recurrent, output) = { @@ -105,9 +312,21 @@ fn native_cold_prefix_survives_runtime_restart() -> Result<()> { ); thread::sleep(Duration::from_millis(2)); } - (attention, recurrent, output, stored) + PrefixReference { + seed_process_id: std::process::id(), + attention_sha256: digest(&attention), + recurrent_sha256: digest(&recurrent), + predictions: output, + } }; // Drop the model, runtime, cache and joined writer before reopening L3. - let backend = backend_with_disk(root.path(), 1 << 30)?; + Ok(reference) +} + +fn require_restored_prefix(root: &Path, expected: &PrefixReference) -> Result<()> { + let tokens = [1, 2, 3, 4, 5, 6, 7, 8].repeat(8); + let inputs = [11, 12, 13, 14]; + let backend = backend_with_disk(root, 1 << 30)?; + let stored = identity(&backend, &tokens); let kv = backend .kv .as_ref() @@ -122,15 +341,18 @@ fn native_cold_prefix_survives_runtime_restart() -> Result<()> { runtime.canonical_session_position("restarted")?, tokens.len() as u64 ); - assert!( - runtime - .export_kv_page("restarted", 0, tokens.len() as u64)? - .payload - == expected_kv, + assert_eq!( + digest( + &runtime + .export_kv_page("restarted", 0, tokens.len() as u64)? + .payload + ), + expected.attention_sha256, "attention bytes changed after L3 restore" ); - assert!( - runtime.export_recurrent_state("restarted")? == expected_recurrent, + assert_eq!( + digest(&runtime.export_recurrent_state("restarted")?), + expected.recurrent_sha256, "recurrent bytes changed after L3 restore" ); let actual = inputs @@ -138,12 +360,65 @@ fn native_cold_prefix_survives_runtime_restart() -> Result<()> { .map(|&token| runtime.decode("restarted", token)) .collect::>>()?; assert_eq!( - actual, expected_output, + actual, expected.predictions, "fixed-input continuation changed after L3 restore" ); Ok(()) } +/// Invoked twice by the typed validator, which owns separate child processes. +#[test] +#[ignore = "requires the validator's private phase/root and pinned model environment"] +fn native_cold_prefix_process_stage() -> Result<()> { + let root = std::path::PathBuf::from( + std::env::var_os("SKIPPY_L3_TEST_ROOT") + .ok_or_else(|| anyhow::anyhow!("SKIPPY_L3_TEST_ROOT is required"))?, + ); + anyhow::ensure!( + root.is_absolute() && root.is_dir(), + "private L3 test root must exist" + ); + let l3 = root.join("l3"); + let reference = root.join("reference.json"); + match std::env::var("SKIPPY_L3_TEST_PHASE")?.as_str() { + "seed" => { + anyhow::ensure!( + !l3.exists() && !reference.exists(), + "seed requires fresh L3 evidence" + ); + let captured = capture_and_commit(&l3)?; + std::fs::write(reference, serde_json::to_vec(&captured)?)?; + } + "restore" => { + anyhow::ensure!(l3.is_dir(), "persisted L3 directory missing"); + anyhow::ensure!( + std::fs::metadata(&reference)?.len() <= 4096, + "L3 reference exceeds bound" + ); + let expected: PrefixReference = serde_json::from_slice(&std::fs::read(reference)?)?; + anyhow::ensure!( + expected.seed_process_id != std::process::id(), + "L3 restore requires a fresh process" + ); + anyhow::ensure!( + expected.predictions.len() == 4, + "L3 reference lacks continuation predictions" + ); + require_restored_prefix(&l3, &expected)?; + std::fs::write( + root.join("restart-receipt.json"), + serde_json::to_vec(&serde_json::json!({ + "status":"passed", "source":"l3", "seed_process_id":expected.seed_process_id, + "restore_process_id":std::process::id(), "state_integrity":"sha256_exact", + "fixed_input_predictions":expected.predictions + }))?, + )?; + } + _ => bail!("L3 process phase must be seed or restore"), + } + Ok(()) +} + #[test] #[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] fn native_cold_offload_refusal_keeps_inference_usable() -> Result<()> { diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index f1315b7766..af7399838f 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -162,7 +162,7 @@ pub(super) fn recurrent_test_backend_with_lanes( telemetry, model_id: backend_model_id.to_string(), default_max_tokens, - request_defaults: EmbeddedOpenAiRequestDefaults::default(), + request_defaults: EmbeddedOpenAiRequestDefaults::default().into(), thinking: None, ctx_size, mode: InferenceBackendMode::LocalRuntime, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index b35aa2247b..d58c070b41 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -86,7 +86,6 @@ impl StageOpenAiBackend { let scheduler_backend = self.clone(); let scheduler_session_id = session_id.to_string(); let scheduler_ids = request.ids.clone(); - let scheduler_lookup_identities = Arc::clone(&lookup_identities); let scheduler_prefill_tokens = Arc::clone(&prefill_tokens); let record_prefill_tokens = Arc::clone(&prefill_tokens); let mut scheduler_cache_stats = std::mem::take(cache_stats); @@ -94,6 +93,18 @@ impl StageOpenAiBackend { self.generation_admission_timeout, request.prompt_token_ids.len(), ); + // Disk metadata probes must not occupy the iteration worker or runtime. + // Keep the original deadline: time spent here still consumes its budget. + if request + .cancellation + .is_some_and(skippy_inference_api::CancellationToken::is_cancelled) + { + return Err(InferenceError::backend("request cancelled")); + } + let prepared_restore = self + .kv + .as_ref() + .map(|kv| kv.prepare_exact_state_restore(lookup_identities.as_ref(), false)); let outcome = self.iteration_scheduler.execute_cache_aware_runtime_timed( "feature-kv-restore-prefill-record", crate::frontend::iteration_scheduler::cache_runtime::CacheAwareRuntimeRequest { @@ -112,7 +123,7 @@ impl StageOpenAiBackend { &scheduler_ids, &scheduler_session_id, scheduler_prefill_tokens.as_ref(), - scheduler_lookup_identities.as_ref(), + prepared_restore.as_ref(), kv_identity_ms, recurrent_cache_prefix_token_ids.as_deref(), max_tokens, @@ -428,7 +439,7 @@ impl StageOpenAiBackend { ids: &InferenceGenerationIds, session_id: &str, prefill_tokens: &[i32], - lookup_identities: &[PrefillKvIdentity], + prepared_restore: Option<&crate::kv_integration::PreparedExactStateRestore>, kv_identity_ms: f64, recurrent_cache_prefix_token_ids: Option<&[i32]>, max_tokens: u32, @@ -446,7 +457,9 @@ impl StageOpenAiBackend { session_id, ids, prefill_tokens, - lookup_identities, + prepared_restore.ok_or_else(|| { + InferenceError::backend("missing prepared exact-state lookup") + })?, kv_identity_ms, cache_stats, ) diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs index 4ba01698e2..769b028cf2 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs @@ -9,7 +9,7 @@ impl StageOpenAiBackend { session_id: &str, ids: &InferenceGenerationIds, prefill_tokens: &[i32], - identities: &[PrefillKvIdentity], + prepared: &crate::kv_integration::PreparedExactStateRestore, kv_identity_ms: f64, cache_stats: &mut GenerationCacheStats, ) -> (bool, usize, Option) { @@ -21,10 +21,10 @@ impl StageOpenAiBackend { let estimated_cold_prefill_ms = self .generation_service_estimator .estimated_prefill_ms(prefill_tokens.len()); - let exact = kv.restore_exact_state_with_cold_cost( + let exact = kv.restore_prepared_exact_state( runtime, session_id, - identities, + prepared, estimated_cold_prefill_ms, ); let exact = match exact { @@ -119,7 +119,12 @@ impl StageOpenAiBackend { .emit("stage.openai_kv_lookup_decision", attrs); } Ok(None) => { - match kv.restore_resident_prefix(runtime, session_id, identities, prefill_tokens) { + match kv.restore_resident_prefix( + runtime, + session_id, + prepared.identities(), + prefill_tokens, + ) { Ok(Some(restored)) => { restored_prefill = true; cache_stats.status = "hit"; @@ -181,7 +186,7 @@ impl StageOpenAiBackend { ); attrs.insert( "skippy.kv.identity_count".to_string(), - json!(identities.len()), + json!(prepared.identities().len()), ); self.telemetry.emit_debug("stage.openai_kv_timing", attrs); } diff --git a/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs b/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs index 2430fb2a32..8072e3fda5 100644 --- a/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs +++ b/skippy/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs @@ -16,6 +16,7 @@ impl StageOpenAiBackend { } let base = self.local_kv_message_base(session_key, request.ids); let identities = kv.lookup_identities(request.config, &base, 0, prefill_tokens); + let prepared = kv.prepare_exact_state_restore(&identities, true); let mut restore_stats = StageReplyStats::default(); let scheduler_kv = Arc::clone(kv); let scheduler_session_key = session_key.to_string(); @@ -23,11 +24,7 @@ impl StageOpenAiBackend { let local_restore = self.iteration_scheduler.execute_runtime( "embedded-split-prefix-restore", move |runtime| match scheduler_kv - .restore_exact_state_with_shared_durable_fallback( - runtime, - &scheduler_session_key, - &identities, - ) + .restore_prepared_exact_state(runtime, &scheduler_session_key, &prepared, None) .map_err(openai_backend_error)? { Some(restored) => Ok(Some(restored.token_count)), @@ -35,7 +32,7 @@ impl StageOpenAiBackend { .restore_resident_prefix( runtime, &scheduler_session_key, - &identities, + prepared.identities(), &scheduler_prefill_tokens, ) .map_err(openai_backend_error) diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs index f7da8524c8..784960eff9 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal/cache.rs @@ -19,6 +19,7 @@ impl DecisionSequence<'_> { } let base = self.backend.local_kv_message_base(&self.session, self.ids); let identities = kv.lookup_identities(&self.backend.config, &base, 0, tokens); + let prepared = kv.prepare_exact_state_restore(&identities, true); let cache = kv.clone(); let session = self.session.clone(); let token_ids = tokens.to_vec(); @@ -26,17 +27,13 @@ impl DecisionSequence<'_> { "decision-prefix-restore", move |runtime| { if let Some(hit) = cache - .restore_exact_state_with_shared_durable_fallback( - runtime, - &session, - &identities, - ) + .restore_prepared_exact_state(runtime, &session, &prepared, None) .map_err(openai_backend_error)? { return Ok(hit.token_count); } cache - .restore_resident_prefix(runtime, &session, &identities, &token_ids) + .restore_resident_prefix(runtime, &session, prepared.identities(), &token_ids) .map(|hit| hit.map_or(0, |hit| hit.token_count)) .map_err(openai_backend_error) }, diff --git a/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs b/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs index f7d76ae050..30778728cb 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/cache_publication.rs @@ -1,7 +1,6 @@ //! Exact-state cache requests must distinguish queued capture from publication. use super::*; use crate::kv_integration::StagePrefixCachePayload; -use crate::runtime_state::{loaded_memory_cache_capabilities, loaded_model_state_kind}; use skippy_inference_api::chat::ChatCompletionRequest; fn cache_stats(kv: &KvStageIntegration) -> Value { diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index 7ee9399baa..137a420a06 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -16,6 +16,7 @@ const MAX_PREFIX_PROBES: usize = 64; mod resident_preference; use resident_preference::DurableRestoreLookup; +pub(crate) use resident_preference::PreparedExactStateRestore; mod restore; mod snapshot_headroom; @@ -182,14 +183,13 @@ impl KvStageIntegration { &self, runtime: &mut RuntimeState, session_id: &str, - identities: &[PrefillKvIdentity], + prepared: &PreparedExactStateRestore, cold_prefill_cost: Option, - shared_durable_fallback: bool, ) -> Result> { if !self.should_lookup() || self.exact_state_payload().is_none() { return Ok(None); } - for candidate in self.ordered_restore_candidates(identities, shared_durable_fallback) { + for candidate in self.ordered_restore_candidates(prepared) { let identity = candidate.identity; let lookup_started = Instant::now(); let (lookup, entries) = { @@ -209,6 +209,9 @@ impl KvStageIntegration { lookup.as_ref().map(|matched| matched.stored_tokens.len()), ); let Some(lookup) = lookup else { + let Some(location) = candidate.location else { + continue; + }; // The durable tiers may still hold this prefix. // Runs inside the restore transaction, so a failed import // rolls the lane back exactly as a radix restore would. @@ -218,8 +221,7 @@ impl KvStageIntegration { identity, DurableRestoreLookup { started: lookup_started, - location: candidate.location.as_ref(), - shared_fallback: shared_durable_fallback, + location, }, cold_prefill_cost, )? { @@ -698,26 +700,11 @@ impl KvStageIntegration { // load on the located entry's manifest key: same-length queries for // different prefixes never suppress each other, and different-length // queries resolving to one entry never load it twice. - let durable_token_ids = if lookup.shared_fallback { - self.durable_exact_lookup_token_ids(&identity.token_ids) - } else { - &identity.token_ids - }; - let location = if let Some(location) = lookup.location { - location.clone() - } else { - match l3.locate_longest(&identity.namespace, durable_token_ids, MAX_PREFIX_PROBES) { - Ok(Some(location)) => location, - // Nothing stored, or a corrupt / identity-mismatched entry. - // Either way the miss path is the safe one; the tier has - // recorded the reason for the status surface. - Ok(None) | Err(_) => return Ok(None), - } - }; + let location = lookup.location; // L3 remains the authority for L2: locate and validate the current // manifest identity before a host-RAM mirror may serve the request. if let Some(restored) = - self.restore_from_l2(runtime, session_id, identity, &location, lookup.started)? + self.restore_from_l2(runtime, session_id, identity, location, lookup.started)? { return Ok(Some(restored)); } @@ -725,7 +712,7 @@ impl KvStageIntegration { // numerical states. A fill claim must not: one state's fill cannot // warm another state's radix namespace, even when their payload bytes // happen to be identical. - let fill_claim = l3_fill_claim_key(l3, &location); + let fill_claim = l3_fill_claim_key(l3, location); { let mut inflight = self .inflight_fills @@ -741,7 +728,7 @@ impl KvStageIntegration { identity, lookup.started, l3, - &location, + location, cold_prefill_cost, ); // On success the claim travels with the re-warm record and the worker diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs index 7cc38c3da3..7d4fb9a32a 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -3,51 +3,90 @@ use super::*; pub(super) struct RestoreCandidate<'a> { pub(super) identity: &'a PrefillKvIdentity, - pub(super) location: Option, + pub(super) location: Option<&'a skippy_cache::L3Location>, } pub(super) struct DurableRestoreLookup<'a> { pub(super) started: Instant, - pub(super) location: Option<&'a skippy_cache::L3Location>, - pub(super) shared_fallback: bool, + pub(super) location: &'a skippy_cache::L3Location, +} + +/// Durable metadata resolved before entering a scheduled runtime operation. +/// A missing location is a completed lookup, not permission to probe again. +pub(crate) struct PreparedExactStateRestore { + identities: Vec, + locations: Vec>, +} + +impl PreparedExactStateRestore { + /// The exact identity order paired with these completed durable probes. + pub(crate) fn identities(&self) -> &[PrefillKvIdentity] { + &self.identities + } } impl KvStageIntegration { - pub(super) fn ordered_restore_candidates<'a>( + /// Locate durable candidates without holding the scheduler's runtime lock. + /// Resident eligibility is deliberately checked later, during restore. + pub(crate) fn prepare_exact_state_restore( &self, - identities: &'a [PrefillKvIdentity], + identities: &[PrefillKvIdentity], shared_durable_fallback: bool, + ) -> PreparedExactStateRestore { + let locations = identities + .iter() + .map(|identity| { + if !self.should_lookup() || self.exact_state_payload().is_none() { + return None; + } + let l3 = self.l3.as_ref()?; + let tokens = if shared_durable_fallback { + self.durable_exact_lookup_token_ids(&identity.token_ids) + } else { + &identity.token_ids + }; + // Corrupt/unavailable storage remains a cache miss. The + // prepared None must never trigger a retry under runtime lock. + l3.locate_longest(&identity.namespace, tokens, MAX_PREFIX_PROBES) + .ok() + .flatten() + }) + .collect(); + PreparedExactStateRestore { + identities: identities.to_vec(), + locations, + } + } + + pub(super) fn ordered_restore_candidates<'a>( + &self, + prepared: &'a PreparedExactStateRestore, ) -> Vec> { if !self.records_resident_prefixes() { - return identities + return prepared + .identities .iter() - .map(|identity| RestoreCandidate { + .zip(&prepared.locations) + .map(|(identity, location)| RestoreCandidate { identity, - location: None, + location: location.as_ref(), }) .collect(); } - let resident = identities + let resident = prepared + .identities .iter() .filter_map(|identity| self.probe_resident_prefix(identity)) .map(|hit| hit.token_count as u64) .max() .unwrap_or(0); - let Some(l3) = self.l3.as_ref() else { - return Vec::new(); - }; - let mut durable = identities + let mut durable = prepared + .identities .iter() - .filter_map(|identity| { - let tokens = if shared_durable_fallback { - self.durable_exact_lookup_token_ids(&identity.token_ids) - } else { - &identity.token_ids - }; - let location = l3 - .locate_longest(&identity.namespace, tokens, MAX_PREFIX_PROBES) - .ok()??; - preflight_l3_kv_location(&location).ok()?; + .zip(&prepared.locations) + .filter_map(|(identity, location)| { + let location = location.as_ref()?; + preflight_l3_kv_location(location).ok()?; (location.token_count > resident).then_some(( location.token_count, RestoreCandidate { @@ -68,97 +107,5 @@ impl KvStageIntegration { } #[cfg(test)] -mod tests { - use super::*; - use crate::kv_integration::RadixResidentEntry; - use skippy_cache::{L3CacheManager, StoreLimits}; - use skippy_protocol::{MessageBase, StageConfig, StageKvCacheConfig, StageKvCacheMode}; - use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; - - #[test] - fn committed_longer_l3_beats_short_ram_and_equal_ram_keeps_native_ownership() { - let root = tempfile::tempdir().unwrap(); - let manager = L3CacheManager::acquire(root.path(), StoreLimits::new(1 << 20, 0)).unwrap(); - let config = StageConfig { - layer_end: 1, - source_model_sha256: Some("ab".repeat(32)), - kv_cache: Some(StageKvCacheConfig { - mode: StageKvCacheMode::LookupRecord, - min_tokens: 1, - max_entries: 8, - max_bytes: 0, - l2_max_bytes: 1024, - exact_max_bytes: None, - codec: Default::default(), - shared_prefix_stride_tokens: 1, - shared_prefix_record_limit: 0, - }), - ..StageConfig::default() - }; - let kv = KvStageIntegration::from_test_model_with_l3_manager( - &config, - Some(ModelStateKind::Dense), - Some(MemoryCacheCapabilities { - resident: true, - resident_checkpoint: true, - resident_attention: true, - kv_recurrent: true, - full_state: true, - }), - Some(manager), - None, - ) - .unwrap() - .unwrap(); - let base: MessageBase = serde_json::from_value(serde_json::json!({ - "schema_version":1,"run_id":"run","request_id":"request","session_id":"session", - "stage_id":"stage","stage_index":0,"topology_id":"topology" - })) - .unwrap(); - let tokens = [1, 2, 3, 4, 5, 6, 7, 8]; - let identity = kv.prefill_identity(&config, &base, 0, &tokens); - let desc = super::super::tests::native_desc(); - let payload = ExactStatePayload::kv_recurrent(vec![1; 256], vec![2; 16]); - let l3 = kv.l3.as_ref().unwrap(); - l3.spill( - &identity.namespace, - &tokens, - &payload, - Some(serde_json::to_string(&desc).unwrap()), - None, - ) - .unwrap(); - let location = l3 - .locate_longest(&identity.namespace, &tokens, 64) - .unwrap() - .unwrap(); - assert_eq!(location.token_count, 8); - for (count, seq, expected) in [(4, 8, false), (8, 9, true)] { - kv.radix - .lock() - .unwrap() - .insert_resident( - &identity.namespace, - &tokens[..count], - 16, - RadixResidentEntry { - page_id: format!("ram-{count}"), - seq_id: seq, - token_count: count as u64, - recompute_cost: 1, - }, - ) - .unwrap(); - assert_eq!( - kv.ordered_restore_candidates(std::slice::from_ref(&identity), false) - .is_empty(), - expected - ); - } - assert_eq!( - kv.radix.lock().unwrap().stats().resident_entries, - 2, - "metadata selection must not evict the resident fallback" - ); - } -} +#[path = "resident_preference/tests.rs"] +mod tests; diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs new file mode 100644 index 0000000000..ed0886161a --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs @@ -0,0 +1,237 @@ +use super::*; +use crate::kv_integration::RadixResidentEntry; +use skippy_cache::{L3CacheManager, StoreLimits}; +use skippy_protocol::{MessageBase, StageConfig, StageKvCacheConfig, StageKvCacheMode}; +use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; +use std::path::Path; +#[cfg(unix)] +use { + crate::frontend::iteration_scheduler::IterationScheduler, + crate::telemetry::{Telemetry, TelemetryLevel}, + std::{sync::Mutex, time::Duration}, +}; + +fn fixture(root: &Path) -> (KvStageIntegration, PrefillKvIdentity) { + let manager = L3CacheManager::acquire(root, StoreLimits::new(1 << 20, 0)).unwrap(); + let config = StageConfig { + layer_end: 1, + source_model_sha256: Some("ab".repeat(32)), + kv_cache: Some(StageKvCacheConfig { + mode: StageKvCacheMode::LookupRecord, + min_tokens: 1, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 1024, + exact_max_bytes: None, + codec: Default::default(), + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + }), + ..StageConfig::default() + }; + let kv = KvStageIntegration::from_test_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_checkpoint: true, + resident_attention: true, + kv_recurrent: true, + full_state: true, + }), + Some(manager), + None, + ) + .unwrap() + .unwrap(); + let base: MessageBase = serde_json::from_value(serde_json::json!({ + "schema_version":1,"run_id":"run","request_id":"request","session_id":"session", + "stage_id":"stage","stage_index":0,"topology_id":"topology" + })) + .unwrap(); + let identity = kv.prefill_identity(&config, &base, 0, &[1, 2, 3, 4, 5, 6, 7, 8]); + (kv, identity) +} + +fn spill(kv: &KvStageIntegration, identity: &PrefillKvIdentity) { + let desc = super::super::tests::native_desc(); + kv.l3 + .as_ref() + .unwrap() + .spill( + &identity.namespace, + &identity.token_ids, + &ExactStatePayload::kv_recurrent(vec![1; 256], vec![2; 16]), + Some(serde_json::to_string(&desc).unwrap()), + None, + ) + .unwrap(); +} + +fn resident(kv: &KvStageIntegration, identity: &PrefillKvIdentity, count: usize, seq: i32) { + kv.radix + .lock() + .unwrap() + .insert_resident( + &identity.namespace, + &identity.token_ids[..count], + 16, + RadixResidentEntry { + page_id: format!("ram-{count}"), + seq_id: seq, + token_count: count as u64, + recompute_cost: 1, + }, + ) + .unwrap(); +} + +#[test] +fn committed_longer_l3_beats_short_ram_and_equal_ram_keeps_native_ownership() { + let root = tempfile::tempdir().unwrap(); + let (kv, identity) = fixture(root.path()); + spill(&kv, &identity); + let prepared = kv.prepare_exact_state_restore(std::slice::from_ref(&identity), false); + for (count, seq, expected_empty) in [(4, 8, false), (8, 9, true)] { + resident(&kv, &identity, count, seq); + assert_eq!( + kv.ordered_restore_candidates(&prepared).is_empty(), + expected_empty + ); + } + assert_eq!( + kv.radix.lock().unwrap().stats().resident_entries, + 2, + "metadata selection must not evict the resident fallback" + ); +} + +#[test] +fn prepared_miss_does_not_probe_a_newly_committed_disk_entry_under_runtime_lock() { + let root = tempfile::tempdir().unwrap(); + let (mut kv, identity) = fixture(root.path()); + // Exercise the radix-miss fallback too, not only resident preference. + kv.payload = StagePrefixCachePayload::KvRecurrent; + let prepared = kv.prepare_exact_state_restore(std::slice::from_ref(&identity), false); + assert!(prepared.locations[0].is_none()); + spill(&kv, &identity); + let mut runtime = RuntimeState::new_modelless_for_test(1); + assert!( + kv.restore_prepared_exact_state(&mut runtime, "target", &prepared, None) + .unwrap() + .is_none(), + "the completed miss must not discover/import the new disk entry" + ); + assert_eq!(runtime.active_session_count(), 0); +} + +#[cfg(unix)] +fn scheduler() -> IterationScheduler { + let config = StageConfig::default(); + let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(1))); + let telemetry = Telemetry::new(None, 1, config.clone(), TelemetryLevel::Off); + IterationScheduler::new(runtime, &config, 8, true, None, telemetry).unwrap() +} + +#[cfg(unix)] +fn paused_prefix_link(root: &Path) -> (std::path::PathBuf, Vec) { + use std::os::unix::ffi::OsStrExt; + let namespace = std::fs::read_dir(root.join("prefixes")) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let path = std::fs::read_dir(namespace) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let bytes = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: c_path is a valid NUL-terminated path in this test's private directory. + assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); + (path, bytes) +} + +#[cfg(unix)] +fn wait_for_lookup_reader(path: &Path) -> std::fs::File { + use std::os::unix::fs::OpenOptionsExt; + let deadline = Instant::now() + Duration::from_secs(30); + loop { + match std::fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(path) + { + Ok(writer) => return writer, + Err(error) if error.raw_os_error() == Some(libc::ENXIO) => { + assert!( + Instant::now() < deadline, + "lookup never opened its disk prefix link" + ); + std::thread::yield_now(); + } + Err(error) => panic!("open paused prefix link: {error}"), + } + } +} + +#[test] +#[cfg(unix)] +fn stalled_disk_lookup_allows_unrelated_runtime_work_and_rechecks_growing_resident() { + use std::{io::Write as _, sync::mpsc, thread}; + let root = tempfile::tempdir().unwrap(); + let (kv, identity) = fixture(root.path()); + spill(&kv, &identity); + resident(&kv, &identity, 4, 8); + let (path, bytes) = paused_prefix_link(root.path()); + let kv = Arc::new(kv); + let request_kv = Arc::clone(&kv); + let request_identity = identity.clone(); + let scheduler = scheduler(); + let request_scheduler = scheduler.clone(); + let lookup = thread::spawn(move || { + let prepared = request_kv.prepare_exact_state_restore(&[request_identity], false); + request_scheduler.execute_runtime("restore-after-disk-lookup", move |runtime| { + let restored = request_kv + .restore_prepared_exact_state(runtime, "target", &prepared, None) + .map_err(|error| { + skippy_inference_api::InferenceError::backend(error.to_string()) + })?; + Ok((prepared, restored.is_none())) + }) + }); + // Writer-open succeeds only after locate_longest opens the actual FIFO. + // Keep it empty: the real fs::read remains blocked, not a simulated sleep. + let mut writer = wait_for_lookup_reader(&path); + let (progress_tx, progress_rx) = mpsc::channel(); + let progress = thread::spawn(move || { + let result = scheduler.execute_runtime("unrelated-during-disk-lookup", |runtime| { + Ok(runtime.active_session_count()) + }); + progress_tx.send(result).unwrap(); + }); + let completed = progress_rx.recv_timeout(Duration::from_secs(30)); + resident(&kv, &identity, 8, 9); + writer.write_all(&bytes).unwrap(); + drop(writer); // Release the disk reader even when the progress assertion fails. + let (prepared, resident_won) = lookup.join().unwrap().unwrap(); + progress.join().unwrap(); + assert_eq!( + completed.unwrap().unwrap(), + 0, + "unrelated scheduler work must complete before disk lookup resumes" + ); + assert!( + kv.ordered_restore_candidates(&prepared).is_empty(), + "the now-equal resident prefix must beat the earlier durable metadata" + ); + assert!( + resident_won, + "the scheduled transaction must leave the native fallback intact" + ); + assert_eq!(kv.radix.lock().unwrap().stats().resident_entries, 2); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/restore.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/restore.rs index 3a7f552a25..d69067c3e3 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/restore.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/restore.rs @@ -2,6 +2,8 @@ use super::*; impl KvStageIntegration { + /// Synchronously locate and restore an exact prefix. Scheduled callers use + /// prepared metadata so this lookup does not hold the shared runtime lock. pub fn restore_exact_state( &self, runtime: &mut RuntimeState, @@ -11,33 +13,29 @@ impl KvStageIntegration { self.restore_exact_state_with_cold_cost(runtime, session_id, identities, None) } - /// Constrain a cold L3 fallback to the checkpoint shared by every stage. - pub(crate) fn restore_exact_state_with_shared_durable_fallback( + /// Restore an exact prefix, using the estimated cold cost for L3 admission. + pub fn restore_exact_state_with_cold_cost( &self, runtime: &mut RuntimeState, session_id: &str, identities: &[PrefillKvIdentity], + cold_prefill_cost: Option, ) -> Result> { - runtime.restore_transaction(session_id, |runtime| { - self.restore_exact_state_inner(runtime, session_id, identities, None, true) - }) + let prepared = self.prepare_exact_state_restore(identities, false); + self.restore_prepared_exact_state(runtime, session_id, &prepared, cold_prefill_cost) } - pub fn restore_exact_state_with_cold_cost( + /// Recheck resident preference and import prepared durable metadata within + /// the existing rollback transaction; never repeat a completed disk lookup. + pub(crate) fn restore_prepared_exact_state( &self, runtime: &mut RuntimeState, session_id: &str, - identities: &[PrefillKvIdentity], + prepared: &PreparedExactStateRestore, cold_prefill_cost: Option, ) -> Result> { runtime.restore_transaction(session_id, |runtime| { - self.restore_exact_state_inner( - runtime, - session_id, - identities, - cold_prefill_cost, - false, - ) + self.restore_exact_state_inner(runtime, session_id, prepared, cold_prefill_cost) }) } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index ac0ce819f4..67cdb0bf57 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -30,6 +30,7 @@ mod exact_state; pub(crate) mod scheduling; mod snapshot_validation; pub(crate) use exact_state::CaptureAdmission; +pub(crate) use exact_state::PreparedExactStateRestore; mod identity; mod l2_serving; pub mod lifecycle; diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index e492cdf0ff..d121c27b32 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -17,9 +17,11 @@ use skippy_runtime::{ WorkloadInfo, parse_cache_type, }; +mod context_capacity; mod expert_placement; mod frame_operations; pub(crate) use frame_operations::slice_activation_frame; +pub(crate) mod lane_admission; mod lane_lifecycle; pub mod lifecycle; pub(crate) mod model_content; diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs index f8accb87c1..c785c78248 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -6,6 +6,7 @@ use std::{ fs::{File, Metadata}, io::{BufReader, Read}, path::{Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, time::{Instant, SystemTime}, }; @@ -55,7 +56,9 @@ impl VerifiedModelContent { ) -> Result<(T, Option)> { #[cfg(unix)] let (model, content) = match Self::observe_files(config).ok().flatten() { - Some(files) => verify_alongside_load(load, || Self::from_observed(files))?, + Some(files) => { + verify_alongside_load(load, |cancelled| Self::from_observed(files, cancelled))? + } None => (load()?, None), }; #[cfg(not(unix))] @@ -69,7 +72,7 @@ impl VerifiedModelContent { #[cfg(any(not(unix), test))] pub(crate) fn observe(config: &StageConfig) -> Result> { Self::observe_files(config)? - .map(Self::from_observed) + .map(|files| Self::from_observed(files, &AtomicBool::new(false))) .transpose() } @@ -86,10 +89,10 @@ impl VerifiedModelContent { #[cfg(any(not(unix), test))] fn from_files(files: Vec<(String, PathBuf)>) -> Result { - Self::from_observed(capture_files(files)?) + Self::from_observed(capture_files(files)?, &AtomicBool::new(false)) } - fn from_observed(files: ObservedFiles) -> Result { + fn from_observed(files: ObservedFiles, cancelled: &AtomicBool) -> Result { let started = Instant::now(); let mut verified_bytes = 0_u64; let mut digest = Sha256::new(); @@ -97,6 +100,10 @@ impl VerifiedModelContent { let mut observed = Vec::with_capacity(files.len()); let mut buffer = vec![0; 1024 * 1024]; for (name, path, stamp) in files { + ensure!( + !cancelled.load(Ordering::Acquire), + "model content verification cancelled" + ); let file = File::open(&path) .with_context(|| format!("open model content {}", path.display()))?; let before = file.metadata()?; @@ -112,14 +119,12 @@ impl VerifiedModelContent { digest.update(name.as_bytes()); digest.update(stamp.bytes.to_le_bytes()); let mut reader = BufReader::new(file); - loop { - let count = reader.read(&mut buffer)?; - if count == 0 { - break; - } - digest.update(&buffer[..count]); - verified_bytes = verified_bytes.saturating_add(count as u64); - } + verified_bytes = verified_bytes.saturating_add(hash_content( + &mut reader, + &mut digest, + &mut buffer, + cancelled, + )?); ensure!( FileStamp::read(&reader.get_ref().metadata()?) == stamp, "model content changed during verification" @@ -184,6 +189,28 @@ impl VerifiedModelContent { } } +/// Hash bounded chunks, abandoning further input reads after a failed model open. +fn hash_content( + reader: &mut impl Read, + digest: &mut Sha256, + buffer: &mut [u8], + cancelled: &AtomicBool, +) -> Result { + let mut bytes = 0_u64; + loop { + ensure!( + !cancelled.load(Ordering::Acquire), + "model content verification cancelled" + ); + let count = reader.read(buffer)?; + if count == 0 { + return Ok(bytes); + } + digest.update(&buffer[..count]); + bytes = bytes.saturating_add(count as u64); + } +} + fn capture_files(files: Vec<(String, PathBuf)>) -> Result { files .into_iter() @@ -201,14 +228,18 @@ fn capture_files(files: Vec<(String, PathBuf)>) -> Result { #[cfg(unix)] fn verify_alongside_load( load: impl FnOnce() -> Result, - verify: impl FnOnce() -> Result + Send, + verify: impl FnOnce(&AtomicBool) -> Result + Send, ) -> Result<(T, Option)> { + let cancelled = AtomicBool::new(false); std::thread::scope(|scope| { let verification = std::thread::Builder::new() .name("skippy-model-content".into()) - .spawn_scoped(scope, verify) + .spawn_scoped(scope, || verify(&cancelled)) .ok(); let model = load(); + if model.is_err() { + cancelled.store(true, Ordering::Release); + } let content = verification .and_then(|verification| verification.join().ok()) .and_then(Result::ok); @@ -293,6 +324,71 @@ fn checkpoint_files(root: &Path) -> Result> { mod tests { use super::*; + #[cfg(unix)] + #[test] + fn failed_model_open_cancels_verification_before_joining() { + use std::{sync::mpsc, time::Duration}; + let (started, observed_start) = mpsc::channel(); + let (cancellation, observed_cancellation) = mpsc::channel(); + let error = verify_alongside_load( + || -> Result<()> { + observed_start.recv_timeout(Duration::from_secs(5))?; + anyhow::bail!("native model load failed") + }, + move |cancelled| { + started.send(())?; + let deadline = Instant::now() + Duration::from_secs(5); + while !cancelled.load(Ordering::Acquire) && Instant::now() < deadline { + std::thread::yield_now(); + } + cancellation.send(cancelled.load(Ordering::Acquire))?; + anyhow::bail!("verification abandoned") + }, + ) + .err() + .expect("failed load must stay an error"); + assert!(observed_cancellation.recv().unwrap()); + assert_eq!(error.to_string(), "native model load failed"); + } + + #[test] + fn cancelled_verification_stops_before_the_next_chunk() { + struct CancelAfterRead<'a> { + cancelled: &'a AtomicBool, + reads: usize, + } + impl Read for CancelAfterRead<'_> { + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { + self.reads += 1; + if self.reads > 1 { + return Ok(0); + } + buffer.fill(7); + self.cancelled.store(true, Ordering::Release); + Ok(buffer.len()) + } + } + let cancelled = AtomicBool::new(false); + let mut reader = CancelAfterRead { + cancelled: &cancelled, + reads: 0, + }; + let error = + hash_content(&mut reader, &mut Sha256::new(), &mut [0; 16], &cancelled).unwrap_err(); + assert_eq!(reader.reads, 1); + assert!(error.to_string().contains("verification cancelled")); + } + + #[cfg(unix)] + #[test] + fn verification_failure_does_not_fail_a_successful_model_open() { + let (model, proof) = + verify_alongside_load(|| Ok("loaded"), |_| anyhow::bail!("content unavailable")) + .unwrap(); + assert_eq!(model, "loaded"); + assert!(proof.is_none()); + } + #[cfg(unix)] #[test] fn model_open_and_content_verification_progress_concurrently() { @@ -305,9 +401,10 @@ mod tests { opened.send(())?; Ok("loaded") }, - move || { + move |cancelled| { started.send(())?; observed_open.recv_timeout(Duration::from_secs(5))?; + assert!(!cancelled.load(Ordering::Acquire)); Ok(VerifiedModelContent { digest: "proof".into(), files: Vec::new(), diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md index 2bbe8b5299..d183db3fa8 100644 --- a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -1,6 +1,213 @@ # Indexed KV attention: review candidate -Status on 2026-10-31: implementation available for review. All eight real-model +## Current candidate: upstream per-owner row lists + +The working candidate replaces the custom indexed operator with the per-owner +row-list and ownership-bitmap implementation from upstream PR29510, based on +`006fc936d1dcb8077c0bccfad31c72ee453960e8`. It stays on the existing upstream pin. +CPU, CUDA and Metal use `ggml_flash_attn_ext_rows` with one I32 row list per +query stream and the existing attention mask. Runtime admission probes the +actual assigned backend and stored KV representation; unsupported row layouts +retain ordinary attention on that backend. Model names do not select a path. +Radix ownership, recurrent checkpoints and persistent L3 remain separate. + +The [layout-matched full-model control](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/9562cd5443cd4bd78573dcf0eb61ca38) +passes all 23 mandatory comparisons byte-for-byte at the unchanged `1e-6` +bound for the fixed Qwen3.5-35B/F16 fixture. Vanilla kernels independently +reproduce the full PR's logits, saved states and restored continuations when +given the matching attention layout. This is a diagnostic intervention, not +untouched vanilla or universal model qualification. The original cross-layout +failure and two optional ordinary-restore failures remain recorded. + +CPU validation passes 2,452 finite operator comparisons, 36 exceptional controls +and 294 native tests; one GPU-only test is explicitly skipped. Initial M1 +validation passed bitmap/codec checks and 1,318 finite comparisons before the +unchanged operator bound failed at F16 head width 40. The inherited row-gather +copy loop omitted entries at head boundaries for widths 40 and 72. The generic +repair assigns copy chunks within each head, preserving the original mapping +for aligned heads. The repaired M1 diagnostic passes the complete unchanged +operator program and F16/Q8/F32 resident-model gates. Actual loaded-library +hashes match the sealed provider. F16 and Q8 use row nodes; stored F32 retains +ordinary attention with F16 attention inputs on Metal. The diagnostic reuses +unchanged host objects and replaces the Metal auxiliary shader; it is not the +shipping runtime. The subsequent production builds are attributed separately +below. + +The final candidate also wires row inputs through both the full-attention and +sliding-window cache pools. Both ordinary and hybrid graph reuse refresh the +current pool inputs; each layer uses its existing window metadata. The new CPU +fixture exercises the actual two-pool graph, shared owners, reordered query +streams and graph reuse. It passes alongside the existing graph-input tests. +No model-family rule, new setting, kernel arithmetic change or CPU fallback was +added. Clean replay of all 104 patches produces native `aec61426350541d9f6c4762ef4ca1850e4f34f49`, +tree `22cbb3144e2926b15ab850016d6fce5eb40d2ceb`, queue digest +`11701d0ac354c8d240d4813e5ff60b83d07d4f9a2daecde45ebe8ccd6ef3f18f`. + +The preceding `cc855ab2` candidate completed the early serving pairs below. +Every arm completed 69 requests and 18,713 output tokens with clean client and +server exits. These are single ordered diagnostics, not ABBAAB qualification, +generated-content parity or results for the final two-pool candidate. + +| Backend / model at c4 | Skippy output tok/s | Standard llama output tok/s | Difference | +|---|---:|---:|---:| +| [CUDA / hybrid dense 4B](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/da26189089e5493f9dbb5a59e8ce3c57) | 26.476 | 26.654 | -0.67% | +| [CUDA / hybrid MoE 35B](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/30aa91d8233f4a599d8436f4673fa446) | 24.971 | 25.056 | -0.34% | +| [CUDA / attention MoE 30B](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/7ae025fc9ac741758d0b0c9e604e2796) | 15.782 | 13.705 | +15.16% | +| [M3 Metal / hybrid dense 4B](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/33bc478fecf44f3bbe8e5861610b4f99) | 26.613 | 26.228 | +1.47% | + +Metal TTFT p95 remains worse in that pair (74.58 versus 29.81 seconds). The +dense CUDA pair failed in the benchmark client after its exact HTTP cache +gate passed; no partial throughput is qualified. Its failed attempt remains +retained. The original Gemma ordinary-attention resident failure reproduces +with the old `00983cf4` runtime at the same observed deltas; neither failure is +waived. The final candidate's actual two-pool GPU tests are separate evidence. + +The [owning Metal runtime's targeted M1 gates](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/fe742c2cf8944ef69e0fdce624475938) +pass all five native/admission tests with clean postchecks. Gemma F16 and Q8 +each execute 13 full-attention and 13 sliding-window row nodes on MTL0; +resident fork logits have zero differences and both page comparisons are exact. +Dense F16/Q8 execute 36 row nodes, while stored F32 preserves the selected Metal +ordinary-attention conversion. These tests retain the original `1e-6` limit. + +The [final CUDA runtime gates](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/accb9ce48b87441888fc1f4fb100a99f) +pass the operator catalog, six resident storage pairs, exact four-lane/32-step +checkpoint continuation and fresh-process L3 restore. The producer reused +unchanged CUDA kernel objects and rebuilt the changed graph consumers; all 19 +numeric exits and 59 artifact hashes pass audit. + +The [final CUDA Gemma F16/Q8 gates](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/a459675abb7240088b65f2892d0c663c) +execute all 26 attention layers through row nodes, with zero fork-logit +differences and exact restored pages. The [final dense CUDA gates](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/602d580a52b443c79acd38c920766a80) +also pass F16, Q8 and mixed Q8/F16 with all 36 row nodes and the same unchanged +resident bound. These actual-model checks are distinct from the CPU two-pool +graph fixture and do not relabel the older ordinary-attention failures. + +Remaining qualification uses one frozen final runtime per backend, all four +models and c1/c2/c4 in ABBAAB order. Audit complete work, source/model/runtime/ +client identities, lifecycle, latency, cache reads and sampled memory before +publishing performance through the typed owner into existing MLflow experiment +6. Historical campaigns and failed attempts keep their original attribution. + +The preceding candidate's cold replay produced native +`cc855ab2f443f77626ebf0f4901610dea737fd14`, tree +`7ff0e7d6b92bf3145b08dd8492b174d2c1bf7ee0`, queue +`a3628a88bae20819756d22e1fc2a68781de2cedae711ed9b08590e7cd9a3a116`. +The Skippy ABI remains 0.1.76; this GGML constructor change adds no Rust ABI +symbol. All performance evidence below remains attributed to its original +source and does not qualify this candidate. + +## Preceding repair: retain ordinary attention execution + +The automatic indexed graph is being withheld because it fails the unchanged +full-model baseline arithmetic contract. This also happens without saved cache +owners or checkpoint imports: fresh base/head controls have exact same-source +repeats, but cross-source maximum logit deltas are `0.223699808` at c1 and +`0.857750654` at c4, with zero and three greedy differences respectively. +These failures remain recorded; operator accuracy tests do not waive them. + +The conservative native repair candidate is `00983cf474939f13c2d8a151efe7355518642906`, +tree `e709f20cf29ae4df087e4d20719fec5e267b554d`, queue +`72b73c5eaf35a818d8b38043f41955565e4786eca998e4209456951bf00b38db`. +It declines automatic indexed read plans at the common graph-admission point, +consistently during construction and reuse. Ordinary attention retains its +existing query layout, physical key extent and backend selection. This is not +a CPU fallback, model exception, new configuration switch or tolerance change. +The public indexed GGML operator remains independently available and tested. +Default-model fixtures explicitly require absent index inputs and the selected +backend; stored KV types and attention-input types are reported separately. + +The preceding ordinary-graph candidate `4c133af3` matched the retained CUDA c4 +canonical and fresh-context baseline exactly, but still differed at c1. +Graph-disabled controls reproduced the same c1 difference. Nsight found 234 +registers and six VEC partial reductions in the baseline versus 150 registers +and nine partials in the modified kernel. The occupancy-based launcher changed +the partitioning without a selector change. This repair therefore preserves +the original ordinary VEC body separately from indexed row loading. Selection +depends only on the presence of index inputs; register and grid counts are not +hardcoded. Source-matched CUDA builds now pass the unchanged fresh c1/c4 +baseline comparisons: all six repeat/cross comparisons have maximum logit +delta zero and no greedy differences (`job_mkz3w1kj6zqmpy5`). The retained +canonical c4 replay also passes all four comparisons exactly +(`job_wjm2d0ge3h65req`). Actual Nsight launches restore 234 registers/thread, +grid 1x6x16, block 32x4 and 16,640 shared bytes across all 256 observed VEC +decode launches (`job_vs97wb6qvq6z4fz`). All 51 downloaded artifacts across +these three controls passed independent size and SHA-256 verification. + +Strict cross-placement resident continuation remains a separate open contract. +The actual Qwen3.5-4B CUDA fixture fails identically on retained ordinary `f71` +and candidate `4c133af3`; saved prefix and cold-export bytes pass, but computed +continuation logits and KV pages differ. Extra Llama-1B Metal tests also fail +the unchanged strict continuation comparison. A separate public-API control +against true unpatched llama.cpp reproduces the same F16 continuation deltas +on Metal; full trace comparison remains separate from equal delta summaries. +These failures remain recorded, rather +than being hidden by passing operator tests or output-count hashes. + +Resident radix ownership, recurrent checkpoints, persistent L3, cooperative +hybrid scheduling and longest RAM/L3 prefix selection remain independent. +Restoring the ordinary graph also restores its physical-pool scaling cost. +The historical idle-prefix scaling improvements below therefore do not describe +this repair candidate. Exact numerical, mixed-KV, additional-model and AgentX +qualification of the repaired default path remains incomplete. The local Just +CLI/native package build passes at this exact native identity. A separate +true-vanilla Gemma2 Metal control crosses its 4,096-token sliding window with +a 6,144-token prefix and softcap 50: all six c1/c4 repeat/cross full-vocabulary +comparisons are exact, with all 26 attention layers on the selected GPU. +This is additional-model correctness evidence, not performance qualification. +ABI remains 0.1.76. + +## One-lane resident-cache correction + +Default native and MTP contexts now select unified KV even at one lane. +Previously, dense one-lane contexts selected non-unified KV while advertising +resident caching; native prefix saves then returned unsupported and repeated +HTTP requests reused zero tokens. Explicit non-unified attention contexts now +omit the resident capability flags that their save API cannot honor. + +Native `11aa69c53e118958f3dc0ab0870f89f3d24d7897`, tree +`b085f1e7672c73be8ec821c84bdad7401600fe91`, queue digest +`0378e014f6c267fd03b078a285dff03fb25f42502e3fbed8907926010296299f` +replays cleanly. The expanded dense resident fixture passes on CPU and Metal: +default one-lane save, source release, byte-exact restore and next logits; +explicit non-unified one- and two-lane contexts report no resident support and +reject saves. CUDA and actual dense-model HTTP reuse are pending on this fix. +ABI 0.1.76 and the attention kernels are unchanged. + +## Historical combined candidate with indexed vector decode + +The earlier combined candidate integrated Jared Wyles's `18f0fa7a49142344c9297cfcbaf9a16352352189`. +For eligible indexed CUDA queries of at most two tokens, F16/BF16 KV can now +use the existing vector kernel; larger prefill and verification windows retain +their existing selection. The owning patch was regenerated to correct stale +mail-patch hunk counts after the guard removal. The combined candidate also +checks compiled CUDA softcap capabilities: unsupported V widths are refused; +supported wide shapes without an MMA softcap variant use the existing tile +kernel. D64 softcapping remains explicitly unsupported on CUDA and cannot count +as GPU qualification through CPU fallback. + +Clean queue replay produces native `9e5ce4cd088fd30193702e7cb176857ef3f47dee`, +tree `bc57c588724ca8cfedb714ea357a5f3370b6068a`, queue digest +`ef74e663109626492be260e879ac0492b71a3963dab035d54d3e8b430eec0297`. +Expanded operator cases cover Q2, mixed F16/BF16, no-mask/no-sink execution, +softcap eligibility and four alternating metadata phases spanning graph replay. + +CUDA correctness and performance qualification for this combined source are +recorded separately from the one-lane fix above. Source `382c6c62a` passes the +CUDA operator, real-model cache/L3, fresh-process and all-eight-layer FP64 +gates; actual F16 attention uses the vector kernel. Its complete same-host c4 +pair measures 26.805 Skippy versus 26.577 standard llama output tokens/s, +69 requests and 18,713 outputs per arm with zero errors. This single pair is +interim evidence, not a complete ABBAAB group. Its verified metrics and artifacts +are in [the existing MLflow experiment](https://mlflow.internal.generalinference.xyz/mlflow/#/experiments/6/runs/90be7573cb6c49fcb3cdc7032861f656). +The older measurements below remain attributed to their original source; +they do not qualify the new dispatch. The full four-model c1/c2/c4 ABBAAB sweep +will record a new campaign within the existing MLflow experiment +`agentx-skippy-vs-llama` (ID 6), preserving historical runs. + +## Prior-source qualification (`1b3f2e6fc36d`) + +The following results qualify the preceding source, before Jared's vector +selection change. All eight real-model attention layers match existing dense CUDA attention exactly at the same logical layout. Strict cache tests pass on CUDA and Metal. Comparison against the old physical layout still fails; that diagnostic is retained below. The final CUDA diff --git a/skippy/evals/kv-validation/README.md b/skippy/evals/kv-validation/README.md index 689ba3ba5d..0c1f59e8a9 100644 --- a/skippy/evals/kv-validation/README.md +++ b/skippy/evals/kv-validation/README.md @@ -26,12 +26,16 @@ This foundation runs: releasing its source lane, followed by model/runtime/cache reload against the same L3 directory. Require an actual L3 hit, identical attention and recurrent payload bytes, and four matching fixed-input continuation predictions. This - runs in one test process and does not qualify fresh-process server restart. + first runs within one test process. The validator additionally invokes two + separate supervised test processes: seed commits and exits before restore + starts. Distinct PIDs, an L3 hit, complete attention/recurrent SHA-256 equality + and four matching predictions are required. This qualifies the bounded native + process boundary, not an HTTP-server restart or long-prefix workload. A second model test refuses L3 writes with a one-byte disk budget, requires native attention cells to be released, and verifies exact cold-recompute predictions before checking that no durable entry was published. -Long c4 state comparisons, L3 restart, pressure, default-budget qualification and +Long c4 state comparisons, HTTP-server L3 restart, pressure, default-budget qualification and standard-vanilla performance comparisons remain separate work in [todo.md](../../../todo.md). A green foundation is not throughput parity or full KV certification. There is no automatic GPU CI trigger or new serving option. diff --git a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch index 76e684da11..870fe4cb9a 100644 --- a/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch +++ b/skippy/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch @@ -1055,7 +1055,7 @@ index 000000000..5d77f4804 +#endif // SKIPPY_MODEL_SOURCE_H diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h new file mode 100644 -index 000000000..b47c55f82 +index 000000000..799bdca2d --- /dev/null +++ b/include/skippy/runtime.h @@ -0,0 +1,277 @@ @@ -1157,7 +1157,7 @@ index 000000000..b47c55f82 + // Tri-state KV/session controls resolved from `model_fit` config. + /** @brief Whether K/V tensors are offloaded to the compute backend (mirrors upstream `offload_kqv`). */ + int32_t kv_offload; -+ /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO enables unified caching at every lane count. Explicit false selects non-unified caching, except recurrent and hybrid models force it true. */ ++ /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO derives the setting from lane count; recurrent and hybrid models force it true. */ + int32_t kv_unified; + /** @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`). */ + int32_t swa_full; @@ -1818,10 +1818,10 @@ index 000000000..7ffe65277 +#endif // SKIPPY_STAGE_PLAN_H diff --git a/include/skippy/state.h b/include/skippy/state.h new file mode 100644 -index 000000000..0fe373d78 +index 000000000..1cfaaa5c6 --- /dev/null +++ b/include/skippy/state.h -@@ -0,0 +1,274 @@ +@@ -0,0 +1,236 @@ +#ifndef SKIPPY_STATE_H +#define SKIPPY_STATE_H + @@ -1841,10 +1841,6 @@ index 000000000..0fe373d78 + SKIPPY_MEMORY_CACHE_RESIDENT = 1 << 0, + SKIPPY_MEMORY_CACHE_KV_RECURRENT = 1 << 1, + SKIPPY_MEMORY_CACHE_FULL_STATE = 1 << 2, -+ /** Resident prefixes restore only their exact saved recurrent checkpoint boundary. */ -+ SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT = 1 << 3, -+ /** Complete resident prefixes contain attention cells in addition to any recurrent state. */ -+ SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION = 1 << 4, +}; + +/** @brief Returns complete cache representations admitted by the built graph and loaded memory. @@ -1964,7 +1960,7 @@ index 000000000..0fe373d78 + size_t * out_bytes, + struct skippy_error ** out_error); + -+/** @brief Exports only recurrent memory; attention pages are exported independently. */ ++/** @brief Exports recurrent state for models that maintain recurrent memory. */ +LLAMA_API enum skippy_status skippy_export_recurrent_state( + struct skippy_session * session, + void * output, @@ -1981,7 +1977,7 @@ index 000000000..0fe373d78 + size_t input_bytes, + struct skippy_error ** out_error); + -+/** @brief Imports recurrent-only state into a session. */ ++/** @brief Imports recurrent state into a session. */ +LLAMA_API enum skippy_status skippy_import_recurrent_state( + struct skippy_session * session, + const void * input, @@ -2030,18 +2026,14 @@ index 000000000..0fe373d78 + size_t record_count, + struct skippy_error ** out_error); + -+/** @brief Retains shared attention cells and an immutable recurrent checkpoint owned by the cache. -+ * Recurrent memory requires token_count equal to the current session position. -+ */ ++/** @brief Saves a session prefix into a resident cache sequence. */ +LLAMA_API enum skippy_status skippy_session_save_prefix( + struct skippy_session * session, + int32_t cache_seq_id, + uint64_t token_count, + struct skippy_error ** out_error); + -+/** @brief Shares retained attention cells and restores a private mutable recurrent row. -+ * Token identity must match; recurrent prefixes require the exact saved boundary. -+ */ ++/** @brief Restores a session prefix from a resident cache sequence. */ +LLAMA_API enum skippy_status skippy_session_restore_prefix( + struct skippy_session * session, + int32_t cache_seq_id, @@ -2049,36 +2041,6 @@ index 000000000..0fe373d78 + size_t token_count, + struct skippy_error ** out_error); + -+/** @brief Exports a cache-owned attention page for cold offload without claiming or restoring an execution lane. */ -+LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( -+ struct skippy_session * session, -+ int32_t cache_seq_id, -+ int32_t layer_start, -+ int32_t layer_end, -+ uint64_t token_start, -+ uint64_t token_count, -+ struct skippy_kv_page_desc * out_desc, -+ void * output, -+ size_t output_capacity, -+ size_t * out_bytes, -+ struct skippy_error ** out_error); -+ -+/** @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors. */ -+LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( -+ struct skippy_session * session, -+ int32_t cache_seq_id, -+ void * output, -+ size_t output_capacity, -+ size_t * out_bytes, -+ struct skippy_error ** out_error); -+ -+/** @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool. */ -+LLAMA_API enum skippy_status skippy_session_resident_prefix_bytes( -+ struct skippy_session * session, -+ int32_t cache_seq_id, -+ uint64_t * out_bytes, -+ struct skippy_error ** out_error); -+ +/** @brief Reports physically occupied cells in the session's unified KV cache. */ +LLAMA_API enum skippy_status skippy_session_memory_used_cells( + struct skippy_session * session, diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 20889cd287..7a8e386451 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -57,14 +57,13 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/package_tensor_binding.cpp | 120 +++ src/skippy/package_tensor_binding.h | 27 + src/skippy/rerank_template.h | 36 + - src/skippy/resident_prefix.cpp | 446 +++++++++ src/skippy/runtime_support.h | 47 + - src/skippy/runtime_types.h | 190 ++++ + src/skippy/runtime_types.h | 183 ++++ src/skippy/sampling.cpp | 602 ++++++++++++ src/skippy/sampling_config.cpp | 178 ++++ src/skippy/sampling_internal.h | 67 ++ src/skippy/sampling_vocab.cpp | 74 ++ - src/skippy/session.cpp | 501 ++++++++++ + src/skippy/session.cpp | 521 ++++++++++ src/skippy/speculative_decoding.cpp | 568 +++++++++++ src/skippy/speculative_internal.h | 32 + src/skippy/stage_execution_contract.cpp | 78 ++ @@ -74,10 +73,10 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs src/skippy/stage_realization.h | 21 + src/skippy/stage_slice_plan.cpp | 907 +++++++++++++++++ src/skippy/stage_slice_plan.h | 136 +++ - src/skippy/state.cpp | 743 ++++++++++++++ + src/skippy/state.cpp | 1189 +++++++++++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ - src/skippy/state_memory.cpp | 125 +++ + src/skippy/state_memory.cpp | 116 +++ src/skippy/state_memory.h | 16 + src/skippy/tokenization.cpp | 179 ++++ src/skippy/verification.cpp | 256 +++++ @@ -126,7 +125,6 @@ Subject: [PATCH 02/15] feat(skippy): realize admitted stages from live graphs create mode 100644 src/skippy/package_tensor_binding.cpp create mode 100644 src/skippy/package_tensor_binding.h create mode 100644 src/skippy/rerank_template.h - create mode 100644 src/skippy/resident_prefix.cpp create mode 100644 src/skippy/runtime_support.h create mode 100644 src/skippy/runtime_types.h create mode 100644 src/skippy/sampling.cpp @@ -7922,7 +7920,7 @@ index 000000000..554d2bdd3 +skippy_context_capabilities skippy_context_capabilities_of(const llama_model * model); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp new file mode 100644 -index 000000000..d6e24cd2a +index 000000000..60a27669f --- /dev/null +++ b/src/skippy/model_loading.cpp @@ -0,0 +1,1189 @@ @@ -8620,8 +8618,7 @@ index 000000000..d6e24cd2a + params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : params.n_threads; + params.n_seq_max = stage_model->lane_count; -+ // Cache-owned sequence IDs share the attention pool even with one lane. -+ params.kv_unified = true; ++ params.kv_unified = stage_model->lane_count > 1; + if (config != nullptr) { + params.kv_unified = skippy_resolve_tristate(config->kv_unified, params.kv_unified); + params.offload_kqv = skippy_resolve_tristate(config->kv_offload, params.offload_kqv); @@ -8801,6 +8798,7 @@ index 000000000..d6e24cd2a + + + stage_model->lane_in_use.assign(stage_model->lane_count, false); ++ stage_model->lane_resident_prefix_tokens.resize(stage_model->lane_count); + + const uint64_t native_model_id = reinterpret_cast(stage_model); + if (event_scope != nullptr) { @@ -9089,7 +9087,7 @@ index 000000000..d6e24cd2a + ctx_params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + ctx_params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : ctx_params.n_threads; + ctx_params.n_seq_max = target_model->lane_count; -+ ctx_params.kv_unified = true; ++ ctx_params.kv_unified = target_model->lane_count > 1; + if (config != nullptr) { + ctx_params.kv_unified = skippy_resolve_tristate(config->kv_unified, ctx_params.kv_unified); + ctx_params.offload_kqv = skippy_resolve_tristate(config->kv_offload, ctx_params.offload_kqv); @@ -10617,458 +10615,6 @@ index 000000000..f0c3b2ea7 + } + return rendered; +} -diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp -new file mode 100644 -index 000000000..1b82ba6ba ---- /dev/null -+++ b/src/skippy/resident_prefix.cpp -@@ -0,0 +1,446 @@ -+#include "skippy/state.h" -+#include "skippy/state_memory.h" -+#include "skippy/errors.h" -+#include "skippy/runtime_support.h" -+#include "skippy/runtime_types.h" -+#include "skippy-verify-checkpoint.h" -+#include "llama-io.h" -+#include "llama-kv-cache.h" -+#include "llama-kv-cache-iswa.h" -+#include "llama-memory-hybrid.h" -+#include "llama-memory-hybrid-iswa.h" -+#include "llama-memory-recurrent.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+ -+namespace { -+ -+// These adapters cover complete memory objects, not model-family names. Never -+// silently drop auxiliary state belonging to an unknown derived memory type. -+llama_memory_t attention_memory(llama_memory_t memory) { -+ if (auto * hybrid = dynamic_cast(memory)) { -+ return hybrid->get_mem_attn(); -+ } -+ if (auto * hybrid = dynamic_cast(memory)) { -+ return hybrid->get_mem_attn(); -+ } -+ return skippy_memory_recurrent_adapter(memory) ? nullptr : memory; -+} -+ -+skippy_status validate_session(skippy_session * session, int32_t cache_seq_id, -+ skippy_error ** error) { -+ if (!session || !session->ctx || !session->stage_model || !session->ctx->get_memory()) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model-backed session is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ if (cache_seq_id < static_cast(session->stage_model->lane_count * 2) -+ || cache_seq_id >= LLAMA_MAX_SEQ) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id is outside the resident cache range"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ auto * memory = session->ctx->get_memory(); -+ if (!(skippy_model_memory_cache_capabilities(session->stage_model) & SKIPPY_MEMORY_CACHE_RESIDENT) -+ || (attention_memory(memory) && !session->ctx->get_cparams().kv_unified)) { -+ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "memory does not support complete shared resident prefixes"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ return SKIPPY_STATUS_OK; -+} -+ -+// A size query never touches tensor bytes. Export writes directly to the -+// caller's allocation, avoiding an extra full recurrent payload temporary. -+class recurrent_buffer_writer final : public llama_io_write_i { -+public: -+ recurrent_buffer_writer(void * data = nullptr, size_t capacity = 0) -+ : data(static_cast(data)), capacity(capacity) {} -+ void write(const void * source, size_t bytes) override { -+ reserve(bytes); -+ if (data && bytes) { std::memcpy(data + position, source, bytes); } -+ position += bytes; -+ } -+ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { -+ reserve(bytes); -+ if (data && bytes) { ggml_backend_tensor_get(tensor, data + position, offset, bytes); } -+ position += bytes; -+ } -+ size_t n_bytes() override { return position; } -+private: -+ void reserve(size_t bytes) const { -+ if (bytes > std::numeric_limits::max() - position -+ || (data && (position > capacity || bytes > capacity - position))) { -+ throw std::runtime_error("recurrent export buffer is too small"); -+ } -+ } -+ uint8_t * data; -+ size_t capacity; -+ size_t position = 0; -+}; -+ -+class checkpoint_writer final : public llama_io_write_i { -+public: -+ void write(const void * source, size_t bytes) override { -+ const auto * data = static_cast(source); -+ if (bytes) { payload.insert(payload.end(), data, data + bytes); } -+ } -+ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { -+ const size_t start = payload.size(); -+ payload.resize(start + bytes); -+ if (bytes) { ggml_backend_tensor_get(tensor, payload.data() + start, offset, bytes); } -+ } -+ size_t n_bytes() override { return payload.size(); } -+ std::vector payload; -+}; -+ -+class checkpoint_reader final : public llama_io_read_i { -+public: -+ explicit checkpoint_reader(const std::vector & payload) : payload(payload.data()), bytes(payload.size()) {} -+ checkpoint_reader(const uint8_t * payload, size_t bytes) : payload(payload), bytes(bytes) {} -+ void read(void * destination, size_t bytes) override { -+ require(bytes); -+ if (bytes) { std::memcpy(destination, payload + position, bytes); } -+ position += bytes; -+ } -+ void read_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { -+ require(bytes); -+ if (bytes) { ggml_backend_tensor_set(tensor, payload + position, offset, bytes); } -+ position += bytes; -+ } -+ size_t n_bytes() override { return position; } -+private: -+ void require(size_t bytes) const { -+ if (bytes > this->bytes - position) { -+ throw std::runtime_error("resident recurrent checkpoint is truncated"); -+ } -+ } -+ const uint8_t * payload; -+ const size_t bytes; -+ size_t position = 0; -+}; -+ -+skippy_status validate_checkpoint(skippy_session * session, int32_t cache_seq_id, -+ const llama_token * tokens, size_t count, skippy_error ** error) { -+ auto status = validate_session(session, cache_seq_id, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ if (count > static_cast(std::numeric_limits::max()) || (count && !tokens)) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix tokens are invalid"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ const auto & checkpoints = session->stage_model->resident_prefixes; -+ const auto found = checkpoints.find(cache_seq_id); -+ if (found == checkpoints.end() || count > found->second.tokens.size() -+ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) -+ && count != found->second.tokens.size()) -+ || (count && !std::equal(tokens, tokens + count, found->second.tokens.begin()))) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix identity or exact recurrent boundary does not match"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ auto * attention = attention_memory(session->ctx->get_memory()); -+ if (attention && count && attention->seq_pos_max(cache_seq_id) < static_cast(count - 1)) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident attention prefix is incomplete"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ return SKIPPY_STATUS_OK; -+} -+ -+skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, -+ const llama_token * tokens, size_t count, skippy_error ** error) { -+ const auto valid = validate_session(session, cache_seq_id, error); -+ if (valid != SKIPPY_STATUS_OK) { return valid; } -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ const auto status = validate_checkpoint(session, cache_seq_id, tokens, count, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ // Allocate history before clearing live state. Checkpoint bytes stay immutable -+ // while each restoring lane receives its own mutable recurrent row. -+ std::vector history; -+ if (count) { history.assign(tokens, tokens + count); } -+ skippy_synchronize_context_if_pending(session->stage_model); -+ auto * memory = session->ctx->get_memory(); -+ if (!memory->seq_rm(session->seq_id, -1, -1)) { -+ throw std::runtime_error("failed to clear execution lane for resident prefix"); -+ } -+ const auto & checkpoint = session->stage_model->resident_prefixes.at(cache_seq_id); -+ try { -+ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { -+ checkpoint_reader reader(checkpoint.recurrent); -+ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (reader.n_bytes() != checkpoint.recurrent.size()) { -+ throw std::runtime_error("resident recurrent checkpoint has trailing data"); -+ } -+ } -+ if (auto * attention = attention_memory(memory)) { -+ if (count) { attention->seq_cp(cache_seq_id, session->seq_id, 0, static_cast(count)); } -+ } -+ } catch (...) { -+ memory->seq_rm(session->seq_id, -1, -1); -+ session->n_past = 0; -+ session->token_history.clear(); -+ throw; -+ } -+ session->n_past = static_cast(count); -+ session->token_history = std::move(history); -+ skippy_mtp_clear_session_state(session); -+ session->verify_checkpoints.clear(); -+ return skippy_success(error); -+} -+ -+skippy_status native_error(skippy_error ** error, const std::exception & exception) { -+ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, exception.what()); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+} -+ -+bool used_attention_cells(llama_memory_t memory, uint64_t * cells) { -+ if (!memory) { *cells = 0; return true; } -+ if (auto * kv = dynamic_cast(memory)) { -+ *cells = kv->get_used_cells(); -+ return true; -+ } -+ if (auto * iswa = dynamic_cast(memory)) { -+ *cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); -+ return true; -+ } -+ return false; -+} -+ -+} // namespace -+ -+extern "C" { -+ -+enum skippy_status skippy_session_save_prefix(skippy_session * session, int32_t cache_seq_id, -+ uint64_t token_count, skippy_error ** error) { -+ const auto status = validate_session(session, cache_seq_id, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ if (token_count == 0 || token_count > static_cast(std::max(session->n_past, 0)) -+ || token_count > session->token_history.size() -+ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) -+ && token_count != static_cast(session->n_past))) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident save requires an available exact checkpoint boundary"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ try { -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ auto & checkpoints = session->stage_model->resident_prefixes; -+ const auto previous = checkpoints.find(cache_seq_id); -+ if (previous != checkpoints.end()) { -+ if (previous->second.tokens.size() == token_count -+ && std::equal(previous->second.tokens.begin(), previous->second.tokens.end(), session->token_history.begin())) { -+ return skippy_success(error); -+ } -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident cache sequence already owns a different prefix"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ skippy_resident_checkpoint checkpoint; -+ checkpoint.tokens.assign(session->token_history.begin(), session->token_history.begin() + token_count); -+ skippy_synchronize_context_if_pending(session->stage_model); -+ auto * memory = session->ctx->get_memory(); -+ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { -+ recurrent_buffer_writer measure; -+ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ checkpoint_writer writer; -+ writer.payload.reserve(measure.n_bytes()); -+ recurrent->state_write(writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ checkpoint.recurrent = std::move(writer.payload); -+ } -+ // Allocate metadata first. On allocation failure during seq_cp, remove -+ // every partially attached attention reference and unpublished map node. -+ auto [entry, inserted] = checkpoints.try_emplace(cache_seq_id); -+ GGML_ASSERT(inserted); -+ auto * attention = attention_memory(memory); -+ try { -+ if (attention) { -+ attention->seq_cp(session->seq_id, cache_seq_id, 0, static_cast(token_count)); -+ } -+ entry->second = std::move(checkpoint); -+ } catch (...) { -+ if (attention) { attention->seq_rm(cache_seq_id, -1, -1); } -+ checkpoints.erase(entry); -+ throw; -+ } -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_restore_prefix(skippy_session * session, int32_t cache_seq_id, -+ const llama_token * tokens, size_t count, skippy_error ** error) { -+ try { return restore_checkpoint(session, cache_seq_id, tokens, count, error); } -+ catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_create_from_resident_prefix(skippy_model * model, int32_t cache_seq_id, -+ const llama_token * tokens, size_t count, skippy_session ** output, skippy_error ** error) { -+ if (!model || !model->ctx || !output) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and output session are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *output = nullptr; -+ skippy_session * session = nullptr; -+ auto status = skippy_session_create(model, &session, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ status = skippy_session_restore_prefix(session, cache_seq_id, tokens, count, error); -+ if (status != SKIPPY_STATUS_OK) { -+ skippy_session_free(session, nullptr); -+ return status; -+ } -+ *output = session; -+ return skippy_success(error); -+} -+ -+enum skippy_status skippy_session_drop_sequence(skippy_session * session, int32_t cache_seq_id, -+ skippy_error ** error) { -+ try { -+ const auto status = validate_session(session, cache_seq_id, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ skippy_synchronize_context_if_pending(session->stage_model); -+ if (auto * attention = attention_memory(session->ctx->get_memory())) { -+ if (!attention->seq_rm(cache_seq_id, -1, -1)) { -+ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident attention prefix"); -+ return SKIPPY_STATUS_RUNTIME_ERROR; -+ } -+ } -+ session->stage_model->resident_prefixes.erase(cache_seq_id); -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_resident_prefix_bytes(skippy_session * session, int32_t cache_seq_id, -+ uint64_t * output, skippy_error ** error) { -+ try { -+ if (!output) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident byte count output is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *output = 0; -+ const auto status = validate_session(session, cache_seq_id, error); -+ if (status != SKIPPY_STATUS_OK) { return status; } -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ const auto & checkpoints = session->stage_model->resident_prefixes; -+ const auto found = checkpoints.find(cache_seq_id); -+ if (found != checkpoints.end()) { -+ *output = found->second.recurrent.capacity() + found->second.tokens.capacity() * sizeof(llama_token); -+ } -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_memory_used_cells(skippy_session * session, uint64_t * output, -+ skippy_error ** error) { -+ if (!session || !session->ctx || !output) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and cell count output are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *output = 0; -+ if (!used_attention_cells(attention_memory(session->ctx->get_memory()), output)) { -+ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "attention occupancy is unavailable for this memory type"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ return skippy_success(error); -+} -+ -+enum skippy_status skippy_export_recurrent_state(skippy_session * session, void * output, -+ size_t capacity, size_t * bytes, skippy_error ** error) { -+ if (!session || !session->ctx || !bytes) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent byte count are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *bytes = 0; -+ try { -+ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); -+ if (!recurrent) { return skippy_success(error); } -+ skippy_synchronize_context_if_pending(session->stage_model); -+ recurrent_buffer_writer measure; -+ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ *bytes = measure.n_bytes(); -+ if (!output || capacity < *bytes) { -+ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); -+ return SKIPPY_STATUS_BUFFER_TOO_SMALL; -+ } -+ recurrent_buffer_writer writer(output, capacity); -+ recurrent->state_write(writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_import_recurrent_state(skippy_session * session, const void * input, -+ size_t bytes, skippy_error ** error) { -+ if (!bytes) { return skippy_success(error); } -+ if (!session || !session->ctx || !input) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent payload are required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ try { -+ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); -+ if (!recurrent) { -+ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); -+ return SKIPPY_STATUS_UNSUPPORTED; -+ } -+ skippy_synchronize_context_if_pending(session->stage_model); -+ checkpoint_reader reader(static_cast(input), bytes); -+ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (reader.n_bytes() != bytes) { -+ throw std::runtime_error("recurrent checkpoint has trailing data"); -+ } -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session * session, -+ int32_t cache_seq_id, void * output, size_t capacity, size_t * bytes, skippy_error ** error) { -+ if (!bytes) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent byte count is required"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ *bytes = 0; -+ const auto valid = validate_session(session, cache_seq_id, error); -+ if (valid != SKIPPY_STATUS_OK) { return valid; } -+ try { -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); -+ if (found == session->stage_model->resident_prefixes.end()) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident checkpoint is unavailable"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ const auto & payload = found->second.recurrent; -+ *bytes = payload.size(); -+ if (payload.empty()) { return skippy_success(error); } -+ if (!output || capacity < payload.size()) { -+ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); -+ return SKIPPY_STATUS_BUFFER_TOO_SMALL; -+ } -+ std::memcpy(output, payload.data(), payload.size()); -+ return skippy_success(error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+enum skippy_status skippy_session_export_resident_kv_page(skippy_session * session, -+ int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, -+ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, -+ void * output, size_t capacity, size_t * bytes, skippy_error ** error) { -+ if (bytes) { *bytes = 0; } -+ const auto valid = validate_session(session, cache_seq_id, error); -+ if (valid != SKIPPY_STATUS_OK) { return valid; } -+ try { -+ std::lock_guard lock(session->stage_model->resident_prefix_mutex); -+ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); -+ if (found == session->stage_model->resident_prefixes.end() -+ || token_start > found->second.tokens.size() -+ || token_count > found->second.tokens.size() - token_start) { -+ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident KV export exceeds the saved prefix"); -+ return SKIPPY_STATUS_INVALID_ARGUMENT; -+ } -+ // This stack view neither claims an execution lane nor changes its -+ // state. Only the explicitly requested cold payload is materialized. -+ skippy_session view{}; -+ view.stage_model = session->stage_model; -+ view.ctx = session->ctx; -+ view.seq_id = cache_seq_id; -+ view.n_past = static_cast(found->second.tokens.size()); -+ return skippy_export_kv_page(&view, layer_start, layer_end, token_start, -+ token_count, descriptor, output, capacity, bytes, error); -+ } catch (const std::exception & exception) { return native_error(error, exception); } -+} -+ -+} // extern "C" diff --git a/src/skippy/runtime_support.h b/src/skippy/runtime_support.h new file mode 100644 index 000000000..d7e991307 @@ -11124,10 +10670,10 @@ index 000000000..d7e991307 + skippy_error ** out_error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h new file mode 100644 -index 000000000..38cd35c47 +index 000000000..f19a25b76 --- /dev/null +++ b/src/skippy/runtime_types.h -@@ -0,0 +1,190 @@ +@@ -0,0 +1,183 @@ +#pragma once + +#include "skippy.h" @@ -11139,7 +10685,6 @@ index 000000000..38cd35c47 +#include +#include +#include -+#include +#include +#include + @@ -11214,13 +10759,6 @@ index 000000000..38cd35c47 + skippy_glm_dsa_hot_tensor hot_tensors[SKIPPY_GLM_DSA_HOT_TENSOR_LIMIT] = {}; +}; + -+// Cache-owned checkpoints outlive execution lanes. Attention remains in the -+// native shared cell pool; only the fixed-size recurrent component is copied. -+struct skippy_resident_checkpoint { -+ std::vector tokens; -+ std::vector recurrent; -+}; -+ +struct skippy_model { + llama_model * model = nullptr; + llama_context * ctx = nullptr; @@ -11248,8 +10786,7 @@ index 000000000..38cd35c47 + uint32_t lane_count = 1; + std::mutex lane_mutex; + std::vector lane_in_use; -+ std::mutex resident_prefix_mutex; -+ std::map resident_prefixes; ++ std::vector> lane_resident_prefix_tokens; + std::mutex chat_templates_mutex; + void * chat_templates = nullptr; + void (*chat_templates_free)(void *) = nullptr; @@ -11275,6 +10812,8 @@ index 000000000..38cd35c47 + int32_t n_past = 0; + bool borrowed_sequence = false; + int32_t borrowed_prefix_tokens = 0; ++ bool preserve_prefix_on_free = false; ++ int32_t preserve_prefix_tokens = 0; + std::vector token_history; + std::vector signal_history; + std::vector prefill_positions; @@ -12265,10 +11804,10 @@ index 000000000..baf83db44 +} diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp new file mode 100644 -index 000000000..be612007f +index 000000000..f1de95cc5 --- /dev/null +++ b/src/skippy/session.cpp -@@ -0,0 +1,501 @@ +@@ -0,0 +1,521 @@ +#include "skippy.h" +#include "skippy/errors.h" +#include "skippy/environment.h" @@ -12418,6 +11957,9 @@ index 000000000..be612007f + if (skippy_mtp_available(session)) { + skippy_mtp_clear_session_state(session); + } ++ if (static_cast(seq_id) < model->lane_resident_prefix_tokens.size()) { ++ model->lane_resident_prefix_tokens[static_cast(seq_id)].clear(); ++ } + if (llama_memory_t memory = model->ctx->get_memory()) { + if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { + skippy_release_execution_lane(model, seq_id); @@ -12679,7 +12221,24 @@ index 000000000..be612007f + g_skippy_external_decode_session = nullptr; + } + if (session->ctx != nullptr) { -+ skippy_session_reset(session, nullptr); ++ if (session->preserve_prefix_on_free && !session->borrowed_sequence && session->stage_model != nullptr) { ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (llama_memory_t memory = session->ctx->get_memory()) { ++ llama_memory_seq_rm( ++ memory, ++ session->seq_id, ++ static_cast(session->preserve_prefix_tokens), ++ -1); ++ } ++ } else { ++ skippy_session_reset(session, nullptr); ++ if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { ++ const size_t lane = static_cast(session->seq_id); ++ if (lane < session->stage_model->lane_resident_prefix_tokens.size()) { ++ session->stage_model->lane_resident_prefix_tokens[lane].clear(); ++ } ++ } ++ } + } + skippy_clear_chat_sampling(session); + if (!session->borrowed_sequence) { @@ -15642,10 +15201,10 @@ index 000000000..1cb24c7cb + std::string & error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp new file mode 100644 -index 000000000..cf0838051 +index 000000000..f035ea13f --- /dev/null +++ b/src/skippy/state.cpp -@@ -0,0 +1,743 @@ +@@ -0,0 +1,1189 @@ +#include "skippy/state.h" +#include "skippy/state_memory.h" +#include "skippy/errors.h" @@ -15929,6 +15488,121 @@ index 000000000..cf0838051 + return skippy_success(out_error); +} + ++static llama_memory_recurrent * skippy_get_recurrent_memory( ++ skippy_session * session, ++ skippy_error ** out_error) { ++ if (session == nullptr || session->ctx == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); ++ return nullptr; ++ } ++ ++ llama_memory_t memory = session->ctx->get_memory(); ++ if (memory == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); ++ return nullptr; ++ } ++ ++ return skippy_memory_recurrent_adapter(memory); ++} ++ ++enum skippy_status skippy_export_recurrent_state( ++ struct skippy_session * session, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error) { ++ if (out_bytes == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_bytes is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ *out_bytes = 0; ++ skippy_error * recurrent_error = nullptr; ++ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); ++ if (recurrent_error != nullptr) { ++ if (out_error != nullptr) { ++ *out_error = recurrent_error; ++ } else { ++ skippy_error_free(recurrent_error); ++ } ++ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (recurrent == nullptr) { ++ return skippy_success(out_error); ++ } ++ ++ session->ctx->synchronize(); ++ const size_t bytes = llama_state_seq_get_size_ext( ++ session->ctx, ++ session->seq_id, ++ LLAMA_STATE_SEQ_FLAGS_NONE); ++ *out_bytes = bytes; ++ if (bytes == 0) { ++ return skippy_success(out_error); ++ } ++ if (output == nullptr || output_capacity < bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent state output buffer is too small"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ ++ const size_t written = llama_state_seq_get_data_ext( ++ session->ctx, ++ static_cast(output), ++ output_capacity, ++ session->seq_id, ++ LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (written != bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to export recurrent state"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ ++ return skippy_success(out_error); ++} ++ ++enum skippy_status skippy_import_recurrent_state( ++ struct skippy_session * session, ++ const void * input, ++ size_t input_bytes, ++ struct skippy_error ** out_error) { ++ if (input_bytes == 0) { ++ return skippy_success(out_error); ++ } ++ if (input == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent state input is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ skippy_error * recurrent_error = nullptr; ++ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); ++ if (recurrent_error != nullptr) { ++ if (out_error != nullptr) { ++ *out_error = recurrent_error; ++ } else { ++ skippy_error_free(recurrent_error); ++ } ++ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (recurrent == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ ++ session->ctx->synchronize(); ++ const size_t read = llama_state_seq_set_data_ext( ++ session->ctx, ++ static_cast(input), ++ input_bytes, ++ session->seq_id, ++ LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (read != input_bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to import recurrent state"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ session->ctx->synchronize(); ++ ++ return skippy_success(out_error); ++} ++ +static llama_kv_cache * skippy_get_kv_cache( + skippy_session * session, + skippy_error ** out_error) { @@ -16377,6 +16051,10 @@ index 000000000..cf0838051 + if (session->token_history.size() > token_count) { + session->token_history.resize(static_cast(token_count)); + skippy_clear_chat_sampling(session); ++ } else if (session->sampling_accepted_token_count > token_count) { ++ // A verify restore to the start of its window leaves the history at ++ // token_count, but the sampler already accepted the window's first row. ++ skippy_clear_chat_sampling(session); + } + if (session->signal_history.size() > token_count) { + session->signal_history.resize(static_cast(token_count)); @@ -16388,6 +16066,333 @@ index 000000000..cf0838051 + return skippy_success(out_error); +} + ++static bool skippy_is_reserved_sequence_id( ++ const skippy_session * session, ++ int32_t seq_id) { ++ if (session == nullptr || session->stage_model == nullptr || seq_id < 0) { ++ return true; ++ } ++ const int32_t reserved = static_cast(session->stage_model->lane_count) * 2; ++ return seq_id < reserved; ++} ++ ++static bool skippy_is_reserved_sequence_id_for_model( ++ const skippy_model * model, ++ int32_t seq_id) { ++ if (model == nullptr || seq_id < 0) { ++ return true; ++ } ++ const int32_t reserved = static_cast(model->lane_count) * 2; ++ return seq_id < reserved; ++} ++ ++static enum skippy_status skippy_get_resident_prefix_memory( ++ skippy_session * session, ++ llama_memory_t * out_memory, ++ struct skippy_error ** out_error) { ++ if (session == nullptr || session->ctx == nullptr || out_memory == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ llama_memory_t memory = session->ctx->get_memory(); ++ if (memory == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ ++ skippy_error * recurrent_error = nullptr; ++ llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); ++ if (recurrent_error != nullptr) { ++ if (out_error != nullptr) { ++ *out_error = recurrent_error; ++ } else { ++ skippy_error_free(recurrent_error); ++ } ++ return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (recurrent != nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "resident prefix cache is not enabled for recurrent memory"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ ++ *out_memory = memory; ++ return SKIPPY_STATUS_OK; ++} ++ ++enum skippy_status skippy_session_save_prefix( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ uint64_t token_count, ++ struct skippy_error ** out_error) { ++ if (token_count > static_cast(std::numeric_limits::max())) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (session == nullptr || token_count > static_cast(session->n_past)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cannot save prefix beyond current session position"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ llama_memory_t memory = nullptr; ++ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); ++ if (status != SKIPPY_STATUS_OK) { ++ return status; ++ } ++ ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (!llama_memory_seq_rm(memory, cache_seq_id, -1, -1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear resident prefix sequence"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (token_count > 0) { ++ llama_memory_seq_cp(memory, session->seq_id, cache_seq_id, 0, static_cast(token_count)); ++ } ++ if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { ++ const size_t lane = static_cast(session->seq_id); ++ if (lane < session->stage_model->lane_resident_prefix_tokens.size() ++ && session->token_history.size() >= static_cast(token_count)) { ++ auto & lane_tokens = session->stage_model->lane_resident_prefix_tokens[lane]; ++ lane_tokens.assign( ++ session->token_history.begin(), ++ session->token_history.begin() + static_cast(token_count)); ++ session->preserve_prefix_on_free = true; ++ session->preserve_prefix_tokens = static_cast(token_count); ++ } ++ } ++ return skippy_success(out_error); ++} ++ ++enum skippy_status skippy_session_restore_prefix( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ const llama_token * token_ids, ++ size_t token_count, ++ struct skippy_error ** out_error) { ++ if (token_count > static_cast(std::numeric_limits::max())) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (token_count > 0 && token_ids == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ llama_memory_t memory = nullptr; ++ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); ++ if (status != SKIPPY_STATUS_OK) { ++ return status; ++ } ++ ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (token_count > 0) { ++ const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); ++ if (max_pos < static_cast(token_count - 1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ } ++ if (!llama_memory_seq_rm(memory, session->seq_id, -1, -1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear execution lane"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (token_count > 0) { ++ llama_memory_seq_cp(memory, cache_seq_id, session->seq_id, 0, static_cast(token_count)); ++ } ++ session->n_past = static_cast(token_count); ++ if (token_count == 0) { ++ session->token_history.clear(); ++ } else { ++ session->token_history.assign(token_ids, token_ids + token_count); ++ } ++ session->signal_history.clear(); ++ skippy_mtp_clear_session_state(session); ++ session->verify_checkpoints.clear(); ++ return skippy_success(out_error); ++} ++ ++enum skippy_status skippy_session_create_from_resident_prefix( ++ struct skippy_model * model, ++ int32_t cache_seq_id, ++ const llama_token * token_ids, ++ size_t token_count, ++ struct skippy_session ** out_session, ++ struct skippy_error ** out_error) { ++ if (model == nullptr || model->model == nullptr || model->ctx == nullptr || out_session == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and out_session are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *out_session = nullptr; ++ if (token_count > static_cast(std::numeric_limits::max()) ++ || token_count > static_cast(std::numeric_limits::max())) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds supported position range"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (token_count > 0 && token_ids == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (skippy_is_reserved_sequence_id_for_model(model, cache_seq_id)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ const int32_t seq_id = skippy_claim_execution_lane(model); ++ if (seq_id < 0) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "no skippy execution lane is available"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ ++ skippy_session temp{}; ++ temp.stage_model = model; ++ temp.ctx = model->ctx; ++ llama_memory_t memory = nullptr; ++ enum skippy_status status = skippy_get_resident_prefix_memory(&temp, &memory, out_error); ++ if (status != SKIPPY_STATUS_OK) { ++ skippy_release_execution_lane(model, seq_id); ++ return status; ++ } ++ ++ skippy_synchronize_context_if_pending(model); ++ if (token_count > 0) { ++ const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); ++ if (max_pos < static_cast(token_count - 1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); ++ skippy_release_execution_lane(model, seq_id); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ } ++ bool lane_prefix_hit = false; ++ const size_t lane = static_cast(seq_id); ++ if (lane < model->lane_resident_prefix_tokens.size()) { ++ const auto & lane_tokens = model->lane_resident_prefix_tokens[lane]; ++ lane_prefix_hit = lane_tokens.size() == token_count ++ && (token_count == 0 || std::equal(lane_tokens.begin(), lane_tokens.end(), token_ids)); ++ } ++ if (!lane_prefix_hit) { ++ if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear borrowed execution lane"); ++ skippy_release_execution_lane(model, seq_id); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ if (token_count > 0) { ++ llama_memory_seq_cp(memory, cache_seq_id, seq_id, 0, static_cast(token_count)); ++ } ++ } ++ if (!llama_memory_seq_rm(memory, seq_id, static_cast(token_count), -1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to trim borrowed execution lane"); ++ skippy_release_execution_lane(model, seq_id); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ ++ skippy_session * session = new skippy_session{}; ++ session->stage_model = model; ++ session->ctx = model->ctx; ++ session->seq_id = seq_id; ++ session->n_past = static_cast(token_count); ++ session->borrowed_sequence = false; ++ session->borrowed_prefix_tokens = 0; ++ if (token_count > 0) { ++ session->token_history.assign(token_ids, token_ids + token_count); ++ } ++ skippy_mtp_clear_session_state(session); ++ *out_session = session; ++ return skippy_success(out_error); ++} ++ ++enum skippy_status skippy_session_drop_sequence( ++ struct skippy_session * session, ++ int32_t seq_id, ++ struct skippy_error ** out_error) { ++ if (skippy_is_reserved_sequence_id(session, seq_id)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "sequence id overlaps execution lanes"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ ++ llama_memory_t memory = nullptr; ++ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); ++ if (status != SKIPPY_STATUS_OK) { ++ return status; ++ } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident prefix sequence"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ return skippy_success(out_error); ++} ++ ++static bool skippy_memory_used_cells(llama_memory_t memory, uint64_t * out_used_cells) { ++ if (auto * cache = dynamic_cast(memory)) { ++ *out_used_cells = cache->get_used_cells(); ++ return true; ++ } ++ if (auto * dsa = dynamic_cast(memory)) { ++ *out_used_cells = std::max(dsa->get_mla()->get_used_cells(), dsa->get_lid()->get_used_cells()); ++ return true; ++ } ++ if (auto * iswa = dynamic_cast(memory)) { ++ *out_used_cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); ++ return true; ++ } ++ if (auto * dsa_iswa = dynamic_cast(memory)) { ++ uint64_t dsa_used_cells = 0; ++ if (!skippy_memory_used_cells(dsa_iswa->get_dsa(), &dsa_used_cells)) { ++ return false; ++ } ++ *out_used_cells = std::max(dsa_used_cells, dsa_iswa->get_swa()->get_used_cells()); ++ return true; ++ } ++ if (auto * msa = dynamic_cast(memory)) { ++ *out_used_cells = std::max(msa->get_base()->get_used_cells(), msa->get_idx()->get_used_cells()); ++ return true; ++ } ++ if (auto * dsv4 = dynamic_cast(memory)) { ++ uint64_t raw_used_cells = 0; ++ if (!skippy_memory_used_cells(dsv4->get_raw(), &raw_used_cells)) { ++ return false; ++ } ++ *out_used_cells = std::max({ ++ raw_used_cells, ++ dsv4->get_csa()->get_used_cells(), ++ dsv4->get_hca()->get_used_cells(), ++ dsv4->get_lid()->get_used_cells(), ++ }); ++ return true; ++ } ++ return false; ++} ++ ++enum skippy_status skippy_session_memory_used_cells( ++ struct skippy_session * session, ++ uint64_t * out_used_cells, ++ struct skippy_error ** out_error) { ++ if (out_used_cells == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_used_cells is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *out_used_cells = 0; ++ ++ llama_memory_t memory = nullptr; ++ enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); ++ if (status != SKIPPY_STATUS_OK) { ++ return status; ++ } ++ if (!skippy_memory_used_cells(memory, out_used_cells)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "physical occupancy is unavailable for this memory type"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ return skippy_success(out_error); ++} ++ +} // extern "C" diff --git a/src/skippy/state_effects.cpp b/src/skippy/state_effects.cpp new file mode 100644 @@ -16927,10 +16932,10 @@ index 000000000..5bb6b779b + std::string & error); diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp new file mode 100644 -index 000000000..806e79d72 +index 000000000..e271852ff --- /dev/null +++ b/src/skippy/state_memory.cpp -@@ -0,0 +1,125 @@ +@@ -0,0 +1,116 @@ +#include "skippy/state_memory.h" +#include "skippy/state.h" +#include "skippy/runtime_types.h" @@ -16989,16 +16994,16 @@ index 000000000..806e79d72 + // coverage merely from a successful dynamic_cast or a nonempty export. + const auto & type = typeid(*memory); + if (type == typeid(llama_kv_cache) || type == typeid(llama_kv_cache_iswa)) { -+ return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; ++ return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_recurrent)) { + return skippy_memory_recurrent_adapter(memory) -+ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_hybrid) || type == typeid(llama_memory_hybrid_iswa)) { + return skippy_memory_recurrent_adapter(memory) && + (skippy_memory_kv_adapter(memory) || skippy_memory_iswa_adapter(memory)) -+ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + // DSA/MSA memories include an indexer tier. Until a real-model resident + // save/restore proves that tier survives, use complete state snapshots. @@ -17022,7 +17027,7 @@ index 000000000..806e79d72 + } + // A phase with no persistent effects adds no cache restrictions. It must + // not be confused with failed graph admission or unexported context state. -+ uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | ++ uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | + SKIPPY_MEMORY_CACHE_FULL_STATE; + for (const auto & effect : effects) { + switch (effect.kind) { @@ -17031,6 +17036,7 @@ index 000000000..806e79d72 + break; + case skippy_state_kind::recurrent_conv: + case skippy_state_kind::recurrent_ssm: ++ supported &= ~SKIPPY_MEMORY_CACHE_RESIDENT; + break; + case skippy_state_kind::derived_persistent: + supported &= SKIPPY_MEMORY_CACHE_FULL_STATE; @@ -17041,20 +17047,10 @@ index 000000000..806e79d72 +} + +extern "C" uint32_t skippy_model_memory_cache_capabilities(const skippy_model * model) { -+ uint32_t capabilities = model && model->ctx ++ return model && model->ctx + ? model->ctx->admit_skippy_cache_capabilities( + skippy_memory_cache_capabilities(model->ctx->get_memory())) + : 0; -+ // Explicit non-unified attention contexts cannot admit the resident API. -+ // Preserve their complete export representations, but never advertise -+ // cache ownership that resident_prefix::validate_session will refuse. -+ if (model && model->ctx && !model->ctx->get_cparams().kv_unified -+ && (capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION)) { -+ capabilities &= ~(SKIPPY_MEMORY_CACHE_RESIDENT -+ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION -+ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); -+ } -+ return capabilities; +} diff --git a/src/skippy/state_memory.h b/src/skippy/state_memory.h new file mode 100644 diff --git a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index e8e334bb0a..15a85b31f3 100644 --- a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -33,1393 +33,6 @@ Subject: [PATCH 03/15] feat(llama): integrate live stage planning and 25 files changed, 3050 insertions(+), 340 deletions(-) create mode 100644 src/skippy-verify-checkpoint.h -diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h -index c37ba9471..00ba30d6a 100644 ---- a/ggml/include/ggml.h -+++ b/ggml/include/ggml.h -@@ -2499,6 +2499,28 @@ extern "C" { - float max_bias, - float logit_softcap); - -+ // same as ggml_flash_attn_ext, but each q slice attends to its own list of K/V rows -+ // q: [n_embd_k, n_batch, n_head, ne3] -+ // k: [n_embd_k, n_rows, n_head_kv, 1 ] shared by all q slices -+ // v: [n_embd_v, n_rows, n_head_kv, 1 ] -+ // mask: [n_kv, n_batch, ne32, ne3] -+ // kv_rows: [n_kv, ne3] I32, mask column i of slice i3 uses row kv_rows[i, i3] of k and v -+ // negative rows are padding, their mask entries must be -inf -+ // kv_rows: contiguous I32 [padded_rows, q->ne[3], 1, 1], src[5]. -+ // Nonnegative entries must index both shared K/V pools; negative padding -+ // entries must have -INFINITY mask values for every corresponding query. -+ // Backends may require padded_rows alignment; query supports_op first. -+ GGML_API struct ggml_tensor * ggml_flash_attn_ext_rows( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, -+ struct ggml_tensor * k, -+ struct ggml_tensor * v, -+ struct ggml_tensor * mask, -+ struct ggml_tensor * kv_rows, -+ float scale, -+ float max_bias, -+ float logit_softcap); -+ - GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec), -diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp -index 679d5216d..e94b39e4c 100644 ---- a/ggml/src/ggml-backend-meta.cpp -+++ b/ggml/src/ggml-backend-meta.cpp -@@ -153,6 +153,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type( - - static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { - GGML_ASSERT(ggml_backend_dev_is_meta(dev)); -+ // The split-state planner does not partition row lists with head-sharded inputs. -+ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { -+ return false; -+ } - const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; - return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), - [op](ggml_backend_dev_t simple_dev) { return ggml_backend_dev_supports_op(simple_dev, op); }); -diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp -index 28e17f3f7..c6429b13b 100644 ---- a/ggml/src/ggml-cann/ggml-cann.cpp -+++ b/ggml/src/ggml-cann/ggml-cann.cpp -@@ -2664,6 +2664,10 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten - return true; - case GGML_OP_FLASH_ATTN_EXT: - { -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ if (op->src[5] != nullptr) { -+ return false; -+ } - #ifdef ASCEND_310P - // FA not support on 310p device - return false; -diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp -index 7a73e138e..1645e954f 100644 ---- a/ggml/src/ggml-cpu/ops.cpp -+++ b/ggml/src/ggml-cpu/ops.cpp -@@ -8930,6 +8930,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; -+ const ggml_tensor * kv_rows = dst->src[5]; - - GGML_TENSOR_LOCALS(int64_t, neq, q, ne) - GGML_TENSOR_LOCALS(size_t, nbq, q, nb) -@@ -9037,6 +9038,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( - const float * pq = (const float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)); - q_to_vec_dot(pq, Q_q, DK); - -+ const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; -+ - // online softmax / attention - // loop over n_kv and n_head_kv - // ref: https://arxiv.org/pdf/2112.05682.pdf -@@ -9047,9 +9050,14 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( - continue; - } - -+ const int64_t ik1 = rows ? rows[ic] : ic; -+ if (ik1 < 0) { -+ continue; -+ } -+ - float s; // KQ value - -- const char * k_data = (const char *) k->data + ( ic*nbk1 + ik2*nbk2 + ik3*nbk3); -+ const char * k_data = (const char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3); - kq_vec_dot(DK, &s, 0, k_data, 0, Q_q, 0, 1); - - s = s*scale; // scale KQ value -@@ -9065,7 +9073,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( - float ms = 1.0f; // upon new higher max val, scale VKQ and KQ sum with this value - float vs = 1.0f; // post-softmax KQ value, expf(s - M) - -- const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3)); -+ const char * v_data = ((const char *) v->data + (ik1*nbv1 + iv2*nbv2 + iv3*nbv3)); - - if (v->type == GGML_TYPE_F16) { - if (s > M) { -@@ -9232,6 +9240,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( - static constexpr int Q_TILE_SZ = ggml_fa_tile_config::Q; - static constexpr int KV_TILE_SZ = ggml_fa_tile_config::KV; - -+ // with kv_rows the loop runs over the mask columns and reads K/V rows through kv_rows -+ const ggml_tensor * kv_rows = dst->src[5]; -+ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; -+ - int ir = ir0; - while (ir < ir1) { - // q indices for the start of this tile -@@ -9239,6 +9251,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( - const int iq2 = (ir - iq3*neq2*neq1)/neq1; - const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1); - -+ // padding rows are masked, read row 0 for them -+ const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; -+ auto kv_row = [rows](int64_t i) -> int64_t { return rows ? std::max(rows[i], 0) : i; }; -+ - // Number of valid rows in this tile: - // - limited by tile size (Q_TILE_SZ) - // - limited by chunk boundary (ir1 - ir) -@@ -9298,8 +9314,8 @@ static void ggml_compute_forward_flash_attn_ext_tiled( - memset(K_f32, 0, DK * KV_TILE_SZ * sizeof(float)); - memset(V32, 0, KV_TILE_SZ * DV * sizeof(float)); - -- for (int64_t ic = 0; ic < nek1; ic += KV_TILE_SZ) { -- const int kv_tile = (int)std::min((int64_t)KV_TILE_SZ, nek1 - ic); -+ for (int64_t ic = 0; ic < n_kv_cols; ic += KV_TILE_SZ) { -+ const int kv_tile = (int)std::min((int64_t)KV_TILE_SZ, n_kv_cols - ic); - - // skip the tile entirely if all the masks are -inf - if (mask) { -@@ -9326,7 +9342,7 @@ static void ggml_compute_forward_flash_attn_ext_tiled( - // Pack K tile transposed: K_f32[dk][kv] so KV_TILE is contiguous (SIMD dim) - // Zero-pad the last tile so the GEMM always operates on KV_TILE_SZ columns - for (int tk = 0; tk < kv_tile; tk++) { -- const char * k_data = (const char *)k->data + (ic + tk)*nbk1 + ik2*nbk2 + ik3*nbk3; -+ const char * k_data = (const char *)k->data + kv_row(ic + tk)*nbk1 + ik2*nbk2 + ik3*nbk3; - if (kv_type == GGML_TYPE_F16) { - const ggml_fp16_t * k_f16 = (const ggml_fp16_t *)k_data; - for (int64_t dk = 0; dk < DK; dk++) { -@@ -9391,7 +9407,7 @@ static void ggml_compute_forward_flash_attn_ext_tiled( - // V accumulation: VKQ32 += softmax(KQ) * V - // Pack V tile to contiguous F32, zero-padded - for (int tk = 0; tk < kv_tile; tk++) { -- const char * v_data = (const char *)v->data + (ic + tk)*nbv1 + iv2*nbv2 + iv3*nbv3; -+ const char * v_data = (const char *)v->data + kv_row(ic + tk)*nbv1 + iv2*nbv2 + iv3*nbv3; - if (kv_type == GGML_TYPE_F16) { - ggml_cpu_fp16_to_fp32((const ggml_fp16_t *)v_data, V32 + tk * DV, DV); - } else { -@@ -9563,8 +9579,12 @@ static void ggml_compute_forward_flash_attn_ext_f16( - // When use_ref is set, force the vec-only reference implementation (no tiling, no KV-chunking) - const bool use_ref = params->use_ref; - -+ // with kv_rows the loops run over the mask columns, the split KV path does not support it -+ const ggml_tensor * kv_rows = dst->src[5]; -+ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; -+ - const bool kv_is_f32_or_f16 = (k->type == GGML_TYPE_F32 || k->type == GGML_TYPE_F16); -- const bool use_split_kv_path = !use_ref && (neq1 == 1 && neq3 == 1) && kv_is_f32_or_f16 && (k->type == v->type) && q->type == GGML_TYPE_F32 && nek1 >= 512; -+ const bool use_split_kv_path = !use_ref && !kv_rows && (neq1 == 1 && neq3 == 1) && kv_is_f32_or_f16 && (k->type == v->type) && q->type == GGML_TYPE_F32 && nek1 >= 512; - - if (use_split_kv_path) { - const int64_t chunk_size = (nek1 + nth - 1) / nth; -@@ -9643,7 +9663,7 @@ static void ggml_compute_forward_flash_attn_ext_f16( - if (use_tiled) { - ggml_compute_forward_flash_attn_ext_tiled(params, dst, ir0, ir1); - } else { -- ggml_compute_forward_flash_attn_ext_f16_one_chunk(params, dst, ir0, ir1, 0, nek1, nullptr, 0); -+ ggml_compute_forward_flash_attn_ext_f16_one_chunk(params, dst, ir0, ir1, 0, n_kv_cols, nullptr, 0); - } - - current_chunk = ggml_threadpool_chunk_add(params->threadpool, 1); -diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp -index 81e86b9dd..2071a15c1 100644 ---- a/ggml/src/ggml-cpu/spacemit/ime.cpp -+++ b/ggml/src/ggml-cpu/spacemit/ime.cpp -@@ -1041,6 +1041,10 @@ class tensor_traits_common : public tensor_traits_base { - return true; - } - case GGML_OP_FLASH_ATTN_EXT: -+ // K/V row lists are handled by the generic CPU path -+ if (op->src[5] != nullptr) { -+ return false; -+ } - forward_flash_attn_ext_f16(params, op); - return true; - case GGML_OP_CONT: -diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh -index 41d948335..beb877941 100644 ---- a/ggml/src/ggml-cuda/fattn-common.cuh -+++ b/ggml/src/ggml-cuda/fattn-common.cuh -@@ -25,6 +25,7 @@ typedef void (* fattn_kernel_t)( - const char * __restrict__ mask, - const char * __restrict__ sinks, - const int * __restrict__ KV_max, -+ const int * __restrict__ KV_rows, - float * __restrict__ dst, - float2 * __restrict__ dst_meta, - const float scale, -@@ -991,8 +992,13 @@ void launch_fattn( - - const bool V_is_K_view = V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs)); - -- const ggml_tensor * mask = dst->src[3]; -- const ggml_tensor * sinks = dst->src[4]; -+ const ggml_tensor * mask = dst->src[3]; -+ const ggml_tensor * sinks = dst->src[4]; -+ const ggml_tensor * kv_rows = dst->src[5]; -+ -+ // with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows -+ const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1]; -+ GGML_ASSERT(!kv_rows || !use_sparse); - - ggml_tensor * KQV = dst; - -@@ -1113,8 +1119,8 @@ void launch_fattn( - - // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. - // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or -- // multiple sequences of possibly different lengths. -- const bool scan_mask = !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); -+ // multiple sequences of possibly different lengths, or kv_rows lists that end with padding. -+ const bool scan_mask = !use_sparse && mask && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows); - if (scan_mask) { - const int64_t s31 = mask->nb[1] / sizeof(half2); - const int64_t s33 = mask->nb[3] / sizeof(half2); -@@ -1123,7 +1129,7 @@ void launch_fattn( - const dim3 block_dim_KV_max(FATTN_KQ_STRIDE/2, 1, 1); - - const int ne_KV_max = blocks_num_KV_max.x*blocks_num_KV_max.y; -- const int iter_k = K->ne[1] / FATTN_KQ_STRIDE; -+ const int iter_k = n_kv_cols / FATTN_KQ_STRIDE; - - KV_max.alloc(ne_KV_max); - ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_KV_max, block_dim_KV_max, 0, main_stream); -@@ -1132,13 +1138,19 @@ void launch_fattn( - CUDA_CHECK(cudaGetLastError()); - } - -+ // K/V are shared by all slices when read through kv_rows -+ if (kv_rows) { -+ nb13 = 0; -+ nb23 = 0; -+ } -+ - const dim3 block_dim(warp_size, nwarps, 1); - int max_blocks_per_sm = 1; // Max. number of active blocks limited by occupancy. - CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, fattn_kernel, block_dim.x * block_dim.y * block_dim.z, nbytes_shared)); - GGML_ASSERT(max_blocks_per_sm > 0); - int parallel_blocks = max_blocks_per_sm; - -- const int64_t n_kv = use_sparse ? n_kv_max : K->ne[1]; -+ const int64_t n_kv = use_sparse ? n_kv_max : n_kv_cols; - const int ntiles_KV = (n_kv + nbatch_fa - 1) / nbatch_fa; // Max. number of parallel blocks limited by KV cache length. - - dim3 blocks_num; -@@ -1255,6 +1267,7 @@ void launch_fattn( - mask ? ((const char *) mask->data) : nullptr, - sinks ? ((const char *) sinks->data) : nullptr, - KV_max.ptr, -+ kv_rows ? (const int *) kv_rows->data : nullptr, - !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, - scale, max_bias, m0, m1, n_head_log2, logit_softcap, - Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3], -diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh -index 296aa2b34..f37b5de88 100644 ---- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh -+++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh -@@ -420,6 +420,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - // padded slots gather row 0, the -inf mask removes their contribution - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; - i_KV = index >= 0 ? index : 0; -+ } else if (indices) { -+ // K/V rows given per mask column, negative rows are padding -+ i_KV = max(indices[k_VKQ_0 + i], 0); - } else { - i_KV = k_VKQ_0 + i; - } -@@ -467,8 +470,11 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - if constexpr (use_sparse) { - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; - src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; -+ } else if (!oob_check || i < i_sup) { -+ const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i; -+ src = KV + i_KV*stride_KV + k*h2_per_chunk; - } else { -- src = !oob_check || i < i_sup ? KV + int64_t(k_VKQ_0 + i)*stride_KV + k*h2_per_chunk : zero; -+ src = zero; - } - ggml_cuda_memcpy_1<16>(swizzle(tile_KV, i*stride_tile + k*h2_per_chunk, i), src); - } -@@ -634,7 +640,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - cp_async_wait_all(); - __syncthreads(); - flash_attn_ext_f16_load_tile -- (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, nullptr); -+ (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, indices); - } else { - // the sparse mask values are gathered per element, always load them synchronously - constexpr bool use_cp_async = nstages == 1 && !use_sparse; -@@ -991,7 +997,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - (mask_h, tile_mask, stride_mask, k_VKQ_0 + nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); - } - flash_attn_ext_f16_load_tile -- (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, nullptr); -+ (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, indices); - } - } - -@@ -1343,7 +1349,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); - } - flash_attn_ext_f16_load_tile -- (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, nullptr); -+ (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, indices); - } - - // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. -@@ -1802,6 +1808,7 @@ static __global__ void flash_attn_ext_f16( - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, -+ const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, - const float scale, -@@ -1924,7 +1931,8 @@ static __global__ void flash_attn_ext_f16( - - const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; -- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; -+ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : -+ KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; - - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; - -@@ -1973,7 +1981,8 @@ static __global__ void flash_attn_ext_f16( - - const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; -- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; -+ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : -+ KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; - - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; - -@@ -1989,7 +1998,7 @@ static __global__ void flash_attn_ext_f16( - (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); - #else -- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, -+ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, - max_bias, m0, m1, n_head_log2, logit_softcap, - ne00, ne01, ne02, ne03, - nb01, nb02, nb03, -diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh -index b5ea915e1..6cb30022e 100644 ---- a/ggml/src/ggml-cuda/fattn-tile.cuh -+++ b/ggml/src/ggml-cuda/fattn-tile.cuh -@@ -797,6 +797,7 @@ static __global__ void flash_attn_tile( - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, -+ const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, - const float scale, -@@ -821,6 +822,7 @@ static __global__ void flash_attn_tile( - const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; - float * GGML_CUDA_RESTRICT dst = dst_ptr; - float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; -+ GGML_UNUSED(KV_rows_ptr); - - // Skip unused kernel variants for faster compilation: - -@@ -1132,7 +1134,7 @@ static __global__ void flash_attn_tile( - } - } - #else -- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, -+ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, - max_bias, m0, m1, n_head_log2, logit_softcap, - ne00, ne01, ne02, ne03, - nb01, nb02, nb03, -diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh -index 57a285565..8eb29ef80 100644 ---- a/ggml/src/ggml-cuda/fattn-vec.cuh -+++ b/ggml/src/ggml-cuda/fattn-vec.cuh -@@ -25,6 +25,7 @@ static __global__ void flash_attn_ext_vec( - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, -+ const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, - const float scale, -@@ -50,6 +51,7 @@ static __global__ void flash_attn_ext_vec( - const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; - float * GGML_CUDA_RESTRICT dst = dst_ptr; - float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; -+ GGML_UNUSED(KV_rows_ptr); - - // Skip unused kernel variants for faster compilation: - if (use_logit_softcap && !(D == 128 || D == 256)) { -@@ -512,7 +514,7 @@ static __global__ void flash_attn_ext_vec( - dst_meta[((sequence*int(ne01.z) + ic0 + tid)*ne02 + head)*gridDim.y + blockIdx.y] = make_float2(KQ_max[tid], KQ_sum[tid]); - } - #else -- GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, -+ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, - max_bias, m0, m1, n_head_log2, logit_softcap, - ne00, ne01, ne02, ne03, - nb01, nb02, nb03, -diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu -index 5fa3e5308..79eb3cccf 100644 ---- a/ggml/src/ggml-cuda/fattn.cu -+++ b/ggml/src/ggml-cuda/fattn.cu -@@ -144,7 +144,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ - // the dense kernel handles up to 64/ncols2 queries per K/V pass, the single-query gather has to beat that - const int64_t n_gather = (ncols1 == 1 ? std::min(Q->ne[1], 64/ncols2) : ncols1) * (int64_t) n_kv_max; - -- return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && -+ return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && dst->src[5] == nullptr && - mask != nullptr && n_kv_max > 0 && max_bias == 0.0f && logit_softcap == 0.0f && - mask->ne[0] == K->ne[1] && mask->ne[1] >= Q->ne[1] && mask->ne[2] == 1 && - K->ne[1] >= std::max(4096, 2*n_gather); -@@ -199,12 +199,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con - const ggml_tensor * V = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - -+ // with kv_rows the kernel iterates over the mask columns -+ const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; -+ - float max_bias = 0.0f; - memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); - - // Edge cases like no mask, ALiBi, unpadded K/V, or misaligned addresses for large data transfers - // are put into the template specialization without GQA optimizations. -- bool use_gqa_opt = mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ bool use_gqa_opt = mask && max_bias == 0.0f && n_kv % FATTN_KQ_STRIDE == 0; - for (const ggml_tensor * t : {Q, K, V, mask}) { - if (t == nullptr || ggml_is_quantized(t->type)) { - continue; -@@ -537,6 +540,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { - } - } - -+// The 576/512 MMA specialization reuses K for V; dimensions alone do not -+// establish the required alias for independently allocated K/V caches. -+static bool ggml_cuda_fattn_v_aliases_k(const ggml_tensor * K, const ggml_tensor * V) { -+ const bool same_view = V->view_src && -+ ((V->view_src == K && V->view_offs == 0) || -+ (K->view_src && V->view_src == K->view_src && V->view_offs == K->view_offs)); -+ const bool same_data = K->data && V->data && K->data == V->data; -+ if (K->data && V->data && !same_data) { -+ return false; -+ } -+ if ((!same_view && !same_data) || K->type != V->type || V->ne[0] > K->ne[0]) { -+ return false; -+ } -+ for (int i = 0; i < GGML_MAX_DIMS; ++i) { -+ if (K->nb[i] != V->nb[i] || (i != 0 && K->ne[i] != V->ne[i])) { -+ return false; -+ } -+ } -+ return true; -+} -+ - static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { - #ifndef FLASH_ATTN_AVAILABLE - GGML_UNUSED(device); GGML_UNUSED(dst); -@@ -549,15 +573,22 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const - const ggml_tensor * V = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - -+ const ggml_tensor * kv_rows = dst->src[5]; -+ -+ // with kv_rows the kernel iterates over the mask columns -+ const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1]; -+ - const int gqa_ratio = Q->ne[2] / K->ne[2]; - GGML_ASSERT(Q->ne[2] % K->ne[2] == 0); - - float max_bias = 0.0f; - memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); -+ float logit_softcap = 0.0f; -+ memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float)); - - // The effective batch size for the kernel can be increased by gqa_ratio. - // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded, -- bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && n_kv % FATTN_KQ_STRIDE == 0; - for (const ggml_tensor * t : {Q, K, V, mask}) { - if (t == nullptr || ggml_is_quantized(t->type)) { - continue; -@@ -629,6 +660,38 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const - return BEST_FATTN_KERNEL_NONE; - } - -+ // Match the actually compiled softcap variants before selecting a kernel. -+ const bool softcap_mma = K->ne[0] == 128 || K->ne[0] == 256 || K->ne[0] == 512; -+ if (logit_softcap != 0.0f && V->ne[0] != 128 && V->ne[0] != 256 && V->ne[0] != 512) { -+ return BEST_FATTN_KERNEL_NONE; -+ } -+ -+ // only the MMA kernel reads K/V through kv_rows -+ if (kv_rows) { -+ if (kv_rows->type != GGML_TYPE_I32 || !ggml_is_contiguous(kv_rows) || -+ kv_rows->ne[0] <= 0 || kv_rows->ne[0] > INT32_MAX || -+ kv_rows->ne[0] % FATTN_KQ_STRIDE != 0 || -+ kv_rows->ne[1] != Q->ne[3] || kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 || -+ !mask || mask->ne[0] != kv_rows->ne[0] || mask->ne[1] < Q->ne[1] || -+ K->ne[1] > INT32_MAX || K->ne[1] != V->ne[1] || K->ne[3] != 1 || V->ne[3] != 1 || -+ (logit_softcap != 0.0f && !softcap_mma) || -+ (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V))) { -+ return BEST_FATTN_KERNEL_NONE; -+ } -+ return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ? -+ BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE; -+ } -+ -+ if ((logit_softcap != 0.0f && !softcap_mma) || -+ (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V))) { -+ // The ordinary wide tile path has GQA4/GQA16 variants and reads V -+ // independently. Rows have no corresponding tile reader. -+ if (K->ne[0] == 576 && gqa_ratio % 4 != 0) { -+ return BEST_FATTN_KERNEL_NONE; -+ } -+ return BEST_FATTN_KERNEL_TILE; -+ } -+ - // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes: - // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. - const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; -diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp -index 54a6d166d..276bd007f 100644 ---- a/ggml/src/ggml-et/ggml-et.cpp -+++ b/ggml/src/ggml-et/ggml-et.cpp -@@ -1270,7 +1270,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm - case GGML_OP_FLASH_ATTN_EXT: - if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && - (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && -- (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && -+ (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr && - ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) { - float max_bias = 0.0f; - float logit_softcap = 0.0f; -diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp -index 08c15ff78..2b8cfb5e8 100644 ---- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp -+++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp -@@ -5180,6 +5180,11 @@ static bool ggml_hexagon_precompute_flash_attn_params( - return false; - } - -+ // K/V row lists are not supported by Hexagon. -+ if (op->src[5] != nullptr) { -+ return false; -+ } -+ - memset(kparams, 0, sizeof(*kparams)); - - const struct ggml_tensor * q = op->src[0]; -diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp -index 2c7972b0a..e94fae132 100644 ---- a/ggml/src/ggml-metal/ggml-metal-device.cpp -+++ b/ggml/src/ggml-metal/ggml-metal-device.cpp -@@ -1955,6 +1955,23 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( - return res; - } - -+ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( -+ ggml_metal_library_t lib, -+ const ggml_tensor * op) { -+ assert(op->op == GGML_OP_FLASH_ATTN_EXT); -+ -+ const char * base = "kernel_flash_attn_ext_rows"; -+ -+ ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, base); -+ if (!res.pipeline) { -+ res = ggml_metal_library_compile_pipeline(lib, base, base, nullptr); -+ } -+ -+ GGML_UNUSED(op); -+ -+ return res; -+} -+ - ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx( - ggml_metal_library_t lib, - const ggml_tensor * op) { -@@ -1984,6 +2001,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - bool has_scap, - bool has_kvpad, - bool has_sparse, -+ bool has_rows, - int32_t nqpsg, - int32_t ne, - int32_t nsg, -@@ -2013,7 +2031,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - dv, - qne_suffix); - -- snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", -+ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", - base, - has_mask, - has_sinks, -@@ -2021,6 +2039,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - has_scap, - has_kvpad, - has_sparse, -+ has_rows, - ns10, - ns20, - nsg, nwg); -@@ -2035,6 +2054,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_VEC + 3); - ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); - ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); -+ ggml_metal_cv_set_bool(cv, has_rows, FC_FLASH_ATTN_EXT_VEC + 6); - - ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); - ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); -diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h -index 4012b9d5f..7569a598f 100644 ---- a/ggml/src/ggml-metal/ggml-metal-device.h -+++ b/ggml/src/ggml-metal/ggml-metal-device.h -@@ -217,6 +217,10 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att - int32_t ns10, - int32_t ns20); - -+struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( -+ ggml_metal_library_t lib, -+ const struct ggml_tensor * op); -+ - struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx( - ggml_metal_library_t lib, - const struct ggml_tensor * op); -@@ -230,6 +234,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att - bool has_scap, - bool has_kvpad, - bool has_sparse, -+ bool has_rows, - int32_t nqpsg, - int32_t ne, - int32_t nsg, -diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index d1bce8bad..15a3ccb06 100644 ---- a/ggml/src/ggml-metal/ggml-metal-device.m -+++ b/ggml/src/ggml-metal/ggml-metal-device.m -@@ -1725,6 +1725,45 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te - case GGML_OP_ROLL: - return ggml_is_contiguous(op->src[0]); - case GGML_OP_FLASH_ATTN_EXT: -+ // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice -+ if (op->src[5] != NULL) { -+ const struct ggml_tensor * kv_rows = op->src[5]; -+ -+ if (kv_rows->type != GGML_TYPE_I32 || -+ !ggml_is_contiguous(kv_rows) || -+ kv_rows->ne[0] <= 0 || kv_rows->ne[0] > INT32_MAX || -+ kv_rows->ne[0] % OP_FLASH_ATTN_EXT_NCPSG != 0 || -+ kv_rows->ne[0] % OP_FLASH_ATTN_EXT_VEC_NCPSG != 0 || -+ kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 || -+ kv_rows->ne[1] != op->src[0]->ne[3] || -+ !op->src[3] || op->src[3]->ne[0] != kv_rows->ne[0] || -+ op->src[3]->ne[1] < op->src[0]->ne[1] || -+ op->src[1]->ne[1] > INT32_MAX || op->src[1]->ne[1] != op->src[2]->ne[1] || -+ op->src[1]->ne[3] != 1 || op->src[2]->ne[3] != 1) { -+ return false; -+ } -+ -+ // the non-vec kernels attend over a contiguous F16 copy of the referenced rows: -+ // - F16 K/V is gathered directly -+ // - quantized K/V is first dequantized with kernel_flash_attn_ext_kv_*_f16 -+ // - other types keep attending to the whole cache (dense mask) -+ switch (op->src[1]->type) { -+ case GGML_TYPE_F16: -+ case GGML_TYPE_Q4_0: -+ case GGML_TYPE_Q4_1: -+ case GGML_TYPE_Q5_0: -+ case GGML_TYPE_Q5_1: -+ case GGML_TYPE_Q8_0: -+ break; -+ default: -+ return false; -+ } -+ -+ // the row gather copies F16 values in groups of 4 -+ if (op->src[2]->ne[0] % 4 != 0) { -+ return false; -+ } -+ } - // for new head sizes, add checks here - if (op->src[0]->ne[0] != 32 && - op->src[0]->ne[0] != 40 && -diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h -index 4ffb5a77d..479c722d3 100644 ---- a/ggml/src/ggml-metal/ggml-metal-impl.h -+++ b/ggml/src/ggml-metal/ggml-metal-impl.h -@@ -383,6 +383,19 @@ typedef struct { - int32_t nblocks; - } ggml_metal_kargs_flash_attn_ext_kv_f16; - -+// gather the K/V cache rows referenced by the kv_rows lists into contiguous F16 buffers -+typedef struct { -+ int32_t ne11; // number of rows per list (n_kv_rows) -+ int32_t ne_12_2; // number of K/V heads -+ int32_t ne10; // DK -+ int32_t ne20; // DV, set to 0 to skip gathering V (V is a view of K) -+ uint64_t v_off; // byte offset of the gathered V region in dst -+ uint64_t nb11; // K source strides (ne13 = 1: the cache is shared by all streams) -+ uint64_t nb12; -+ uint64_t nb21; // V source strides (ne23 = 1) -+ uint64_t nb22; -+} ggml_metal_kargs_flash_attn_ext_rows; -+ - typedef struct { - int32_t ne11; - int32_t ne_12_2; // assume K and V are same shape -diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp -index 53c981618..55a9c5873 100644 ---- a/ggml/src/ggml-metal/ggml-metal-ops.cpp -+++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp -@@ -3165,7 +3165,10 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool - return false; - } - -- return op->src[1]->ne[1] % OP_FLASH_ATTN_EXT_TENSOR_NCPSG == 0; -+ // with kv_rows, the attention runs over the compacted row lists (padded to 256), not over the cache -+ const int64_t ne11_attn = op->src[5] ? op->src[5]->ne[0] : op->src[1]->ne[1]; -+ -+ return ne11_attn % OP_FLASH_ATTN_EXT_TENSOR_NCPSG == 0; - } - - // returns the n_kv_max hint if the sparse path is available for this op, or 0 otherwise -@@ -3174,6 +3177,11 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool - static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ // K/V row lists are handled by the dense kernels, not by the sparse path -+ if (op->src[5] != nullptr) { -+ return 0; -+ } -+ - int32_t n_kv_max = 0; - memcpy(&n_kv_max, ((const int32_t *) op->op_params) + 4, sizeof(n_kv_max)); - -@@ -3417,6 +3425,32 @@ size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { - return GGML_PAD(sizeof(int32_t)*(size_t) n_kv_max_padded*ne31*ne32*ne33, 16); - } - -+// size of the contiguous F16 buffers holding the K/V rows referenced by the kv_rows lists -+// the attention over these buffers is a standard dense op (no per-tile gather in the main kernel) -+size_t ggml_metal_op_flash_attn_ext_extra_rows(const ggml_tensor * op) { -+ assert(op->op == GGML_OP_FLASH_ATTN_EXT); -+ -+ const ggml_tensor * kv_rows = op->src[5]; -+ -+ if (!kv_rows) { -+ return 0; -+ } -+ -+ GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); -+ GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne); -+ -+ const int64_t n_rows = kv_rows->ne[0]; -+ const int64_t n_slices = kv_rows->ne[1]; -+ -+ // note: when V is a view of K, the gathered V is read from the gathered K, so only K is gathered -+ const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); -+ -+ const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*n_rows*ne12*n_slices, 16); -+ const size_t v_size = v_is_view_of_k ? 0 : GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne20*n_rows*ne22*n_slices, 16); -+ -+ return k_size + v_size; -+} -+ - int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_tensor * op = ctx->node(idx); - -@@ -3449,6 +3483,22 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - GGML_ASSERT(!op->src[3] || op->src[3]->ne[1] >= op->src[0]->ne[1] && - "the Flash-Attention Metal kernel requires the mask to be at least n_queries big"); - -+ // K/V row lists (ggml_flash_attn_ext_rows): src[5] holds one list of cache rows per q slice -+ // the attention loops then run over the mask columns and read K/V rows through the lists -+ const ggml_tensor * kv_rows = op->src[5]; -+ const bool has_rows = kv_rows != nullptr; -+ -+ GGML_ASSERT(!has_rows || (kv_rows->type == GGML_TYPE_I32 && ggml_is_contiguous(kv_rows))); -+ GGML_ASSERT(!has_rows || (kv_rows->ne[1] == ne03 && kv_rows->ne[2] == 1 && kv_rows->ne[3] == 1)); -+ GGML_ASSERT(!has_rows || op->src[3]); -+ -+ // the loop bound over the mask columns / K/V row lists -+ const int64_t ne11_attn = has_rows ? kv_rows->ne[0] : ne11; -+ -+ // the row lists are padded by the KV cache to a multiple of 256, so the pad path never triggers -+ GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_NCPSG == 0); -+ GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); -+ - float scale; - float max_bias; - float logit_softcap; -@@ -3463,6 +3513,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - const bool has_mask = op->src[3] != NULL; - const bool has_sinks = op->src[4] != NULL; -+ -+ GGML_ASSERT(!has_rows || has_mask); - const bool has_bias = max_bias != 0.0f; - const bool has_scap = logit_softcap != 0.0f; - -@@ -3499,12 +3551,25 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - const bool use_sparse = n_kv_max_sparse > 0; - const int n_kv_max_padded = use_sparse ? GGML_PAD(n_kv_max_sparse, OP_FLASH_ATTN_EXT_VEC_NCPSG) : 0; - -+ const bool use_vec = ggml_metal_op_flash_attn_ext_use_vec(op); -+ -+ // with kv_rows, the non-vec path gathers the referenced rows into a contiguous F16 buffer and -+ // attends over it with the F16 kernel - quantized KV is first dequantized with the F16 pass -+ const bool rows_gather = has_rows && !use_vec; -+ - // the vec kernels dequantize the KV inline; no need for the F16 dequant pass in the sparse path -- const bool use_kv_f16 = !use_sparse && ggml_metal_op_flash_attn_ext_use_kv_f16(op); -+ const bool dequant_kv = !use_sparse && (rows_gather ? -+ ggml_is_quantized(op->src[1]->type) : ggml_metal_op_flash_attn_ext_use_kv_f16(op)); -+ -+ const bool use_kv_f16 = !use_sparse && (rows_gather ? true : dequant_kv); - - ggml_metal_buffer_id bid_idx = bid_kv_f16; - bid_idx.offs += ggml_metal_op_flash_attn_ext_extra_kv_f16(op); - -+ // contiguous K/V buffers holding the rows referenced by the kv_rows lists -+ ggml_metal_buffer_id bid_rows = bid_idx; -+ bid_rows.offs += ggml_metal_op_flash_attn_ext_extra_idx(op); -+ - ggml_metal_buffer_id bid_k = bid_src1; - ggml_metal_buffer_id bid_v = bid_src2; - -@@ -3517,7 +3582,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - uint64_t nb22_attn = nb22; - uint64_t nb23_attn = nb23; - -- if (use_kv_f16) { -+ if (dequant_kv) { - assert(ggml_metal_op_flash_attn_ext_extra_kv_f16(op) != 0); - - const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); -@@ -3605,6 +3670,70 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - } - } - -+ // with kv_rows, gather the cache rows referenced by the lists into contiguous F16 buffers -+ // the attention then runs as a standard dense op over the gathered rows (tensor or half8x8 kernel) -+ if (rows_gather) { -+ assert(ggml_metal_op_flash_attn_ext_extra_rows(op) != 0); -+ -+ const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); -+ -+ GGML_ASSERT(ne20 % 4 == 0); -+ -+ const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*ne11_attn*ne12*ne03, 16); -+ -+ ggml_metal_kargs_flash_attn_ext_rows args0 = { -+ /*.ne11 =*/ (int32_t) ne11_attn, -+ /*.ne_12_2 =*/ ne12, -+ /*.ne10 =*/ ne10, -+ /*.ne20 =*/ v_is_view_of_k ? 0 : ne20, // the gathered V is a view of the gathered K -+ /*.v_off =*/ k_size, -+ /*.nb11 =*/ nb11_attn, -+ /*.nb12 =*/ nb12_attn, -+ /*.nb21 =*/ nb21_attn, -+ /*.nb22 =*/ nb22_attn, -+ }; -+ -+ auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_rows(lib, op); -+ const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline0), 64); -+ -+ ggml_metal_encoder_set_pipeline(enc, pipeline0); -+ ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); -+ ggml_metal_encoder_set_buffer (enc, bid_k, 1); -+ ggml_metal_encoder_set_buffer (enc, bid_v, 2); -+ ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(kv_rows), 3); -+ ggml_metal_encoder_set_buffer (enc, bid_rows, 4); -+ -+ ggml_metal_encoder_dispatch_threadgroups(enc, ne11_attn, ne03, 1, nth, 1, 1); -+ -+ ggml_metal_op_concurrency_reset(ctx); -+ -+ // contiguous F16 layout of the gathered rows: [DK, n_rows, n_head_kv, n_streams] -+ bid_k = bid_rows; -+ -+ nb10_attn = sizeof(ggml_fp16_t); -+ nb11_attn = nb10_attn*ne10; -+ nb12_attn = nb11_attn*ne11_attn; -+ nb13_attn = nb12_attn*ne12; -+ -+ // if V is a view of K, the gathered V is read from the gathered K with K's strides -+ if (v_is_view_of_k) { -+ bid_v = bid_k; -+ -+ nb20_attn = nb10_attn; -+ nb21_attn = nb11_attn; -+ nb22_attn = nb12_attn; -+ nb23_attn = nb13_attn; -+ } else { -+ bid_v = bid_rows; -+ bid_v.offs += k_size; -+ -+ nb20_attn = sizeof(ggml_fp16_t); -+ nb21_attn = nb20_attn*ne20; -+ nb22_attn = nb21_attn*ne11_attn; -+ nb23_attn = nb22_attn*ne22; -+ } -+ } -+ - if (!use_sparse && ggml_metal_op_flash_attn_ext_use_tensor(op, props_dev->has_tensor)) { - // tensor API kernel - const int nqptg = ne00 >= 512 ? OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE : OP_FLASH_ATTN_EXT_TENSOR_NQPSG; // queries per threadgroup -@@ -3650,9 +3779,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.nb01 =*/ nb01, - /*.nb02 =*/ nb02, - /*.nb03 =*/ nb03, -- /*.ne11 =*/ ne11, -+ /*.ne11 =*/ (int32_t) ne11_attn, - /*.ne_12_2 =*/ ne12, -- /*.ne_12_3 =*/ ne13, -+ /*.ne_12_3 =*/ has_rows ? ne03 : ne13, // the gathered K/V holds one copy per stream - /*.ns10 =*/ ns10, - /*.nb11 =*/ nb11_attn, - /*.nb12 =*/ nb12_attn, -@@ -3710,7 +3839,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - bool need_sync = false; - -- const bool has_kvpad = ne11 % ncpsg != 0; -+ const bool has_kvpad = ne11_attn % ncpsg != 0; - - if (has_kvpad) { - assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); -@@ -3810,9 +3939,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.nb01 =*/ nb01, - /*.nb02 =*/ nb02, - /*.nb03 =*/ nb03, -- /*.ne11 =*/ ne11, -+ /*.ne11 =*/ (int32_t) ne11_attn, - /*.ne_12_2 =*/ ne12, -- /*.ne_12_3 =*/ ne13, -+ /*.ne_12_3 =*/ has_rows ? ne03 : ne13, // the gathered K/V holds one copy per stream - /*.ns10 =*/ ns10, - /*.nb11 =*/ nb11_attn, - /*.nb12 =*/ nb12_attn, -@@ -3878,7 +4007,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - bool need_sync = false; - -- const bool has_kvpad = !use_sparse && ne11 % ncpsg != 0; -+ const bool has_kvpad = !use_sparse && ne11_attn % ncpsg != 0; - - if (use_sparse) { - assert(ggml_metal_op_flash_attn_ext_extra_idx(op) != 0); -@@ -3961,13 +4090,13 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - // queries: Q*NSG*PAD2(ne00, 128) - // attn + mask: NSG*4*Q*C - // results: 2*NSG*Q*PAD2(ne20, 128) -- // sparse idx: NSG*C ints (only when use_sparse) -+ // sparse idx: NSG*C ints (when use_sparse, or when gathering K/V rows) - const int64_t dk_pad = GGML_PAD(ne00, 128); - const int64_t dv_pad = GGML_PAD(ne20, 128); - - auto fa_vec_smem = [&](int64_t nsg, int32_t nqptg) -> size_t { - const size_t smem_half = (size_t) (dk_pad + 4*ncpsg + 2*dv_pad)*nqptg*nsg; -- return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + (use_sparse ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); -+ return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + ((use_sparse || has_rows) ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); - }; - - int64_t nsg = 1; -@@ -3998,7 +4127,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - } else { - nwg = 32; - nsg = 1; -- while (2*nwg*nsg*ncpsg < ne11 && nsg < 4) { -+ while (2*nwg*nsg*ncpsg < ne11_attn && nsg < 4) { - nsg *= 2; - } - } -@@ -4019,7 +4148,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.nb01 =*/ nb01, - /*.nb02 =*/ nb02, - /*.nb03 =*/ nb03, -- /*.ne11 =*/ use_sparse ? n_kv_max_padded : ne11, -+ /*.ne11 =*/ use_sparse ? n_kv_max_padded : (int32_t) ne11_attn, - /*.ne_12_2 =*/ ne12, - /*.ne_12_3 =*/ ne13, - /*.ns10 =*/ ns10, -@@ -4048,7 +4177,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.n_kv_max_padded =*/ n_kv_max_padded, - }; - -- auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); -+ auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); - - GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); - -@@ -4059,7 +4188,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_metal_encoder_set_buffer (enc, bid_v, 3); - ggml_metal_encoder_set_buffer (enc, bid_src3, 4); - ggml_metal_encoder_set_buffer (enc, bid_src4, 5); -- ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : bid_src0, 8); -+ ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : (has_rows ? ggml_metal_get_buffer_id(kv_rows) : bid_src0), 8); - - const size_t smem = fa_vec_smem(nsg, nqptg); - -diff --git a/ggml/src/ggml-metal/ggml-metal-ops.h b/ggml/src/ggml-metal/ggml-metal-ops.h -index 583d1156b..bed325743 100644 ---- a/ggml/src/ggml-metal/ggml-metal-ops.h -+++ b/ggml/src/ggml-metal/ggml-metal-ops.h -@@ -46,6 +46,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_blk(const struct ggml_tensor * op); - size_t ggml_metal_op_flash_attn_ext_extra_tmp(const struct ggml_tensor * op); - size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const struct ggml_tensor * op); - size_t ggml_metal_op_flash_attn_ext_extra_idx(const struct ggml_tensor * op); -+size_t ggml_metal_op_flash_attn_ext_extra_rows(const struct ggml_tensor * op); - - int ggml_metal_op_concat (ggml_metal_op_t ctx, int idx); - int ggml_metal_op_repeat (ggml_metal_op_t ctx, int idx); -diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp -index 344882e04..cab2fbf99 100644 ---- a/ggml/src/ggml-metal/ggml-metal.cpp -+++ b/ggml/src/ggml-metal/ggml-metal.cpp -@@ -235,6 +235,7 @@ static size_t ggml_backend_metal_buffer_type_get_alloc_size(ggml_backend_buffer_ - res += ggml_metal_op_flash_attn_ext_extra_tmp(tensor); - res += ggml_metal_op_flash_attn_ext_extra_kv_f16(tensor); - res += ggml_metal_op_flash_attn_ext_extra_idx(tensor); -+ res += ggml_metal_op_flash_attn_ext_extra_rows(tensor); - } break; - case GGML_OP_CUMSUM: - case GGML_OP_ARGSORT: -diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal -index ebee1becd..06fe0a86c 100644 ---- a/ggml/src/ggml-metal/kernels/fa_aux.metal -+++ b/ggml/src/ggml-metal/kernels/fa_aux.metal -@@ -48,6 +48,82 @@ template [[host_name("kernel_flash_attn_ext_kv_q5_0_f16")]] kernel kernel_flash_ - template [[host_name("kernel_flash_attn_ext_kv_q5_1_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; - template [[host_name("kernel_flash_attn_ext_kv_q8_0_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; - -+// gather the K/V cache rows referenced by the kv_rows lists into contiguous F16 buffers -+// - one threadgroup per (row, stream); the attention is then run as a standard dense op over the -+// gathered rows, which avoids the per-tile K/V gather in the main kernels -+// - negative rows are padding: filled with zeros, their mask entries are -INF so they contribute nothing -+kernel void kernel_flash_attn_ext_rows( -+ constant ggml_metal_kargs_flash_attn_ext_rows & args, -+ device const char * k_src, -+ device const char * v_src, -+ device const int * rows, -+ device char * dst, -+ uint3 tgpig[[threadgroup_position_in_grid]], -+ ushort tiitg[[thread_index_in_threadgroup]], -+ ushort3 ntg[[threads_per_threadgroup]]) { -+ const int64_t i1 = tgpig[0]; // row index -+ const int64_t i3 = tgpig[1]; // stream -+ -+ const int64_t row = rows[i1 + i3*args.ne11]; -+ -+ // gathered layout: [DK, n_rows, n_head_kv, n_streams] and [DV, n_rows, n_head_kv, n_streams] F16 -+ device half4 * k_dst = (device half4 *) (dst + i3*args.ne_12_2*args.ne11*args.ne10*sizeof(half)); -+ device half4 * v_dst = (device half4 *) (dst + args.v_off + i3*args.ne_12_2*args.ne11*args.ne20*sizeof(half)); -+ -+ // note: the K/V cache is shared by all streams (ne13 = ne23 = 1), the row list selects the rows -+ // each thread copies up to 4 half4 values (32 bytes) to keep the memory transactions large -+ -+ // K: all heads of this row -+ { -+ const int64_t per_head = args.ne10/4; -+ const int64_t chunks_per_head = (per_head + 3)/4; -+ -+ for (int64_t i = tiitg; i < args.ne_12_2*chunks_per_head; i += ntg.x) { -+ const int64_t i2 = i/chunks_per_head; -+ const int64_t i0 = 4*(i%chunks_per_head); -+ const int n = (int) min((int64_t) 4, per_head - i0); -+ -+ device half4 * dst4 = k_dst + (i2*args.ne11 + i1)*per_head + i0; -+ -+ if (row >= 0) { -+ device const half4 * src4 = (device const half4 *) (k_src + row*args.nb11 + i2*args.nb12) + i0; -+ for (int j = 0; j < n; ++j) { -+ dst4[j] = src4[j]; -+ } -+ } else { -+ for (int j = 0; j < n; ++j) { -+ dst4[j] = half4(0.0h); -+ } -+ } -+ } -+ } -+ -+ // V: all heads of this row -+ { -+ const int64_t per_head = args.ne20/4; -+ const int64_t chunks_per_head = (per_head + 3)/4; -+ -+ for (int64_t i = tiitg; i < args.ne_12_2*chunks_per_head; i += ntg.x) { -+ const int64_t i2 = i/chunks_per_head; -+ const int64_t i0 = 4*(i%chunks_per_head); -+ const int n = (int) min((int64_t) 4, per_head - i0); -+ -+ device half4 * dst4 = v_dst + (i2*args.ne11 + i1)*per_head + i0; -+ -+ if (row >= 0) { -+ device const half4 * src4 = (device const half4 *) (v_src + row*args.nb21 + i2*args.nb22) + i0; -+ for (int j = 0; j < n; ++j) { -+ dst4[j] = src4[j]; -+ } -+ } else { -+ for (int j = 0; j < n; ++j) { -+ dst4[j] = half4(0.0h); -+ } -+ } -+ } -+ } -+} -+ - constant bool FC_flash_attn_ext_pad_has_mask [[function_constant(FC_FLASH_ATTN_EXT_PAD + 0)]]; - - constant int32_t FC_flash_attn_ext_pad_ncpsg [[function_constant(FC_FLASH_ATTN_EXT_PAD + 25)]]; -diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal -index 46270ba4b..c81e4d09b 100644 ---- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal -+++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal -@@ -13,6 +13,7 @@ constant int32_t FC_flash_attn_ext_vec_ns20 [[function_constant(FC_FLASH_ATTN_EX - constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 22)]]; - constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; - constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; -+constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; - template< - typename q4_t, // query types in shared memory - typename k4_t, // key types in shared memory -@@ -90,7 +91,8 @@ kernel void kernel_flash_attn_ext_vec( - threadgroup o4_t * so4 = (threadgroup o4_t *) (shmem_f16 + SMEM_Q + SMEM_S + 2*sgitg*Q*PV); // scratch buffer for the results - - // sparse indices for the current block -- threadgroup int * spidx = FC_flash_attn_ext_vec_has_sparse -+ // note: with kv_rows, the buffer holds the row list of the current slice instead -+ threadgroup int * spidx = (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) - ? (threadgroup int *) (shmem_f16 + SMEM) + sgitg*C - : nullptr; - -@@ -165,6 +167,12 @@ kernel void kernel_flash_attn_ext_vec( - ((int64_t)(iq3%args.ne33)*args.ne32 + (iq2%args.ne32))*args.ne31*args.n_kv_max_padded + (iq1%args.ne31)*args.n_kv_max_padded; - } - -+ // K/V row list of the current slice (ggml_flash_attn_ext_rows) -+ // with kv_rows, the loop below runs over the mask columns (args.ne11) and the K/V cache rows -+ // are read indirectly through the list. negative entries are padding, their mask is -INF -+ device const int * rows_list = FC_flash_attn_ext_vec_has_rows ? -+ (device const int *) idx + (int64_t)(iq3%args.ne33)*args.ne11 : nullptr; -+ - float slope = 1.0f; - - // ALiBi -@@ -222,12 +230,12 @@ kernel void kernel_flash_attn_ext_vec( - ic = 0; - } - -- // load the sparse KV indices for the current block into shared memory -- if (FC_flash_attn_ext_vec_has_sparse) { -+ // load the KV row indices for the current block into shared memory -+ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { - FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { - const short i = ii*NW + tiisg; - -- spidx[i] = pidx[ic + i]; -+ spidx[i] = FC_flash_attn_ext_vec_has_rows ? rows_list[ic + i] : pidx[ic + i]; - } - simdgroup_barrier(mem_flags::mem_threadgroup); - } -@@ -242,6 +250,15 @@ kernel void kernel_flash_attn_ext_vec( - sm[qq*C + tiisg] = -MAXHALF; - } - } -+ } else if (FC_flash_attn_ext_vec_has_rows) { -+ // the mask is compact: column ic maps to cache row spidx[tiisg] -+ FOR_UNROLL (short qq = 0; qq < Q; ++qq) { -+ if ((iq1*Q + qq) < args.ne01) { -+ sm[qq*C + tiisg] = pm[qq][ic + tiisg]; -+ } else { -+ sm[qq*C + tiisg] = -MAXHALF; -+ } -+ } - } else { - FOR_UNROLL (short qq = 0; qq < Q; ++qq) { - if ((iq1*Q + qq) < args.ne01) { -@@ -276,7 +293,7 @@ kernel void kernel_flash_attn_ext_vec( - { - device const k4_t * pk4 = nullptr; - -- if (!FC_flash_attn_ext_vec_has_sparse) { -+ if (!FC_flash_attn_ext_vec_has_sparse && !FC_flash_attn_ext_vec_has_rows) { - pk4 = (device const k4_t *) (k + ic*args.nb11); - - pk4 += ty*NS10/4 + tx; -@@ -291,7 +308,7 @@ kernel void kernel_flash_attn_ext_vec( - - // each simdgroup processes Q queries and NE (NW/NL) cache elements - FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { -- if (FC_flash_attn_ext_vec_has_sparse) { -+ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { - // the KV rows are gathered from the index list; -1 entries are padding - const int i11 = spidx[NE*cc + ty]; - if (i11 >= 0) { -@@ -434,7 +451,7 @@ kernel void kernel_flash_attn_ext_vec( - } - } - -- if (FC_flash_attn_ext_vec_has_sparse) { -+ if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { - FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { - // the KV rows are gathered from the index list; -1 entries are padding - const int i11 = spidx[NE*cc + ty]; -diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp -index 17ceacc7a..bb92e6c1e 100644 ---- a/ggml/src/ggml-opencl/ggml-opencl.cpp -+++ b/ggml/src/ggml-opencl/ggml-opencl.cpp -@@ -9402,6 +9402,10 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te - case GGML_OP_MEAN: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_FLASH_ATTN_EXT: { -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ if (op->src[5] != nullptr) { -+ return false; -+ } - #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { - return true; -diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp -index 22b2f45e2..67b2e1f9f 100644 ---- a/ggml/src/ggml-openvino/ggml-openvino.cpp -+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp -@@ -1513,6 +1513,11 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { - return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"}; - } - -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ if (op->src[5] != nullptr) { -+ return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"}; -+ } -+ - if (op->src[4] != nullptr) { - return {false, "FLASH_ATTN_EXT with sinks is not supported"}; - } -diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp -index 6759af0ed..ebd0bd09b 100644 ---- a/ggml/src/ggml-sycl/ggml-sycl.cpp -+++ b/ggml/src/ggml-sycl/ggml-sycl.cpp -@@ -7178,7 +7178,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons - case GGML_OP_SOLVE_TRI: - return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; - case GGML_OP_FLASH_ATTN_EXT: -- return ggml_sycl_flash_attn_ext_supported(device, op); -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); - default: - return false; - } -diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp -index 436bfe3bb..682c21b01 100644 ---- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp -+++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp -@@ -15569,6 +15569,10 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm - } - case GGML_OP_FLASH_ATTN_EXT: - { -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ if (op->src[5] != nullptr) { -+ return false; -+ } - bool coopmat2 = device->coopmat2; - uint32_t HSK = op->src[1]->ne[0]; - uint32_t HSV = op->src[2]->ne[0]; -diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp -index 15e6c784b..9bcf2d981 100644 ---- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp -+++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp -@@ -4580,7 +4580,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const - { - // conservative support checks for whether the more resource-intensive shader paths - // can be used, to avoid cases where flash_attn is assigned to the CPU later on -- supports_op = src0->type == GGML_TYPE_F32 && -+ // K/V row lists (ggml_flash_attn_ext_rows) are not supported -+ supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 && - (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || - src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && - (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || -diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c -index 01dc8d05c..7935876fc 100644 ---- a/ggml/src/ggml.c -+++ b/ggml/src/ggml.c -@@ -5516,20 +5516,37 @@ struct ggml_tensor * ggml_arange( - - // ggml_flash_attn_ext - --struct ggml_tensor * ggml_flash_attn_ext( -+static struct ggml_tensor * ggml_flash_attn_ext_impl( - struct ggml_context * ctx, - struct ggml_tensor * q, - struct ggml_tensor * k, - struct ggml_tensor * v, - struct ggml_tensor * mask, -+ struct ggml_tensor * kv_rows, - float scale, - float max_bias, - float logit_softcap) { - GGML_ASSERT(ggml_can_mul_mat(k, q)); - // TODO: check if vT can be multiplied by (k*qT) - -- GGML_ASSERT(q->ne[3] == k->ne[3]); -- GGML_ASSERT(q->ne[3] == v->ne[3]); -+ if (kv_rows) { -+ // k and v are shared by all q slices, kv_rows picks the rows of each slice -+ GGML_ASSERT(mask && mask->ne[0] == kv_rows->ne[0]); -+ GGML_ASSERT(mask->ne[1] >= q->ne[1]); -+ GGML_ASSERT(kv_rows->type == GGML_TYPE_I32 && ggml_is_contiguous(kv_rows)); -+ GGML_ASSERT(kv_rows->ne[0] > 0 && kv_rows->ne[0] <= INT32_MAX); -+ GGML_ASSERT(kv_rows->ne[1] == q->ne[3] && kv_rows->ne[2] == 1 && kv_rows->ne[3] == 1); -+ GGML_ASSERT(k->ne[1] > 0 && k->ne[1] <= INT32_MAX && k->ne[1] == v->ne[1]); -+ GGML_ASSERT(k->ne[2] == v->ne[2]); -+ GGML_ASSERT(q->nb[0] == ggml_type_size(q->type)); -+ GGML_ASSERT(k->nb[0] == ggml_type_size(k->type)); -+ GGML_ASSERT(v->nb[0] == ggml_type_size(v->type)); -+ GGML_ASSERT(k->ne[3] == 1); -+ GGML_ASSERT(v->ne[3] == 1); -+ } else { -+ GGML_ASSERT(q->ne[3] == k->ne[3]); -+ GGML_ASSERT(q->ne[3] == v->ne[3]); -+ } - - if (mask) { - GGML_ASSERT(mask->type == GGML_TYPE_F16); -@@ -5556,10 +5573,36 @@ struct ggml_tensor * ggml_flash_attn_ext( - result->src[1] = k; - result->src[2] = v; - result->src[3] = mask; -+ result->src[5] = kv_rows; - - return result; - } - -+struct ggml_tensor * ggml_flash_attn_ext( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, -+ struct ggml_tensor * k, -+ struct ggml_tensor * v, -+ struct ggml_tensor * mask, -+ float scale, -+ float max_bias, -+ float logit_softcap) { -+ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, NULL, scale, max_bias, logit_softcap); -+} -+ -+struct ggml_tensor * ggml_flash_attn_ext_rows( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, -+ struct ggml_tensor * k, -+ struct ggml_tensor * v, -+ struct ggml_tensor * mask, -+ struct ggml_tensor * kv_rows, -+ float scale, -+ float max_bias, -+ float logit_softcap) { -+ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, kv_rows, scale, max_bias, logit_softcap); -+} -+ - - void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, diff --git a/include/llama.h b/include/llama.h index 428f51f8d..8e39fdf48 100644 --- a/include/llama.h @@ -1508,91 +121,6 @@ index 3b8f45d26..cd34e36a9 100644 LLM_KV_ATTENTION_INDEXER_BLOCK_SIZE, LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, LLM_KV_ATTENTION_INDEXER_TYPES, -diff --git a/src/llama-context-kv-rows.cpp b/src/llama-context-kv-rows.cpp -new file mode 100644 -index 000000000..463e53a9d ---- /dev/null -+++ b/src/llama-context-kv-rows.cpp -@@ -0,0 +1,79 @@ -+#include "llama-context.h" -+ -+#include "llama-graph.h" -+#include "llama-impl.h" -+ -+#include -+#include -+#include -+ -+void llama_context::resolve_fused_kv_rows( -+ const llama_memory_context_i * mctx, -+ uint32_t n_seqs, -+ const skippy_graph_build_inputs & graph_build_inputs) { -+ cparams.fused_kv_rows = false; -+ if (!cparams.flash_attn || !cparams.kv_unified) { -+ return; -+ } -+ -+ // Resolve the same one-token-per-owner shape as the upstream row probe, -+ // but compare to actual ordinary attention placement, not weight placement. -+ // In particular --no-kv-offload and filtered stages need not share their -+ // weight layer's device. Only stable backend handles survive the re-reserve. -+ using Key = std::pair; -+ std::map ordinary; -+ auto reserve = [&]() { -+ if (!graph_reserve(n_seqs, n_seqs, n_seqs, mctx, true, nullptr, graph_build_inputs)) { -+ throw std::runtime_error("failed to reserve graph for Flash Attention over K/V rows check"); -+ } -+ }; -+ reserve(); -+ std::map ordinals; -+ for (const auto & node : get_gf_res_reserve()->get_fused_nodes()) { -+ if (node.op == LLM_FUSED_OP_FLASH_ATTN) { -+ const auto backend = ggml_backend_sched_get_tensor_backend(sched.get(), node.tensor); -+ if (!backend || node.il < 0) { -+ return; -+ } -+ ordinary.emplace(Key{node.il, ordinals[node.il]++}, backend); -+ } -+ } -+ if (ordinary.empty()) { -+ return; -+ } -+ -+ try { -+ cparams.fused_kv_rows = true; -+ reserve(); -+ ordinals.clear(); -+ size_t observed = 0, row_nodes = 0; -+ bool same_backends = true; -+ for (const auto & node : get_gf_res_reserve()->get_fused_nodes()) { -+ if (node.op != LLM_FUSED_OP_FLASH_ATTN && node.op != LLM_FUSED_OP_FLASH_ATTN_KV_ROWS) { -+ continue; -+ } -+ const Key key{node.il, ordinals[node.il]++}; -+ const auto previous = ordinary.find(key); -+ const auto actual = ggml_backend_sched_get_tensor_backend(sched.get(), node.tensor); -+ same_backends &= previous != ordinary.end() && actual && previous->second == actual; -+ row_nodes += node.op == LLM_FUSED_OP_FLASH_ATTN_KV_ROWS; -+ ++observed; -+ } -+ cparams.fused_kv_rows = same_backends && observed == ordinary.size() && row_nodes > 0; -+ } catch (...) { -+ // Restore the ordinary graph before propagating the original probe -+ // failure. If even ordinary reservation fails, construction fails -+ // closed; no partially checked row graph is executable. -+ cparams.fused_kv_rows = false; -+ reserve(); -+ throw; -+ } -+ if (!cparams.fused_kv_rows) { -+ // Leave the scheduler with the ordinary graph now, rather than relying -+ // on a later worst-case reserve to remove the rejected row graph. -+ reserve(); -+ LLAMA_LOG_INFO("%s: K/V rows unavailable on ordinary attention backends, keeping ordinary graph\n", __func__); -+ } else { -+ LLAMA_LOG_INFO("%s: K/V rows enabled on ordinary attention backends\n", __func__); -+ } -+} diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 9011bef0d..42aa95c19 100644 --- a/src/llama-context.cpp @@ -2780,1975 +1308,183 @@ index 39c5619df..12771e390 100644 void sched_reserve(); + void sched_reserve(const skippy_graph_build_inputs & graph_build_inputs); - void synchronize(); - - const llama_model & get_model() const; - const llama_cparams & get_cparams() const; -+ const skippy_graph_build_inputs & get_graph_build_inputs() const; -+ uint64_t get_sched_reserve_count() const; -+#ifdef LLAMA_STAGE_BUILD_TESTS -+ void set_fused_gdn_for_test(bool fused_ar, bool fused_chunk); -+#endif - - ggml_backend_sched_t get_sched() const; - -@@ -69,6 +99,7 @@ struct llama_context { - uint32_t n_ctx_seq() const; - uint32_t n_batch() const; - uint32_t n_ubatch() const; -+ bool kv_unified() const; - uint32_t n_seq_max() const; - - uint32_t n_threads() const; -@@ -78,6 +109,7 @@ struct llama_context { - - // return true if the memory was updated - bool memory_update(bool optimize); -+ bool memory_update(bool optimize, const skippy_graph_build_inputs & graph_build_inputs); - - enum llama_pooling_type pooling_type() const; - -@@ -149,14 +181,19 @@ struct llama_context { - const llama_ubatch & ubatch, - llm_graph_type gtype, - llama_memory_context_i * mctx, -- ggml_status & ret); -+ ggml_status & ret, -+ const skippy_graph_build_inputs & graph_build_inputs = {}); - - int encode(const llama_batch_ext & batch_inp); -+ int encode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - int decode(const llama_batch_ext & batch_inp); -+ int decode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - - // compat version - int encode(const llama_batch & batch_inp); -+ int encode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - int decode(const llama_batch & batch_inp); -+ int decode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - - // - // state save/load -@@ -263,13 +300,34 @@ public: - - // can reuse the llm_graph_result instance of the context (for example to update a memory module) - llm_graph_result * get_gf_res_reserve() const; -+ uint32_t admit_skippy_cache_capabilities(uint32_t memory_capabilities) { -+ if (!skippy_cache_admission_bound) { -+ skippy_cache_admitted_capabilities = skippy_cache_profile_seen -+ ? skippy_cache_capabilities & memory_capabilities : 0; -+ skippy_cache_admission_bound = true; -+ } -+ return skippy_cache_admitted_capabilities; -+ } -+ // live graph result of the most recent schedule, or null before the first build -+ llm_graph_result * get_gf_res_prev_active() const; - - // returns the result of ggml_backend_sched_graph_compute_async execution - ggml_status graph_compute(ggml_cgraph * gf, bool batched); - - // reserve a graph with a dummy ubatch of the specified size -- ggml_cgraph * graph_reserve( -- uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only = false, size_t * sizes = nullptr); -+ ggml_cgraph * graph_reserve(uint32_t n_tokens, -+ uint32_t n_seqs, -+ uint32_t n_outputs, -+ const llama_memory_context_i * mctx, -+ bool split_only = false, -+ size_t * sizes = nullptr, -+ const skippy_graph_build_inputs & graph_build_inputs = {}, -+ bool embedding_input = false); -+ -+ bool get_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; -+ bool get_input_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; -+ bool get_activation_frontier(std::vector & parts) const; -+ bool get_input_activation_frontier(std::vector & parts) const; - - bool set_sampler(llama_seq_id seq_id, llama_sampler * sampler); - -@@ -280,7 +338,8 @@ private: - llm_graph_result * res, - const llama_ubatch & ubatch, - const llama_memory_context_i * mctx, -- llm_graph_type gtype) const; -+ llm_graph_type gtype, -+ const skippy_graph_build_inputs & graph_build_inputs = {}) const; - - llm_graph_cb graph_get_cb() const; - -@@ -295,7 +354,10 @@ private: - - // disable auto fused ops (Flash Attention, Gated Delta Net) whose op lands on a device - // that differs from the layer it belongs to (usually due to missing backend support) -- void resolve_fused_ops(const llama_memory_context_i * mctx, uint32_t n_seqs); -+ void resolve_fused_ops( -+ const llama_memory_context_i * mctx, -+ uint32_t n_seqs, -+ const skippy_graph_build_inputs & graph_build_inputs); -+ -+ void resolve_fused_kv_rows( -+ const llama_memory_context_i * mctx, -+ uint32_t n_seqs, -+ const skippy_graph_build_inputs & graph_build_inputs); - - // TODO: read/write lora adapters and cvec - size_t state_write_data(llama_io_write_i & io); -@@ -312,6 +374,10 @@ private: - - llama_cparams cparams; - -+ const skippy_graph_build_inputs graph_build_inputs; -+ uint64_t computation_generation = 0; -+ -+ - llama_adapter_cvec_ptr cvec; - llama_adapter_loras_ptr loras; - -@@ -378,6 +444,7 @@ private: - ggml_backend_sched_ptr sched; - - bool sched_need_reserve = true; -+ uint64_t sched_reserve_count = 0; - - // whether the reserve graph has a logits tensor, set in sched_reserve() - // true until then, because the first output_reserve() runs before any graph is reserved -@@ -425,9 +492,32 @@ private: - // Separate arenas give batches with and without outputs distinct CUDA graph cache keys. - std::array gf_res_prev; - llm_graph_result_ptr gf_res_reserve; -+ // Intersect every reserved prefill/decode profile; no configuration can authorize state coverage. -+ uint32_t skippy_cache_capabilities = UINT32_MAX; -+ bool skippy_cache_profile_seen = false; -+ uint32_t skippy_cache_admitted_capabilities = 0; -+ bool skippy_cache_admission_bound = false; - - llm_graph_result * gf_res_prev_active = nullptr; - -+ bool activation_boundary_observed = false; -+ bool activation_boundary_stable = true; -+ enum ggml_type activation_boundary_type = GGML_TYPE_COUNT; -+ uint64_t activation_boundary_elements_per_token = 0; -+ uint64_t activation_boundary_bytes_per_token = 0; -+ -+ bool input_activation_boundary_observed = false; -+ bool input_activation_boundary_stable = true; -+ enum ggml_type input_activation_boundary_type = GGML_TYPE_COUNT; -+ uint64_t input_activation_boundary_elements_per_token = 0; -+ uint64_t input_activation_boundary_bytes_per_token = 0; -+ bool activation_frontier_observed = false; -+ bool activation_frontier_stable = true; -+ std::vector activation_frontier; -+ bool input_activation_frontier_observed = false; -+ bool input_activation_frontier_stable = true; -+ std::vector input_activation_frontier; -+ - // host buffer for the model output (logits and embeddings) - ggml_backend_buffer_ptr buf_output; - -diff --git a/src/llama-cparams.h b/src/llama-cparams.h -index f4eb181a7..3705569fc 100644 ---- a/src/llama-cparams.h -+++ b/src/llama-cparams.h -@@ -39,6 +39,8 @@ struct llama_cparams { - bool offload_kqv; - bool flash_attn; - bool auto_fa; -+ bool fused_kv_rows; // backend-probed unified per-owner attention rows -+ bool auto_fkvr; - bool fused_gdn_ar; // use fused gated delta net (autoregressive) - bool fused_gdn_ch; // use fused gated delta net (chunked) - bool auto_fgdn; -diff --git a/src/llama-ext.h b/src/llama-ext.h -index b55c0c357..9449e1da7 100644 ---- a/src/llama-ext.h -+++ b/src/llama-ext.h -@@ -75,6 +75,12 @@ LLAMA_API bool llama_quant_tensor_allows_quantization( - const quantize_state_impl * qs, - const ggml_tensor * tensor); - -+// Returns whether the selected tensor type requires importance weights. -+LLAMA_API bool llama_quant_tensor_requires_imatrix( -+ const ggml_tensor * tensor, -+ ggml_type type, -+ llama_ftype ftype); -+ - // Compute quantization type assignments for a list of tensors. - // All tensors should be quantizable (use llama_quant_tensor_allows_quantization to filter). - // result_types: caller-allocated array of n_tensors elements, filled with assigned types. -diff --git a/src/llama-graph-kv-rows.cpp b/src/llama-graph-kv-rows.cpp -new file mode 100644 -index 000000000..5da812201 ---- /dev/null -+++ b/src/llama-graph-kv-rows.cpp -@@ -0,0 +1,124 @@ -+#include "llama-graph.h" -+ -+#include "llama-cparams.h" -+#include "llama-kv-cache.h" -+#include "llama-kv-cache-iswa.h" -+#include "ggml-backend.h" -+ -+bool llm_graph_context::supports_row_attn(const ggml_tensor * node, const ggml_tensor * storage) const { -+ while (storage->view_src) { -+ storage = storage->view_src; -+ } -+ if (storage->buffer) { -+ const auto type = ggml_backend_buffer_get_type(storage->buffer); -+ const auto device = ggml_backend_buft_get_device(type); -+ if (device) { -+ return ggml_backend_dev_supports_op(device, node); -+ } -+ // Host storage may use the scheduler's existing CPU backend. Never -+ // redirect unsupported GPU-owned storage through a CPU pool copy. -+ if (!ggml_backend_buft_is_host(type) || !sched) { -+ return false; -+ } -+ for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { -+ const auto backend = ggml_backend_sched_get_backend(sched, i); -+ const auto device_cpu = ggml_backend_get_device(backend); -+ if (device_cpu && ggml_backend_dev_type(device_cpu) == GGML_BACKEND_DEVICE_TYPE_CPU && -+ ggml_backend_supports_op(backend, node)) { -+ return true; -+ } -+ } -+ return false; -+ } -+ return sched && ggml_backend_sched_get_n_backends(sched) > 0 && -+ ggml_backend_supports_op(ggml_backend_sched_get_backend(sched, 0), node); -+} -+ -+namespace { -+ -+void build_pool_row_inputs( -+ ggml_context * ctx, const llama_ubatch & ubatch, const llama_cparams & params, -+ const llama_kv_cache_context * mctx, ggml_tensor * & row_input, ggml_tensor * & mask_input, -+ uint32_t & physical_extent, const char * row_name, const char * mask_name) { -+ if (!params.flash_attn || !params.fused_kv_rows || params.training) { -+ return; -+ } -+ const uint32_t rows = mctx->get_n_kv_rows(); -+ const uint32_t slices = llama_kv_cache::get_n_kv_slices(ubatch); -+ if (!rows || rows % 256 != 0 || !slices) { -+ return; -+ } -+ physical_extent = mctx->get_n_kv(); -+ row_input = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, rows, slices); -+ mask_input = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, rows, ubatch.n_tokens / slices, 1, slices); -+ ggml_set_input(row_input); -+ ggml_set_input(mask_input); -+ ggml_set_name(row_input, row_name); -+ ggml_set_name(mask_input, mask_name); -+} -+ -+bool can_reuse_pool_row_inputs( -+ const llama_ubatch & ubatch, const llama_cparams & params, const llama_kv_cache_context * mctx, -+ const ggml_tensor * row_input, const ggml_tensor * mask_input, uint32_t physical_extent) { -+ const uint32_t rows = params.flash_attn && params.fused_kv_rows && !params.training ? mctx->get_n_kv_rows() : 0; -+ const uint32_t slices = llama_kv_cache::get_n_kv_slices(ubatch); -+ const bool use_rows = rows && rows % 256 == 0 && slices; -+ if (use_rows != (row_input != nullptr)) { -+ return false; -+ } -+ if (!use_rows) { -+ return true; -+ } -+ return physical_extent == mctx->get_n_kv() && row_input->ne[0] == rows && -+ row_input->ne[1] == slices && mask_input->ne[0] == rows && -+ mask_input->ne[1] == ubatch.n_tokens / slices && mask_input->ne[3] == slices; -+} -+ -+void set_pool_row_inputs( -+ const llama_ubatch & ubatch, const llama_cparams & params, const llama_kv_cache_context * mctx, -+ ggml_tensor * row_input, ggml_tensor * mask_input) { -+ if (row_input && row_input->buffer) { -+ mctx->set_input_kv_rows(row_input, &ubatch); -+ } -+ if (mask_input && mask_input->buffer) { -+ GGML_ASSERT(row_input && row_input->buffer); -+ mctx->set_input_kq_mask(mask_input, &ubatch, params.causal_attn, row_input); -+ } -+} -+ -+} // namespace -+ -+void llm_graph_input_attn_kv::build_row_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { -+ build_pool_row_inputs(ctx, ubatch, cparams, mctx, self_kv_rows, self_read_mask, -+ read_physical_extent, "attn_inp_kv_rows", "attn_inp_read_mask"); -+} -+ -+bool llm_graph_input_attn_kv::can_reuse_row_inputs(const llama_ubatch & ubatch, const llama_cparams & params) { -+ return can_reuse_pool_row_inputs(ubatch, params, mctx, self_kv_rows, self_read_mask, read_physical_extent); -+} -+ -+void llm_graph_input_attn_kv::set_row_inputs(const llama_ubatch & ubatch) { -+ set_pool_row_inputs(ubatch, cparams, mctx, self_kv_rows, self_read_mask); -+} -+ -+void llm_graph_input_attn_kv_iswa::build_row_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { -+ build_pool_row_inputs(ctx, ubatch, cparams, mctx->get_base(), self_kv_rows, self_read_mask, -+ read_physical_extent, "attn_inp_kv_rows", "attn_inp_read_mask"); -+ build_pool_row_inputs(ctx, ubatch, cparams, mctx->get_swa(), self_kv_rows_swa, self_read_mask_swa, -+ read_physical_extent_swa, "attn_inp_kv_rows_swa", "attn_inp_read_mask_swa"); -+} -+ -+bool llm_graph_input_attn_kv_iswa::can_reuse_row_inputs( -+ const llama_ubatch & ubatch, const llama_cparams & params) { -+ // Evaluate both pools: their compact extents and SWA visibility are independent. -+ const bool base = can_reuse_pool_row_inputs(ubatch, params, mctx->get_base(), -+ self_kv_rows, self_read_mask, read_physical_extent); -+ const bool swa = can_reuse_pool_row_inputs(ubatch, params, mctx->get_swa(), -+ self_kv_rows_swa, self_read_mask_swa, read_physical_extent_swa); -+ return base && swa; -+} -+ -+void llm_graph_input_attn_kv_iswa::set_row_inputs(const llama_ubatch & ubatch) { -+ set_pool_row_inputs(ubatch, cparams, mctx->get_base(), self_kv_rows, self_read_mask); -+ set_pool_row_inputs(ubatch, cparams, mctx->get_swa(), self_kv_rows_swa, self_read_mask_swa); -+} -diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 6cadda971..67b94396a 100644 ---- a/src/llama-graph.cpp -+++ b/src/llama-graph.cpp -@@ -17,6 +17,7 @@ - #include "llama-memory-hybrid-iswa.h" - #include "llama-memory-recurrent.h" - -+#include - #include - #include - #include -@@ -25,6 +26,42 @@ - #include - #include - -+bool skippy_graph_build_inputs::topology_equal(const skippy_graph_build_inputs & other) const { -+ if (activation_import_identities != other.activation_import_identities || -+ activation_import_bindings != other.activation_import_bindings || -+ activation_export_identities != other.activation_export_identities || -+ activation_export_bindings != other.activation_export_bindings || -+ resident_tensor_names != other.resident_tensor_names || -+ execution_contract != other.execution_contract) return false; -+ if (activation_frontier.size() != other.activation_frontier.size()) return false; -+ for (size_t index = 0; index < activation_frontier.size(); ++index) { -+ const auto & left = activation_frontier[index]; -+ const auto & right = other.activation_frontier[index]; -+ if ((left.values != nullptr) != (right.values != nullptr) || -+ left.payload_bytes != right.payload_bytes || left.ggml_type != right.ggml_type || -+ left.rank != right.rank || left.token_axis != right.token_axis) return false; -+ for (int dimension = 0; dimension < GGML_MAX_DIMS; ++dimension) { -+ if (left.dimensions[dimension] != right.dimensions[dimension] || -+ left.byte_strides[dimension] != right.byte_strides[dimension]) return false; -+ } -+ } -+ return selection.enabled == other.selection.enabled && -+ selection.layer_start == other.selection.layer_start && -+ selection.layer_end == other.selection.layer_end && -+ selection.glm_dsa_policy_profile == other.selection.glm_dsa_policy_profile && -+ selection.glm_dsa_policy_flags == other.selection.glm_dsa_policy_flags && -+ selection.glm_dsa_short_prefill_max_tokens == other.selection.glm_dsa_short_prefill_max_tokens && -+ selection.glm_dsa_direct_sparse_decode_max_top_k == other.selection.glm_dsa_direct_sparse_decode_max_top_k && -+ selection.glm_dsa_dense_sparse_mask_max_bytes == other.selection.glm_dsa_dense_sparse_mask_max_bytes && -+ selection.glm_dsa_compact_flash_min_kv == other.selection.glm_dsa_compact_flash_min_kv && -+ selection.glm_dsa_phase_hint == other.selection.glm_dsa_phase_hint && -+ (activation_tokens.tokens != nullptr) == (other.activation_tokens.tokens != nullptr) && -+ activation_tokens.token_count == other.activation_tokens.token_count && -+ (mtp_embeddings.values != nullptr) == (other.mtp_embeddings.values != nullptr) && -+ mtp_embeddings.token_count == other.mtp_embeddings.token_count && -+ mtp_embeddings.n_embd == other.mtp_embeddings.n_embd; -+} -+ - // dedup helpers - - static ggml_tensor * build_attn_inp_kq_mask( -@@ -68,13 +105,13 @@ static bool can_reuse_kq_mask( - // impl - - void llm_graph_input_embd::set_input(const llama_ubatch * ubatch) { -- if (ubatch->token) { -+ if (ubatch->token && tokens != nullptr && tokens->buffer != nullptr) { - const int64_t n_tokens = ubatch->n_tokens; - - ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens)); - } - -- if (ubatch->embd && embd && !ubatch->is_mixed()) { -+ if (ubatch->embd && embd != nullptr && embd->buffer != nullptr && !ubatch->is_mixed()) { - GGML_ASSERT(n_embd == embd->ne[0]); - - const int64_t n_tokens = ubatch->n_tokens; -@@ -128,11 +165,11 @@ static int64_t llm_graph_n_tok_rows(const llama_ubatch & ubatch) { - bool llm_graph_input_embd::can_reuse(const llm_graph_params & params) { - bool res = true; - -- res &= (!params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens); -- res &= (!params.ubatch.embd) || (embd && embd->ne[1] == params.ubatch.n_tokens); -- res &= (!mixed_tokens) || mixed_tokens->ne[0] == llm_graph_n_tok_rows(params.ubatch); -- res &= (!mixed_embd) || mixed_embd->ne[1] == params.ubatch.n_tokens; -- res &= (!scale_rows) || scale_rows->ne[1] == params.ubatch.n_tokens; -+ res &= (!params.ubatch.token) || (tokens && tokens->buffer && tokens->ne[0] == params.ubatch.n_tokens); -+ res &= (!params.ubatch.embd) || (embd && embd->buffer && embd->ne[1] == params.ubatch.n_tokens); -+ res &= (!mixed_tokens) || (mixed_tokens->buffer && mixed_tokens->ne[0] == llm_graph_n_tok_rows(params.ubatch)); -+ res &= (!mixed_embd) || (mixed_embd->buffer && mixed_embd->ne[1] == params.ubatch.n_tokens); -+ res &= (!scale_rows) || (scale_rows->buffer && scale_rows->ne[1] == params.ubatch.n_tokens); - - return res; - } -@@ -145,11 +182,21 @@ void llm_graph_input_embd_h::set_input(const llama_ubatch * ubatch) { - if (ubatch->token) { - ggml_backend_tensor_set(tokens, ubatch->token, 0, n_tokens*ggml_element_size(tokens)); - } else { -- // note: mtmd embedding input goes through here - GGML_ASSERT(ubatch->embd); - GGML_ASSERT(n_embd == embd->ne[0]); -+ const float * values = ubatch->embd; -+ if (mtp_embeddings.values != nullptr) { -+ GGML_ASSERT(mtp_embeddings.n_embd == n_embd); -+ GGML_ASSERT(ubatch->pos != nullptr); -+ const llama_pos token_offset = ubatch->pos[0] - mtp_embeddings.pos_start; -+ GGML_ASSERT(token_offset >= 0); -+ GGML_ASSERT( -+ static_cast(token_offset) + ubatch->n_tokens <= -+ mtp_embeddings.token_count); -+ values = mtp_embeddings.values + static_cast(token_offset)*n_embd; -+ } - -- ggml_backend_tensor_set(embd, ubatch->embd, 0, n_tokens*n_embd*ggml_element_size(embd)); -+ ggml_backend_tensor_set(embd, values, 0, n_tokens*n_embd*ggml_element_size(embd)); - } - - GGML_ASSERT(ubatch->embd_state && "this graph requires a state embedding, see llama_batch_ext_set_embd_state()"); -@@ -158,18 +205,24 @@ void llm_graph_input_embd_h::set_input(const llama_ubatch * ubatch) { - ggml_backend_tensor_set(h, ubatch->embd_state, 0, n_tokens*n_embd_state*ggml_element_size(h)); - } - -+void llm_graph_input_embd_h::set_build_inputs(const skippy_graph_build_inputs & inputs) { -+ mtp_embeddings = inputs.mtp_embeddings; -+} -+ - bool llm_graph_input_embd_h::can_reuse(const llm_graph_params & params) { - bool res = true; - -- res &= (!params.ubatch.token) || (tokens && tokens->ne[0] == params.ubatch.n_tokens); -- res &= (!params.ubatch.embd) || (embd && embd->ne[1] == params.ubatch.n_tokens); -- res &= (!params.ubatch.embd_state) || (h && h->ne[1] == params.ubatch.n_tokens); -+ res &= (!params.ubatch.token) || (tokens && tokens->buffer && tokens->ne[0] == params.ubatch.n_tokens); -+ res &= (params.ubatch.token) || (embd && embd->buffer && embd->ne[1] == params.ubatch.n_tokens); -+ res &= (!params.ubatch.embd_state) || (h && h->buffer && h->ne[1] == params.ubatch.n_tokens); - - return res; - } - - void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { -- if (ubatch->pos && pos) { -+ // A filtered stage can omit positional work entirely. In that case the -+ // scheduler leaves this otherwise declared graph input unallocated. -+ if (ubatch->pos && pos && pos->buffer) { - const int64_t n_tokens = ubatch->n_tokens; - - const bool has_embd = ubatch->is_mixed() || ubatch->token == nullptr; -@@ -205,7 +258,7 @@ void llm_graph_input_pos::set_input(const llama_ubatch * ubatch) { - bool llm_graph_input_pos::can_reuse(const llm_graph_params & params) { - bool res = true; - -- res &= pos->ne[0] == params.ubatch.n_tokens*n_pos_per_embd; -+ res &= pos && pos->buffer && pos->ne[0] == params.ubatch.n_tokens*n_pos_per_embd; - - return res; - } -@@ -524,6 +577,7 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { - - void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { - // the idxs are left unallocated when the KV cache is bypassed during training -+ // Filtered stages retain only the leaves used by their selected closure. - if (self_k_idxs && self_k_idxs->buffer) { - mctx->set_input_k_idxs(self_k_idxs, ubatch); - } -@@ -537,6 +591,8 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { - mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); - } - -+ set_row_inputs(*ubatch); -+ - if (self_k_rot && self_k_rot->buffer) { - mctx->set_input_k_rot(self_k_rot); - } -@@ -547,24 +603,38 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { - } - - bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) { -- const auto * mctx = static_cast(params.mctx); -+ return can_reuse_attn(static_cast(params.mctx), -+ params.ubatch, params.cparams); -+} - -- this->mctx = mctx; -+bool llm_graph_input_attn_kv::can_reuse_attn(const llama_kv_cache_context * context, -+ const llama_ubatch & ubatch, const llama_cparams & params) { -+ mctx = context; - -- bool res = true; -+ bool res = can_reuse_row_inputs(ubatch, params); - -- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -+ if (self_k_idxs && self_k_idxs->buffer) { -+ res &= self_k_idxs->ne[0] == ubatch.n_tokens; -+ } - //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there - -- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); -+ if (self_kq_mask && self_kq_mask->buffer) { -+ res &= can_reuse_kq_mask(self_kq_mask, mctx, ubatch, params); -+ } - - return res; - } - - void llm_graph_input_attn_k::set_input(const llama_ubatch * ubatch) { -- mctx->set_input_k_idxs(self_k_idxs, ubatch); -+ // Filtered stages can omit their attention path, leaving these declared -+ // graph inputs unallocated by the scheduler. -+ if (self_k_idxs && self_k_idxs->buffer) { -+ mctx->set_input_k_idxs(self_k_idxs, ubatch); -+ } - -- mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); -+ if (self_kq_mask && self_kq_mask->buffer) { -+ mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); -+ } - } - - bool llm_graph_input_attn_k::can_reuse(const llm_graph_params & params) { -@@ -576,9 +646,10 @@ bool llm_graph_input_attn_k::can_reuse(const llm_graph_params & params) { - bool llm_graph_input_attn_k::can_reuse_impl(const llm_graph_params & params) { - bool res = true; - -- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -+ res &= self_k_idxs && self_k_idxs->buffer && self_k_idxs->ne[0] == params.ubatch.n_tokens; - -- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); -+ res &= self_kq_mask && self_kq_mask->buffer && -+ can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); - - return res; - } -@@ -594,37 +665,51 @@ llm_graph_input_attn_kv_msa::llm_graph_input_attn_kv_msa( - void llm_graph_input_attn_kv_msa::set_input(const llama_ubatch * ubatch) { - llm_graph_input_attn_kv::set_input(ubatch); - -- if (self_k_idxs_idx) { -+ if (self_k_idxs_idx && self_k_idxs_idx->buffer) { - mctx_msa->get_idx()->set_input_k_idxs(self_k_idxs_idx, ubatch); - } - } - - bool llm_graph_input_attn_kv_msa::can_reuse(const llm_graph_params & params) { -- mctx_msa = static_cast(params.mctx); -+ const auto * runtime_memory = dynamic_cast(params.mctx); -+ if (runtime_memory == nullptr) return false; -+ mctx_msa = runtime_memory; - - // the parent class operates on the base cache context - this->mctx = mctx_msa->get_base(); - - bool res = true; - -- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -- if (self_k_idxs_idx) { -+ if (self_k_idxs && self_k_idxs->buffer) { -+ res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -+ } -+ if (self_k_idxs_idx && self_k_idxs_idx->buffer) { - res &= self_k_idxs_idx->ne[0] == params.ubatch.n_tokens; - } - -- res &= can_reuse_kq_mask(self_kq_mask, this->mctx, params.ubatch, params.cparams); -+ if (self_kq_mask && self_kq_mask->buffer) { -+ res &= can_reuse_kq_mask(self_kq_mask, this->mctx, params.ubatch, params.cparams); -+ } - - return res; - } - - void llm_graph_input_attn_k_dsa::set_input(const llama_ubatch * ubatch) { -- mctx->get_mla()->set_input_k_idxs(self_k_idxs_mla, ubatch); -+ if (self_k_idxs_mla && self_k_idxs_mla->buffer) { -+ mctx->get_mla()->set_input_k_idxs(self_k_idxs_mla, ubatch); -+ } - -- mctx->get_mla()->set_input_kq_mask(self_kq_mask_mla, ubatch, cparams.causal_attn); -+ if (self_kq_mask_mla && self_kq_mask_mla->buffer) { -+ mctx->get_mla()->set_input_kq_mask(self_kq_mask_mla, ubatch, cparams.causal_attn); -+ } - -- mctx->get_lid()->set_input_k_idxs(self_k_idxs_lid, ubatch); -+ if (self_k_idxs_lid && self_k_idxs_lid->buffer) { -+ mctx->get_lid()->set_input_k_idxs(self_k_idxs_lid, ubatch); -+ } - -- mctx->get_lid()->set_input_kq_mask(self_kq_mask_lid, ubatch, cparams.causal_attn); -+ if (self_kq_mask_lid && self_kq_mask_lid->buffer) { -+ mctx->get_lid()->set_input_kq_mask(self_kq_mask_lid, ubatch, cparams.causal_attn); -+ } - - // left unallocated when the indexer does not use the rotation - if (self_k_rot_lid && self_k_rot_lid->buffer) { -@@ -633,7 +718,9 @@ void llm_graph_input_attn_k_dsa::set_input(const llama_ubatch * ubatch) { - } - - bool llm_graph_input_attn_k_dsa::can_reuse(const llm_graph_params & params) { -- mctx = static_cast(params.mctx); -+ const auto * runtime_memory = dynamic_cast(params.mctx); -+ if (runtime_memory == nullptr) return false; -+ mctx = runtime_memory; - - return can_reuse_impl(params); - } -@@ -641,11 +728,19 @@ bool llm_graph_input_attn_k_dsa::can_reuse(const llm_graph_params & params) { - bool llm_graph_input_attn_k_dsa::can_reuse_impl(const llm_graph_params & params) { - bool res = true; - -- res &= self_k_idxs_mla->ne[0] == params.ubatch.n_tokens; -- res &= self_k_idxs_lid->ne[0] == params.ubatch.n_tokens; -+ if (self_k_idxs_mla && self_k_idxs_mla->buffer) { -+ res &= self_k_idxs_mla->ne[0] == params.ubatch.n_tokens; -+ } -+ if (self_k_idxs_lid && self_k_idxs_lid->buffer) { -+ res &= self_k_idxs_lid->ne[0] == params.ubatch.n_tokens; -+ } - -- res &= can_reuse_kq_mask(self_kq_mask_mla, mctx->get_mla(), params.ubatch, params.cparams); -- res &= can_reuse_kq_mask(self_kq_mask_lid, mctx->get_lid(), params.ubatch, params.cparams); -+ if (self_kq_mask_mla && self_kq_mask_mla->buffer) { -+ res &= can_reuse_kq_mask(self_kq_mask_mla, mctx->get_mla(), params.ubatch, params.cparams); -+ } -+ if (self_kq_mask_lid && self_kq_mask_lid->buffer) { -+ res &= can_reuse_kq_mask(self_kq_mask_lid, mctx->get_lid(), params.ubatch, params.cparams); -+ } - - return res; - } -@@ -695,6 +790,8 @@ void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) { - mctx->get_swa()->set_input_kq_mask(self_kq_mask_swa, ubatch, cparams.causal_attn); - } - -+ set_row_inputs(*ubatch); -+ - if (self_k_rot && self_k_rot->buffer) { - mctx->get_base()->set_input_k_rot(self_k_rot); - } -@@ -713,30 +810,35 @@ void llm_graph_input_attn_kv_iswa::set_input(const llama_ubatch * ubatch) { - } - - bool llm_graph_input_attn_kv_iswa::can_reuse(const llm_graph_params & params) { -- const auto * mctx = static_cast(params.mctx); -+ return can_reuse_attn(static_cast(params.mctx), -+ params.ubatch, params.cparams); -+} - -- this->mctx = mctx; -+bool llm_graph_input_attn_kv_iswa::can_reuse_attn( -+ const llama_kv_cache_iswa_context * context, const llama_ubatch & ubatch, -+ const llama_cparams & params) { -+ mctx = context; - -- bool res = true; -+ bool res = can_reuse_row_inputs(ubatch, params); - - // base tensors may not be allocated if there are no non-SWA attention layers - if (self_k_idxs && self_k_idxs->buffer) { -- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -- //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -+ res &= self_k_idxs->ne[0] == ubatch.n_tokens; -+ //res &= self_v_idxs->ne[0] == ubatch.n_tokens; // TODO: need to move this to the unified cache and check there - } - - if (self_kq_mask && self_kq_mask->buffer) { -- res &= can_reuse_kq_mask(self_kq_mask, mctx->get_base(), params.ubatch, params.cparams); -+ res &= can_reuse_kq_mask(self_kq_mask, mctx->get_base(), ubatch, params); - } - - // swa tensors may not be allocated if there are no SWA attention layers - if (self_k_idxs_swa && self_k_idxs_swa->buffer) { -- res &= self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; -- //res &= self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -+ res &= self_k_idxs_swa->ne[0] == ubatch.n_tokens; -+ //res &= self_v_idxs_swa->ne[0] == ubatch.n_tokens; // TODO: need to move this to the unified cache and check there - } - - if (self_kq_mask_swa && self_kq_mask_swa->buffer) { -- res &= can_reuse_kq_mask(self_kq_mask_swa, mctx->get_swa(), params.ubatch, params.cparams); -+ res &= can_reuse_kq_mask(self_kq_mask_swa, mctx->get_swa(), ubatch, params); - } - - return res; -@@ -1040,6 +1142,33 @@ static void dsv4_build_comp_inputs( - } - } - -+std::unique_ptr llm_graph_input_dsv4_create( -+ ggml_context * ctx, -+ const llama_hparams & hparams, -+ const llama_cparams & cparams, -+ const llama_ubatch & ubatch, -+ const llama_kv_cache_dsv4_context * mctx) { -+ const auto * raw_ctx = mctx->get_raw(); -+ auto inp_raw = std::make_unique(cparams, raw_ctx); -+ const int64_t n_stream = mctx->get_csa_plan(ubatch).n_stream; -+ -+ GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "DSV4 expects SWA raw cache"); -+ -+ inp_raw->self_k_idxs = raw_ctx->build_input_k_idxs(ctx, ubatch); -+ inp_raw->self_kq_mask = dsv4_build_raw_kq_mask(ctx, raw_ctx, ubatch, cparams, n_stream); -+ inp_raw->self_kq_mask_cnv = inp_raw->self_kq_mask; -+ inp_raw->self_k_rot = raw_ctx->build_input_k_rot(ctx); -+ -+ auto inp = std::make_unique(cparams, std::move(inp_raw), mctx); -+ dsv4_build_comp_inputs(ctx, inp->inp_csa, mctx->get_csa_plan(ubatch), "csa", cparams, n_stream); -+ dsv4_build_comp_inputs(ctx, inp->inp_hca, mctx->get_hca_plan(ubatch), "hca", cparams, n_stream); -+ dsv4_build_comp_inputs(ctx, inp->inp_lid, mctx->get_lid_plan(ubatch), "lid", cparams, n_stream); -+ inp->inp_csa.k_rot = mctx->get_csa()->build_input_k_rot(ctx); -+ inp->inp_hca.k_rot = mctx->get_hca()->build_input_k_rot(ctx); -+ inp->inp_lid.k_rot = mctx->get_lid()->build_input_k_rot(ctx); -+ return inp; -+} -+ - void llm_graph_input_dsv4_raw::set_input(const llama_ubatch * ubatch) { - if (self_k_idxs && self_k_idxs->buffer) { - mctx->set_input_k_idxs(self_k_idxs); -@@ -1147,22 +1276,12 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { - } - - void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { -- mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); -- mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); -- -- mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); -- -- if (inp_attn->self_k_rot) { -- mctx->get_attn()->set_input_k_rot(inp_attn->self_k_rot); -- } -- -- if (inp_attn->self_v_rot) { -- mctx->get_attn()->set_input_v_rot(inp_attn->self_v_rot); -- } -+ inp_attn->mctx = mctx->get_attn(); -+ inp_attn->set_input(ubatch); - - const int64_t n_rs = mctx->get_recr()->get_n_rs(); - -- if (inp_rs->s_copy) { -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { - GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); - int32_t * data = (int32_t *) inp_rs->s_copy->data; - -@@ -1178,16 +1297,15 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { - - this->mctx = mctx; - -- bool res = true; -+ bool res = inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); - -- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; -- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -- -- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); -- -- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { -+ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); -+ } - -- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; -+ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { -+ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; -+ } - - res &= inp_rs->head == mctx->get_recr()->get_head(); - res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); -@@ -1199,13 +1317,18 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { - // Instead of creating a hybrid input, the graph can simply create 2 separate inputs. - // Refactoring is required in the future. - void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { -- mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); -+ const auto * attn_ctx = mctx->get_attn(); - -- mctx->get_attn()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); -+ // These tensors may not be allocated for staged slices that contain only -+ // recurrent layers. -+ if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { -+ attn_ctx->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); -+ attn_ctx->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); -+ } - - const int64_t n_rs = mctx->get_recr()->get_n_rs(); - -- if (inp_rs->s_copy) { -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { - GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); - int32_t * data = (int32_t *) inp_rs->s_copy->data; - -@@ -1223,62 +1346,35 @@ bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { - - bool res = true; - -- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; -- -- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); -- -- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); -- -- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; -- -- res &= inp_rs->head == mctx->get_recr()->get_head(); -- res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); -- -- return res; --} -- --void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { -- const auto * attn_ctx = mctx->get_attn(); -- -- // base tensors may not be allocated if there are no non-SWA attention layers - if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { -- attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); -- attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); -+ res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; - } - - if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { -- attn_ctx->get_base()->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); -- } -- -- // swa tensors may not be allocated if there are no SWA attention layers -- if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { -- attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); -- attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); -+ res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); - } - -- if (inp_attn->self_kq_mask_swa && inp_attn->self_kq_mask_swa->buffer) { -- attn_ctx->get_swa()->set_input_kq_mask(inp_attn->self_kq_mask_swa, ubatch, cparams.causal_attn); -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { -+ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); - } - -- if (inp_attn->self_k_rot) { -- attn_ctx->get_base()->set_input_k_rot(inp_attn->self_k_rot); -+ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { -+ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; - } - -- if (inp_attn->self_v_rot) { -- attn_ctx->get_base()->set_input_v_rot(inp_attn->self_v_rot); -- } -+ res &= inp_rs->head == mctx->get_recr()->get_head(); -+ res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); - -- if (inp_attn->self_k_rot_swa) { -- attn_ctx->get_swa()->set_input_k_rot(inp_attn->self_k_rot_swa); -- } -+ return res; -+} - -- if (inp_attn->self_v_rot_swa) { -- attn_ctx->get_swa()->set_input_v_rot(inp_attn->self_v_rot_swa); -- } -+void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { -+ inp_attn->mctx = mctx->get_attn(); -+ inp_attn->set_input(ubatch); - - const int64_t n_rs = mctx->get_recr()->get_n_rs(); - -- if (inp_rs->s_copy) { -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { - GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); - int32_t * data = (int32_t *) inp_rs->s_copy->data; - -@@ -1296,28 +1392,16 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) - - bool res = true; - -- const auto * attn_ctx = mctx->get_attn(); -+ res &= inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); - -- // base tensors may not be allocated if there are no non-SWA attention layers -- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { -- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; -- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -+ if (inp_rs->s_copy && inp_rs->s_copy->buffer) { -+ res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); - } - -- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, attn_ctx->get_base(), params.ubatch, params.cparams); -- -- // swa tensors may not be allocated if there are no SWA attention layers -- if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { -- res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; -- //res &= inp_attn->self_v_idxs_swa->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -+ if (inp_rs->s_copy_main && inp_rs->s_copy_main->buffer) { -+ res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; - } - -- res &= can_reuse_kq_mask(inp_attn->self_kq_mask_swa, attn_ctx->get_swa(), params.ubatch, params.cparams); -- -- res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); -- -- res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; -- - res &= inp_rs->head == mctx->get_recr()->get_head(); - res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); - -@@ -1383,6 +1467,8 @@ void llm_graph_result::reset() { - t_embd = nullptr; - t_embd_pooled = nullptr; - t_h_nextn = nullptr; -+ activation_imports.clear(); -+ activation_exports.clear(); - - t_layer_inp.resize(LLAMA_MAX_LAYERS + 1); - std::fill(t_layer_inp.begin(), t_layer_inp.end(), nullptr); -@@ -1397,8 +1483,17 @@ void llm_graph_result::reset() { - inputs.clear(); - fused_nodes.clear(); - hdmd_inputs.clear(); -- -- buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false)); -+ block_boundaries.clear(); -+ state_effects.clear(); -+ input_choices.clear(); -+ build_inputs = {}; -+ request_input_bindings.clear(); -+ request_input_ordinals.clear(); -+ -+ // A filtered runtime first constructs the canonical whole-model graph and -+ // then materializes a second graph descriptor plus detached frontier -+ // leaves in this same metadata arena. -+ buf_compute_meta.resize(2*(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false))); - - ggml_init_params params = { - /*.mem_size =*/ buf_compute_meta.size(), -@@ -1411,17 +1506,92 @@ void llm_graph_result::reset() { - gf = ggml_new_graph_custom(ctx_compute.get(), max_nodes, false); - } - -+void llm_graph_result::set_inputs(const llama_ubatch * ubatch, const skippy_graph_build_inputs & build_inputs) { -+ this->build_inputs = build_inputs; -+ set_inputs(ubatch); -+} -+ - void llm_graph_result::set_inputs(const llama_ubatch * ubatch) { - for (auto & input : inputs) { -+ input->set_build_inputs(build_inputs); - input->set_input(ubatch); - } -+ GGML_ASSERT(build_inputs.activation_frontier.empty() || -+ build_inputs.activation_frontier.size() == activation_imports.size()); -+ for (size_t index = 0; index < build_inputs.activation_frontier.size(); ++index) { -+ const auto & source = build_inputs.activation_frontier[index]; -+ ggml_tensor * destination = activation_imports[index].tensor; -+ if (source.values == nullptr) { -+ GGML_ASSERT(activation_imports[index].optional); -+ continue; -+ } -+ GGML_ASSERT(destination != nullptr && destination->buffer != nullptr); -+ GGML_ASSERT(source.rank > 0 && source.rank <= GGML_MAX_DIMS && -+ source.token_axis >= 0 && source.token_axis < static_cast(source.rank)); -+ if (destination->type != static_cast(source.ggml_type)) { -+ throw std::runtime_error( -+ "activation frontier part type mismatch at index " + std::to_string(index) + -+ " binding=" + activation_imports[index].binding + -+ " destination=" + ggml_type_name(destination->type) + -+ " source=" + ggml_type_name(static_cast(source.ggml_type))); -+ } -+ for (uint32_t dimension = 0; dimension < source.rank; ++dimension) { -+ const int64_t expected = static_cast(dimension) == source.token_axis ? -+ ubatch->n_tokens : source.dimensions[dimension]; -+ GGML_ASSERT(destination->ne[dimension] == expected); -+ } -+ -+ size_t token_offset = 0; -+ if (!source.sequence_ids.empty() && ubatch->seq_id != nullptr && ubatch->seq_id[0] != nullptr) { -+ const llama_seq_id seq_id = ubatch->seq_id[0][0]; -+ const auto found = std::find(source.sequence_ids.begin(), source.sequence_ids.end(), seq_id); -+ GGML_ASSERT(found != source.sequence_ids.end()); -+ const size_t sequence_index = static_cast(found - source.sequence_ids.begin()); -+ token_offset = source.sequence_offsets[sequence_index]; -+ if (ubatch->pos != nullptr) { -+ GGML_ASSERT(ubatch->pos[0] >= source.sequence_pos_starts[sequence_index]); -+ token_offset += static_cast(ubatch->pos[0] - source.sequence_pos_starts[sequence_index]); -+ } -+ } else if (ubatch->pos != nullptr && source.dimensions[source.token_axis] > ubatch->n_tokens) { -+ GGML_ASSERT(ubatch->pos[0] >= source.pos_start); -+ token_offset = static_cast(ubatch->pos[0] - source.pos_start); -+ } -+ GGML_ASSERT(token_offset + static_cast(ubatch->n_tokens) <= -+ static_cast(source.dimensions[source.token_axis])); -+ const size_t inner_bytes = static_cast(source.byte_strides[source.token_axis]); -+ const size_t source_plane_bytes = inner_bytes * static_cast(source.dimensions[source.token_axis]); -+ const size_t destination_plane_bytes = inner_bytes * static_cast(ubatch->n_tokens); -+ GGML_ASSERT(source_plane_bytes > 0 && source.payload_bytes % source_plane_bytes == 0); -+ const size_t outer_count = static_cast(source.payload_bytes) / source_plane_bytes; -+ for (size_t outer = 0; outer < outer_count; ++outer) { -+ const size_t source_offset = outer * source_plane_bytes + token_offset * inner_bytes; -+ const size_t destination_offset = outer * destination_plane_bytes; -+ ggml_backend_tensor_set( -+ destination, -+ static_cast(source.values) + source_offset, -+ destination_offset, -+ destination_plane_bytes); -+ } -+ } - } - - void llm_graph_result::set_outputs(const llm_graph_params & params) { -+ const auto bind_ports = [](std::vector & ports, -+ const std::vector & expected) { -+ if (ports.empty() || ports.size() != expected.size()) return; -+ // Tensor names are local graph details and can collide with a different -+ // planner binding. Port registration order is the cross-build contract. -+ for (size_t index = 0; index < ports.size(); ++index) { -+ ports[index].binding = expected[index]; -+ } -+ }; -+ bind_ports(activation_imports, params.build_inputs.activation_import_bindings); -+ bind_ports(activation_exports, params.build_inputs.activation_export_bindings); - if (t_logits != nullptr) { - ggml_set_output(t_logits); - } - if (t_embd != nullptr) { -+ ggml_build_forward_expand(gf, t_embd); - ggml_set_output(t_embd); - } - if (t_embd_pooled != nullptr) { -@@ -1430,6 +1600,11 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { - if (t_h_nextn != nullptr) { - ggml_set_output(t_h_nextn); - } -+ for (const skippy_activation_port & port : activation_exports) { -+ if (port.tensor != nullptr) { -+ ggml_set_output(port.tensor); -+ } -+ } - { - const auto & embeddings_layer_inp = params.cparams.embeddings_layer_inp; - for (size_t il = 0; il < embeddings_layer_inp.size(); ++il) { -@@ -1461,6 +1636,74 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { - } - } - -+void llm_graph_result::add_skippy_activation_import( -+ ggml_tensor * tensor, int32_t token_axis, bool optional, bool token_axis_explicit) { -+ if (tensor == nullptr) return; -+ const auto found = std::find_if(activation_imports.begin(), activation_imports.end(), -+ [tensor](const skippy_activation_port & port) { return port.tensor == tensor; }); -+ if (found == activation_imports.end()) { -+ activation_imports.push_back({tensor, token_axis, optional, {}, token_axis_explicit}); -+ } -+} -+ -+void llm_graph_result::add_skippy_activation_export( -+ ggml_tensor * tensor, int32_t token_axis, bool optional, bool token_axis_explicit) { -+ if (tensor == nullptr) return; -+ const auto found = std::find_if(activation_exports.begin(), activation_exports.end(), -+ [tensor](const skippy_activation_port & port) { return port.tensor == tensor; }); -+ if (found == activation_exports.end()) { -+ activation_exports.push_back({tensor, token_axis, optional, {}, token_axis_explicit}); -+ } -+} -+ -+void llm_graph_result::add_skippy_input_choice( -+ const std::array & alternatives, -+ uint32_t selected) { -+ GGML_ASSERT(alternatives[0] != nullptr && alternatives[1] != nullptr && selected < alternatives.size()); -+ input_choices.push_back({alternatives, selected}); -+} -+ -+void llm_graph_result::replace_with_stage_graph( -+ ggml_cgraph * graph, -+ std::vector imports, -+ std::vector exports, -+ std::vector effects) { -+ GGML_ASSERT(graph != nullptr); -+ const auto retain_if_present = [graph](ggml_tensor *& tensor) { -+ if (tensor == nullptr) return; -+ for (int index = 0; index < ggml_graph_n_nodes(graph); ++index) { -+ if (ggml_graph_node(graph, index) == tensor) return; -+ } -+ tensor = nullptr; -+ }; -+ gf = graph; -+ state_effects = std::move(effects); -+ activation_imports = std::move(imports); -+ activation_exports = std::move(exports); -+ retain_if_present(t_logits); -+ retain_if_present(t_embd); -+ retain_if_present(t_embd_pooled); -+ retain_if_present(t_h_nextn); -+ for (auto *& tensor : t_layer_inp) retain_if_present(tensor); -+ for (auto *& tensor : t_sampled) retain_if_present(tensor); -+ for (auto *& tensor : t_sampled_probs) retain_if_present(tensor); -+ for (auto *& tensor : t_sampled_logits) retain_if_present(tensor); -+ for (auto *& tensor : t_candidates) retain_if_present(tensor); -+ -+ // resolve_fused_ops() compares the backend of every fused node with the -+ // device of its layer. Fused nodes of layers outside this stage are not in -+ // the stage graph, so the scheduler never assigns them a backend and they -+ // would read as a device mismatch. Keep only the nodes this stage computes. -+ std::unordered_set stage_nodes; -+ for (int index = 0; index < ggml_graph_n_nodes(graph); ++index) { -+ stage_nodes.insert(ggml_graph_node(graph, index)); -+ } -+ fused_nodes.erase(std::remove_if(fused_nodes.begin(), fused_nodes.end(), -+ [&stage_nodes](const llm_graph_fused_node & node) { -+ return stage_nodes.count(node.tensor) == 0; -+ }), fused_nodes.end()); -+} -+ - bool llm_graph_result::can_reuse(const llm_graph_params & params) { - if (!this->params.allow_reuse(params)) { - if (debug > 1) { -@@ -1494,6 +1737,42 @@ bool llm_graph_result::can_reuse(const llm_graph_params & params) { - } - - llm_graph_input_i * llm_graph_result::add_input(llm_graph_input_ptr input) { -+ const auto request_input = [&](ggml_tensor * tensor, const char * identity) { -+ if (tensor == nullptr) { -+ return; -+ } -+ const auto existing = std::find_if(request_input_bindings.begin(), request_input_bindings.end(), -+ [tensor](const skippy_request_input_binding & binding) { -+ return binding.tensor == tensor; -+ }); -+ if (existing == request_input_bindings.end()) { -+ const uint32_t ordinal = request_input_ordinals[identity]++; -+ request_input_bindings.push_back( -+ {tensor, std::string(identity) + "." + std::to_string(ordinal)}); -+ } -+ }; -+ -+ // Some family builders create generic input bundles directly instead of -+ // going through build_inp_embd(). Register those request leaves here so -+ // every graph exposes the same semantic input contract to stage planning. -+ // A mode the builder does not offer stays out of the advertised embeddings -+ // channel while its leaves keep the semantic graph complete. -+ if (auto * embd = dynamic_cast(input.get())) { -+ request_input(embd->tokens, "tokens"); -+ request_input(embd->embd, embd->allow_embeddings ? "embeddings" : "unavailable.embeddings"); -+ // The mixed batch carries only the token rows it names, with the -+ // remaining rows supplied as raw embeddings, so it owns its own leaves. -+ request_input(embd->mixed_tokens, "tokens.mixed"); -+ request_input(embd->mixed_slots, "tokens.mixed.slots"); -+ request_input(embd->mixed_embd, -+ embd->allow_embeddings ? "embeddings.mixed" : "unavailable.embeddings.mixed"); -+ request_input(embd->scale_rows, "scale.rows"); -+ } -+ if (auto * mtp = dynamic_cast(input.get())) { -+ request_input(mtp->tokens, "tokens"); -+ request_input(mtp->embd, "embeddings"); -+ request_input(mtp->h, "mtp.hidden"); -+ } - inputs.emplace_back(std::move(input)); - return inputs.back().get(); - } -@@ -1513,6 +1792,7 @@ void llm_graph_result::set_hdmd_input(const ggml_tensor * cur, const ggml_tensor - - void llm_graph_result::set_params(const llm_graph_params & params) { - this->params = params; -+ build_inputs = params.build_inputs; - } - - // -@@ -1561,6 +1841,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : - hdmd (params.hdmd), - samplers (params.samplers), - cb_func (params.cb), -+ build_inputs (params.build_inputs), - res (params.res), - ctx0 (res->get_ctx()), - gf (res->get_gf()) { -@@ -1573,7 +1854,143 @@ void llm_graph_context::cb(ggml_tensor * cur, const char * name, int il) const { - } - } - -+void llm_graph_context::begin_block(ggml_tensor * cur, int il) const { -+ res->block_boundaries.push_back({skippy_block_boundary_kind::entry, il, cur}); -+} -+ -+void llm_graph_context::end_block(ggml_tensor * cur, int il) const { -+ // Expand eagerly so block boundary positions partition the executable -+ // graph: lazy expansion lets independent nodes from later blocks be -+ // appended before an earlier block's exit tensor. -+ ggml_build_forward_expand(gf, cur); -+ res->block_boundaries.push_back({skippy_block_boundary_kind::exit, il, cur}); -+} -+ -+void llm_graph_context::state_read(skippy_state_kind kind, ggml_tensor * storage, int il) const { -+ res->state_effects.push_back({kind, skippy_state_access::read, -+ il, skippy_state_canonical_storage(storage), nullptr, -1, -+ il >= n_layer ? skippy_state_residency::per_stage : skippy_state_residency::layer_local}); -+} -+ -+void llm_graph_context::state_write(skippy_state_kind kind, ggml_tensor * storage, ggml_tensor * effect_node, int il) const { -+ const ggml_tensor * canonical = skippy_state_canonical_storage(storage); -+ int64_t ordinal = 0; -+ for (const auto & effect : res->state_effects) { -+ if (effect.access == skippy_state_access::write && effect.kind == kind && -+ effect.layer == il && effect.storage == canonical) { -+ ++ordinal; -+ } -+ } -+ res->state_effects.push_back({kind, skippy_state_access::write, il, canonical, effect_node, ordinal, -+ il >= n_layer ? skippy_state_residency::per_stage : skippy_state_residency::layer_local}); -+} -+ -+void llm_graph_context::request_input(ggml_tensor * tensor, const char * identity) const { -+ if (tensor != nullptr) { -+ const uint32_t ordinal = res->request_input_ordinals[identity]++; -+ res->request_input_bindings.push_back({tensor, std::string(identity) + "." + std::to_string(ordinal)}); -+ } -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_no_cache * input) const { -+ request_input(input->self_kq_mask, "attention.mask"); -+ request_input(input->self_kq_mask_swa, "attention.swa.mask"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_kv * input) const { -+ request_input(input->self_k_idxs, "attention.key_indices"); -+ request_input(input->self_v_idxs, "attention.value_indices"); -+ request_input(input->self_kq_mask, "attention.mask"); -+ request_input(input->self_kv_rows, "attention.kv_rows"); -+ request_input(input->self_read_mask, "attention.read_mask"); -+ request_input(input->self_k_rot, "attention.key_rotation"); -+ request_input(input->self_v_rot, "attention.value_rotation"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_k * input) const { -+ request_input(input->self_k_idxs, "attention.key_indices"); -+ request_input(input->self_kq_mask, "attention.mask"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_kv_iswa * input) const { -+ request_input(input->self_k_idxs, "attention.base.key_indices"); -+ request_input(input->self_v_idxs, "attention.base.value_indices"); -+ request_input(input->self_kq_mask, "attention.base.mask"); -+ request_input(input->self_kv_rows, "attention.base.read_rows"); -+ request_input(input->self_read_mask, "attention.base.read_mask"); -+ request_input(input->self_k_rot, "attention.base.key_rotation"); -+ request_input(input->self_v_rot, "attention.base.value_rotation"); -+ request_input(input->self_k_idxs_swa, "attention.swa.key_indices"); -+ request_input(input->self_v_idxs_swa, "attention.swa.value_indices"); -+ request_input(input->self_kq_mask_swa, "attention.swa.mask"); -+ request_input(input->self_kv_rows_swa, "attention.swa.read_rows"); -+ request_input(input->self_read_mask_swa, "attention.swa.read_mask"); -+ request_input(input->self_k_rot_swa, "attention.swa.key_rotation"); -+ request_input(input->self_v_rot_swa, "attention.swa.value_rotation"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_k_iswa * input) const { -+ request_input(input->self_k_idxs, "attention.base.key_indices"); -+ request_input(input->self_kq_mask, "attention.base.mask"); -+ request_input(input->self_k_rot, "attention.base.key_rotation"); -+ request_input(input->self_k_idxs_swa, "attention.swa.key_indices"); -+ request_input(input->self_kq_mask_swa, "attention.swa.mask"); -+ request_input(input->self_k_rot_swa, "attention.swa.key_rotation"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_k_dsa * input) const { -+ request_input(input->self_k_idxs_mla, "attention.dsa.mla.key_indices"); -+ request_input(input->self_k_idxs_lid, "attention.dsa.indexer.key_indices"); -+ request_input(input->self_kq_mask_mla, "attention.dsa.mla.mask"); -+ request_input(input->self_kq_mask_lid, "attention.dsa.indexer.mask"); -+ request_input(input->self_k_rot_lid, "attention.dsa.indexer.key_rotation"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_k_dsa_iswa * input) const { -+ request_inputs(input->get_dsa()); -+ request_input(input->get_swa()->self_k_idxs, "attention.swa.key_indices"); -+ request_input(input->get_swa()->self_kq_mask, "attention.swa.mask"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_attn_kv_msa * input) const { -+ request_inputs(static_cast(input)); -+ request_input(input->self_k_idxs_idx, "attention.msa.indexer.key_indices"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_mem_hybrid_iswa * input) const { -+ request_inputs(input->get_attn()); -+ request_inputs(input->get_recr()); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_rs * input) const { -+ request_input(input->s_copy, "recurrent.copy_indices"); -+} -+ -+void llm_graph_context::request_inputs(llm_graph_input_dsv4 * input) const { -+ const auto register_comp = [&](const llm_graph_input_dsv4::comp_input & comp, const char * plane) { -+ const std::string prefix = std::string("dsv4.") + plane + "."; -+ request_input(comp.state_pos, (prefix + "state_positions").c_str()); -+ request_input(comp.state_persist_src_idxs, (prefix + "persist_source_indices").c_str()); -+ request_input(comp.state_persist_dst_idxs, (prefix + "persist_destination_indices").c_str()); -+ request_input(comp.state_restore_src_idxs, (prefix + "restore_source_indices").c_str()); -+ request_input(comp.state_restore_dst_idxs, (prefix + "restore_destination_indices").c_str()); -+ request_input(comp.state_snapshot_src_idxs, (prefix + "snapshot_source_indices").c_str()); -+ request_input(comp.state_snapshot_dst_idxs, (prefix + "snapshot_destination_indices").c_str()); -+ request_input(comp.state_read_idxs, (prefix + "read_indices").c_str()); -+ request_input(comp.state_write_idxs, (prefix + "write_indices").c_str()); -+ request_input(comp.state_write_pos, (prefix + "write_positions").c_str()); -+ request_input(comp.kq_mask, (prefix + "attention_mask").c_str()); -+ request_input(comp.k_rot, (prefix + "key_rotation").c_str()); -+ }; - -+ auto * raw = input->get_raw(); -+ request_input(raw->self_k_idxs, "dsv4.raw.key_indices"); -+ request_input(raw->self_kq_mask, "dsv4.raw.attention_mask"); -+ request_input(raw->self_k_rot, "dsv4.raw.key_rotation"); -+ register_comp(input->get_csa(), "csa"); -+ register_comp(input->get_hca(), "hca"); -+ register_comp(input->get_lid(), "lid"); -+} - - ggml_tensor * llm_graph_context::build_cvec( - ggml_tensor * cur, -@@ -1615,7 +2032,8 @@ ggml_tensor * llm_graph_context::build_hadamard_input( - ggml_tensor * llm_graph_context::build_lora_mm( - ggml_tensor * w, - ggml_tensor * cur, -- ggml_tensor * w_s) const { -+ ggml_tensor * w_s, -+ enum ggml_prec prec) const { - cur = build_hadamard_input(w, cur); - ggml_tensor * res = ggml_mul_mat(ctx0, w, cur); - -@@ -1627,6 +2045,11 @@ ggml_tensor * llm_graph_context::build_lora_mm( - ggml_prec_set_acc(res, GGML_PREC_BF16); - } - -+ if (prec != GGML_PREC_DEFAULT) { -+ // Set precision on the base MUL_MAT before an optional scale/LoRA attachment changes the root op. -+ ggml_prec_set_acc(res, prec); -+ } -+ - if (w_s) { - res = ggml_mul(ctx0, res, w_s); - } -@@ -2145,6 +2568,10 @@ ggml_tensor * llm_graph_context::build_moe_ffn( - ggml_tensor * selected_experts_in) const { - const int64_t n_embd = cur->ne[0]; - const int64_t n_tokens = cur->ne[1]; -+ const auto top_k = [&](ggml_tensor * value, int64_t k) { -+ auto * result = ggml_argsort_top_k(ctx0, value, k); -+ return result; -+ }; - const bool weight_before_ffn = arch == LLM_ARCH_LLAMA4; // for llama4, we apply the sigmoid-ed weights before the FFN - - ggml_tensor * logits = nullptr; -@@ -2214,14 +2641,14 @@ ggml_tensor * llm_graph_context::build_moe_ffn( - // organize experts into n_expert_groups - ggml_tensor * selection_groups = ggml_reshape_3d(ctx0, selection_probs, n_exp_per_group, hparams.n_expert_groups, n_tokens); // [n_exp_per_group, n_expert_groups, n_tokens] - -- ggml_tensor * group_scores = ggml_argsort_top_k(ctx0, selection_groups, 2); // [2, n_expert_groups, n_tokens] -+ ggml_tensor * group_scores = top_k(selection_groups, 2); // [2, n_expert_groups, n_tokens] - group_scores = ggml_get_rows(ctx0, ggml_reshape_4d(ctx0, selection_groups, 1, selection_groups->ne[0], selection_groups->ne[1], selection_groups->ne[2]), group_scores); // [1, 2, n_expert_groups, n_tokens] - - // get top n_group_used expert groups - group_scores = ggml_sum_rows(ctx0, ggml_reshape_3d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2], group_scores->ne[3])); // [1, n_expert_groups, n_tokens] - group_scores = ggml_reshape_2d(ctx0, group_scores, group_scores->ne[1], group_scores->ne[2]); // [n_expert_groups, n_tokens] - -- ggml_tensor * expert_groups = ggml_argsort_top_k(ctx0, group_scores, hparams.n_group_used); // [n_group_used, n_tokens] -+ ggml_tensor * expert_groups = top_k(group_scores, hparams.n_group_used); // [n_group_used, n_tokens] - cb(expert_groups, "ffn_moe_group_topk", il); - - // mask out the other groups -@@ -2234,7 +2661,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( - // select experts - ggml_tensor * selected_experts = selected_experts_in; - if (selected_experts == nullptr) { -- selected_experts = ggml_argsort_top_k(ctx0, selection_probs, n_expert_used); // [n_expert_used, n_tokens] -+ selected_experts = top_k(selection_probs, n_expert_used); // [n_expert_used, n_tokens] - cb(selected_experts->src[0], "ffn_moe_argsort", il); - } - cb(selected_experts, "ffn_moe_topk", il); -@@ -2467,6 +2894,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( - for (uint32_t i = 0; i < n_expert_used_il; ++i) { - cur_experts[i] = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]); - -+ - ggml_build_forward_expand(gf, cur_experts[i]); - } - -@@ -2531,14 +2959,30 @@ ggml_tensor * llm_graph_context::build_moe_cache_slots( - return ggml_reshape_2d(ctx0, slots, selected_experts->ne[0], selected_experts->ne[1]); // [n_expert_used, n_tokens] - } - -+// Deepstack models embed text and multimodal rows in the same graph, and only -+// the token rows carry the Granite embedding scale. Keep the decision in one -+// place so the stage planner sees the same input contract the graph executes. -+static bool scale_embedding_input(uint32_t input_mode, uint32_t n_deepstack_layers) { -+ return input_mode == 0 || n_deepstack_layers == 0; -+} -+ -+#ifdef LLAMA_STAGE_BUILD_TESTS -+bool skippy_scale_embedding_input_for_test(uint32_t input_mode, uint32_t n_deepstack_layers) { -+ return scale_embedding_input(input_mode, n_deepstack_layers); -+} -+#endif -+ - // input embeddings with optional lora --ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float tok_scale) const { -+ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float tok_scale, bool allow_embeddings) const { -+ if (ubatch.embd && !allow_embeddings) { -+ GGML_ABORT("This GGUF does not support multimodal. Please reconvert it."); -+ } - const int64_t n_embd_inp = hparams.n_embd_inp(); - const int64_t n_embd = hparams.n_embd; - - assert(n_embd_inp >= n_embd); - -- auto inp = std::make_unique(n_embd_inp); -+ auto inp = std::make_unique(n_embd_inp, allow_embeddings); - - // mixed path (ubatch.is_mixed()): set_rows the token rows into a copy of the embd rows, with its own inputs as select branches must not share tensors - // TODO: use inp->tokens and inp->embd once ggml_build_forward_select allows it -@@ -2559,11 +3003,17 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to - inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens); - cb(inp->tokens, "inp_tokens", -1); - ggml_set_input(inp->tokens); -+ request_input(inp->tokens, "tokens"); - res->t_inp_tokens = inp->tokens; - - inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd_inp, ubatch.n_tokens); - cb(inp->embd, "inp_embd", -1); - ggml_set_input(inp->embd); -+ // Advertise only input modes this graph can execute. Planning uses these -+ // declarations to discover additional profiles without probing invalid modes. -+ if (allow_embeddings) { -+ request_input(inp->embd, "embeddings"); -+ } - - if (has_mixed) { - inp->mixed_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tok_rows); -@@ -2658,6 +3108,12 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to - - const int idx = ubatch.is_mixed() ? 2 : ubatch.token ? 0 : 1; - -+ // the non-mixed graph executes exactly the token and the raw-embedding mode -+ if (!has_mixed) { -+ const std::array alternatives = { inps[0], inps[1] }; -+ res->add_skippy_input_choice(alternatives, (uint32_t) idx); -+ } -+ - ggml_tensor * cur = ggml_build_forward_select(gf, inps.data(), has_mixed ? 3 : 2, idx); - - if (n_embd_inp != n_embd) { -@@ -2668,7 +3124,7 @@ ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float to - - // NOTE: For deepstack models, only apply scale to token inputs (ie text-only input). - // Raw embeddings are assumed to be multimodal inputs that should not be scaled. -- const bool scale_tok_only = hparams.f_embedding_scale != 0.0f && hparams.n_deepstack_layers > 0; -+ const bool scale_tok_only = hparams.f_embedding_scale != 0.0f && !scale_embedding_input(1, hparams.n_deepstack_layers); - - // For Granite architecture - if (hparams.f_embedding_scale != 0.0f && !scale_tok_only) { -@@ -2710,6 +3166,7 @@ ggml_tensor * llm_graph_context::build_inp_pos() const { - cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (int64_t)n_tokens*hparams.n_pos_per_embd()); - ggml_set_input(cur); - cb(cur, "inp_pos", -1); -+ request_input(cur, "positions"); - - res->add_input(std::move(inp)); - -@@ -2725,6 +3182,7 @@ ggml_tensor * llm_graph_context::build_inp_attn_scale() const { - cur = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens); - ggml_set_input(cur); - cb(cur, "inp_attn_scale", -1); -+ request_input(cur, "attention.scale"); - - res->add_input(std::move(inp)); - -@@ -2747,6 +3205,7 @@ ggml_tensor * llm_graph_context::build_inp_out_ids() const { - cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs); - ggml_set_input(cur); - ggml_set_name(cur, "out_ids"); -+ request_input(cur, "output.indices"); - - res->add_input(std::move(inp)); - -@@ -2761,6 +3220,7 @@ ggml_tensor * llm_graph_context::build_inp_mean() const { - cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq); - ggml_set_input(cur); - ggml_set_name(cur, "mean"); -+ request_input(cur, "pooling.mean"); - - res->add_input(std::move(inp)); - -@@ -2775,6 +3235,7 @@ ggml_tensor * llm_graph_context::build_inp_cls() const { - cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq); - ggml_set_input(cur); - ggml_set_name(cur, "cls"); -+ request_input(cur, "pooling.indices"); - - res->add_input(std::move(inp)); - -@@ -2863,11 +3324,16 @@ ggml_tensor * llm_graph_context::build_attn_mha( - ggml_tensor * v_mla, - int64_t n_kv_max, - float kq_scale, -- int il) const { -+ int il, -+ ggml_tensor * kv_rows, -+ ggml_tensor * dense_mask) const { -+ ggml_tensor * original_q = q; -+ ggml_tensor * original_k = k; -+ ggml_tensor * original_v = v; - const bool v_trans = v->nb[1] > v->nb[2]; - - // split the batch into streams if needed -- const auto n_stream = k->ne[3]; -+ const auto n_stream = kv_rows ? kv_rows->ne[1] : k->ne[3]; - - // the stream dim steps over one stream's worth of dim-2 (tokens): (ne[2]/n_stream) rows of stride nb[2]. - // q->nb[3]/n_stream only equals that for a contiguous q; nope-only MLA (glm5-next) passes a permuted -@@ -2888,7 +3354,31 @@ ggml_tensor * llm_graph_context::build_attn_mha( - v = ggml_transpose(ctx0, v); - } - -+ const float softcap = hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f; -+ const auto configure_attention = [&](ggml_tensor * node) { -+ ggml_flash_attn_ext_add_sinks(node, sinks); -+ GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); -+ ggml_flash_attn_ext_set_n_kv_max(node, static_cast(n_kv_max)); -+ ggml_prec_set_acc(node, GGML_PREC_F32); -+ }; -+ if (kv_rows) { -+ // Query capability with the original stored types BEFORE adding -+ // any full-pool F32 conversion. This metadata node is not expanded -+ // if the device keeps this storage on ordinary attention. -+ cur = ggml_flash_attn_ext_rows(ctx0, q, k, v, fa_mask, kv_rows, -+ kq_scale, hparams.f_max_alibi_bias, softcap); -+ configure_attention(cur); -+ if (!supports_row_attn(cur, original_k)) { -+ GGML_ASSERT(dense_mask); -+ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, -+ sinks, v_mla, n_kv_max, kq_scale, il); -+ } -+ } -+ - // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) -+ // Supported F32 row paths retain ordinary FA's whole-pool conversion; -+ // row selection does not make that conversion proportional to live KV. -+ const bool convert_f32 = k->type == GGML_TYPE_F32 || v->type == GGML_TYPE_F32; - if (k->type == GGML_TYPE_F32) { - k = ggml_cast(ctx0, k, GGML_TYPE_F16); - } -@@ -2897,14 +3387,21 @@ ggml_tensor * llm_graph_context::build_attn_mha( - v = ggml_cast(ctx0, v, GGML_TYPE_F16); - } - -- cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias, -- hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); -- res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); -- -- ggml_flash_attn_ext_add_sinks(cur, sinks); -- GGML_ASSERT(n_kv_max >= 0 && n_kv_max <= INT32_MAX); -- ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); -- ggml_prec_set_acc(cur, GGML_PREC_F32); -+ if (!kv_rows || convert_f32) { -+ cur = kv_rows ? ggml_flash_attn_ext_rows(ctx0, q, k, v, fa_mask, -+ kv_rows, kq_scale, hparams.f_max_alibi_bias, softcap) : -+ ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, -+ kq_scale, hparams.f_max_alibi_bias, softcap); -+ configure_attention(cur); -+ } -+ if (kv_rows && !supports_row_attn(cur, original_k)) { -+ // Keep unsupported devices and K/V types on their existing native -+ // attention path, rather than copying the shared pool to the CPU. -+ GGML_ASSERT(dense_mask); -+ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, -+ sinks, v_mla, n_kv_max, kq_scale, il); -+ } -+ res->add_fused_node({kv_rows ? LLM_FUSED_OP_FLASH_ATTN_KV_ROWS : LLM_FUSED_OP_FLASH_ATTN, cur, il}); - - if (v_mla) { - #if 0 -@@ -3019,6 +3516,8 @@ llm_graph_input_attn_no_cache * llm_graph_context::build_attn_inp_no_cache() con - inp->self_kq_mask_swa_cnv = nullptr; - } - -+ request_inputs(inp.get()); -+ - return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp)); - } - -@@ -3103,6 +3602,8 @@ static std::unique_ptr build_attn_inp_kv_impl( - inp->self_kq_mask_cnv = inp->self_kq_mask; - } - -+ inp->build_row_inputs(ctx0, ubatch); -+ - inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); - inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); - -@@ -3113,6 +3614,7 @@ llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv() const { - const auto * mctx_cur = static_cast(mctx); - - auto inp = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur); -+ request_inputs(inp.get()); - - return (llm_graph_input_attn_kv *) res->add_input(std::move(inp)); - } -@@ -3164,17 +3666,30 @@ ggml_tensor * llm_graph_context::build_attn( - const auto & k_idxs = inp->get_k_idxs(); - const auto & v_idxs = inp->get_v_idxs(); - -- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); -- ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); -+ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); -+ ggml_tensor * v_write = mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il); -+ -+ ggml_build_forward_expand(gf, k_write); -+ ggml_build_forward_expand(gf, v_write); -+ -+ state_write(skippy_state_kind::kv_key, k_write, k_write, il); -+ state_write(skippy_state_kind::kv_value, v_write, v_write, il); - } - - k = mctx_cur->get_k(ctx0, il); - v = mctx_cur->get_v(ctx0, il); -+ -+ state_read(skippy_state_kind::kv_key, k, il); -+ state_read(skippy_state_kind::kv_value, v, il); - } - - ggml_tensor * kq_mask = inp->get_kq_mask(); - -- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); -+ // Bias-producing builders retain their existing dense mask and semantics. -+ const bool rows = inp->self_kv_rows != nullptr && kq_b == nullptr && v_mla == nullptr; -+ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, -+ rows ? inp->self_read_mask : kq_mask, sinks, v_mla, 0, kq_scale, il, -+ rows ? inp->self_kv_rows : nullptr, kq_mask); - cb(cur, "kqv_out", il); - - if (inp->self_v_rot) { -@@ -3226,6 +3741,7 @@ llm_graph_input_attn_k * llm_graph_context::build_attn_inp_k() const { - const auto * mctx_cur = static_cast(mctx); - - auto inp = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur); -+ request_inputs(inp.get()); - - return (llm_graph_input_attn_k *) res->add_input(std::move(inp)); - } -@@ -3256,7 +3772,9 @@ ggml_tensor * llm_graph_context::build_attn( - { - const auto & k_idxs = inp->get_k_idxs(); - -- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); -+ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); -+ ggml_build_forward_expand(gf, k_write); -+ state_write(skippy_state_kind::kv_key, k_write, k_write, il); - } - - const auto & kq_mask = inp->get_kq_mask(); -@@ -3265,6 +3783,8 @@ ggml_tensor * llm_graph_context::build_attn( - ggml_tensor * k = mctx_cur->get_k(ctx0, il); - ggml_tensor * v = ggml_view_4d(ctx0, k, v_cur->ne[0], k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); - -+ state_read(skippy_state_kind::kv_key, k, il); -+ - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); - cb(cur, "kqv_out", il); - -@@ -3320,6 +3840,8 @@ ggml_tensor * llm_graph_context::build_attn( - - const auto & kq_mask = inp->get_kq_mask_mla(); - -+ GGML_ASSERT(top_k != nullptr); -+ - // prepare new kq mask - starts filled with -INFINITY - ggml_tensor * kq_mask_all = ggml_fill(ctx0, kq_mask, -INFINITY); - -@@ -3422,13 +3944,17 @@ ggml_tensor * llm_graph_context::build_attn( - if (store_kv && k_cur) { - const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); - -- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); -+ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); -+ ggml_build_forward_expand(gf, k_write); -+ state_write(skippy_state_kind::kv_key, k_write, k_write, il); - } - - if (store_kv && v_cur) { - const auto & v_idxs = is_swa ? inp->get_v_idxs_swa() : inp->get_v_idxs(); - -- ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); -+ ggml_tensor * v_write = mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il); -+ ggml_build_forward_expand(gf, v_write); -+ state_write(skippy_state_kind::kv_value, v_write, v_write, il); - } - - const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); -@@ -3437,7 +3963,14 @@ ggml_tensor * llm_graph_context::build_attn( - ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); - ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - -- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); -+ state_read(skippy_state_kind::kv_key, k, il); -+ state_read(skippy_state_kind::kv_value, v, il); -+ -+ ggml_tensor * kv_rows = is_swa ? inp->self_kv_rows_swa : inp->self_kv_rows; -+ ggml_tensor * read_mask = is_swa ? inp->self_read_mask_swa : inp->self_read_mask; -+ const bool rows = kv_rows && !use_kv_cur && !kq_b && !v_mla; -+ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, rows ? read_mask : kq_mask, -+ sinks, v_mla, 0, kq_scale, il, rows ? kv_rows : nullptr, kq_mask); - cb(cur, "kqv_out", il); - - if (v_rot) { -@@ -3498,7 +4031,9 @@ ggml_tensor * llm_graph_context::build_attn( - if (k_cur) { - const auto & k_idxs = is_swa ? inp->get_k_idxs_swa() : inp->get_k_idxs(); - -- ggml_build_forward_expand(gf, mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il)); -+ ggml_tensor * k_write = mctx_cur->cpy_k(ctx0, k_cur, k_idxs, il); -+ ggml_build_forward_expand(gf, k_write); -+ state_write(skippy_state_kind::kv_key, k_write, k_write, il); - } - - const auto & kq_mask = is_swa ? inp->get_kq_mask_swa() : inp->get_kq_mask(); -@@ -3508,6 +4043,8 @@ ggml_tensor * llm_graph_context::build_attn( - ggml_tensor * k = mctx_cur->get_k(ctx0, il); - ggml_tensor * v = ggml_view_4d(ctx0, k, v_cur->ne[0], k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); - -+ state_read(skippy_state_kind::kv_key, k, il); -+ - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); - cb(cur, "kqv_out", il); - -@@ -3622,6 +4159,8 @@ llm_graph_input_attn_k_dsa * llm_graph_context::build_attn_inp_k_dsa() const { - - auto inp = build_attn_inp_k_dsa_impl(ctx0, ubatch, hparams, cparams, mctx_cur); - -+ request_inputs(inp.get()); -+ - return (llm_graph_input_attn_k_dsa *) res->add_input(std::move(inp)); - } + void synchronize(); -@@ -3639,6 +4178,7 @@ llm_graph_input_attn_k_dsa_iswa * llm_graph_context::build_attn_inp_k_dsa_iswa() - inp_swa->self_kq_mask_cnv = inp_swa->self_kq_mask; + const llama_model & get_model() const; + const llama_cparams & get_cparams() const; ++ const skippy_graph_build_inputs & get_graph_build_inputs() const; ++ uint64_t get_sched_reserve_count() const; ++#ifdef LLAMA_STAGE_BUILD_TESTS ++ void set_fused_gdn_for_test(bool fused_ar, bool fused_chunk); ++#endif - auto inp = std::make_unique(std::move(inp_dsa), std::move(inp_swa), mctx_cur); -+ request_inputs(inp.get()); + ggml_backend_sched_t get_sched() const; - return (llm_graph_input_attn_k_dsa_iswa *) res->add_input(std::move(inp)); - } -@@ -3668,6 +4208,8 @@ llm_graph_input_attn_kv_msa * llm_graph_context::build_attn_inp_kv_msa(bool msa_ - inp->self_k_idxs_idx = mctx_idx->build_input_k_idxs(ctx0, ubatch); - } +@@ -69,6 +99,7 @@ struct llama_context { + uint32_t n_ctx_seq() const; + uint32_t n_batch() const; + uint32_t n_ubatch() const; ++ bool kv_unified() const; + uint32_t n_seq_max() const; -+ request_inputs(inp.get()); -+ - return (llm_graph_input_attn_kv_msa *) res->add_input(std::move(inp)); - } + uint32_t n_threads() const; +@@ -78,6 +109,7 @@ struct llama_context { -@@ -3697,12 +4239,16 @@ llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const - inp->self_kq_mask_swa_cnv = inp->self_kq_mask_swa; - } + // return true if the memory was updated + bool memory_update(bool optimize); ++ bool memory_update(bool optimize, const skippy_graph_build_inputs & graph_build_inputs); -+ inp->build_row_inputs(ctx0, ubatch); -+ - inp->self_k_rot = mctx_cur->get_base()->build_input_k_rot(ctx0); - inp->self_v_rot = mctx_cur->get_base()->build_input_v_rot(ctx0); + enum llama_pooling_type pooling_type() const; - inp->self_k_rot_swa = mctx_cur->get_swa()->build_input_k_rot(ctx0); - inp->self_v_rot_swa = mctx_cur->get_swa()->build_input_v_rot(ctx0); +@@ -149,14 +181,19 @@ struct llama_context { + const llama_ubatch & ubatch, + llm_graph_type gtype, + llama_memory_context_i * mctx, +- ggml_status & ret); ++ ggml_status & ret, ++ const skippy_graph_build_inputs & graph_build_inputs = {}); -+ request_inputs(inp.get()); -+ - return (llm_graph_input_attn_kv_iswa *) res->add_input(std::move(inp)); - } + int encode(const llama_batch_ext & batch_inp); ++ int encode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + int decode(const llama_batch_ext & batch_inp); ++ int decode(const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); -@@ -3731,32 +4277,16 @@ llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa() const { + // compat version + int encode(const llama_batch & batch_inp); ++ int encode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); + int decode(const llama_batch & batch_inp); ++ int decode(const llama_batch & batch_inp, const skippy_graph_build_inputs & graph_build_inputs); - inp->self_k_rot_swa = mctx_cur->get_swa()->build_input_k_rot(ctx0); + // + // state save/load +@@ -263,13 +300,34 @@ public: -+ request_inputs(inp.get()); -+ - return (llm_graph_input_attn_k_iswa *) res->add_input(std::move(inp)); - } + // can reuse the llm_graph_result instance of the context (for example to update a memory module) + llm_graph_result * get_gf_res_reserve() const; ++ uint32_t admit_skippy_cache_capabilities(uint32_t memory_capabilities) { ++ if (!skippy_cache_admission_bound) { ++ skippy_cache_admitted_capabilities = skippy_cache_profile_seen ++ ? skippy_cache_capabilities & memory_capabilities : 0; ++ skippy_cache_admission_bound = true; ++ } ++ return skippy_cache_admitted_capabilities; ++ } ++ // live graph result of the most recent schedule, or null before the first build ++ llm_graph_result * get_gf_res_prev_active() const; - llm_graph_input_dsv4 * llm_graph_context::build_inp_dsv4() const { - const auto * mctx_cur = static_cast(mctx); -- const auto * raw_ctx = mctx_cur->get_raw(); -- -- auto inp_raw = std::make_unique(cparams, raw_ctx); -+ auto inp = llm_graph_input_dsv4_create(ctx0, hparams, cparams, ubatch, mctx_cur); + // returns the result of ggml_backend_sched_graph_compute_async execution + ggml_status graph_compute(ggml_cgraph * gf, bool batched); -- const int64_t n_stream = mctx_cur->get_csa_plan(ubatch).n_stream; -- -- GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE && "DSV4 expects SWA raw cache"); -- -- inp_raw->self_k_idxs = raw_ctx->build_input_k_idxs(ctx0, ubatch); -- inp_raw->self_kq_mask = dsv4_build_raw_kq_mask(ctx0, raw_ctx, ubatch, cparams, n_stream); -- inp_raw->self_kq_mask_cnv = inp_raw->self_kq_mask; -- -- inp_raw->self_k_rot = raw_ctx->build_input_k_rot(ctx0); -- auto inp = std::make_unique(cparams, std::move(inp_raw), mctx_cur); -- -- dsv4_build_comp_inputs(ctx0, inp->inp_csa, mctx_cur->get_csa_plan(ubatch), "csa", cparams, n_stream); -- dsv4_build_comp_inputs(ctx0, inp->inp_hca, mctx_cur->get_hca_plan(ubatch), "hca", cparams, n_stream); -- dsv4_build_comp_inputs(ctx0, inp->inp_lid, mctx_cur->get_lid_plan(ubatch), "lid", cparams, n_stream); -- inp->inp_csa.k_rot = mctx_cur->get_csa()->build_input_k_rot(ctx0); -- inp->inp_hca.k_rot = mctx_cur->get_hca()->build_input_k_rot(ctx0); -- inp->inp_lid.k_rot = mctx_cur->get_lid()->build_input_k_rot(ctx0); -+ request_inputs(inp.get()); - - return (llm_graph_input_dsv4 *) res->add_input(std::move(inp)); - } -@@ -3772,14 +4302,37 @@ ggml_tensor * llm_graph_context::build_rs( - uint32_t rs_size, - int32_t rs_zero, - const llm_graph_get_rows_fn & get_state_rows) const { -+ return build_rs_impl(s, state_copy, state_copy_main, state_size, n_seqs, -+ n_rs, rs_head, rs_size, rs_zero, get_state_rows, nullptr, -1); -+} + // reserve a graph with a dummy ubatch of the specified size +- ggml_cgraph * graph_reserve( +- uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only = false, size_t * sizes = nullptr); ++ ggml_cgraph * graph_reserve(uint32_t n_tokens, ++ uint32_t n_seqs, ++ uint32_t n_outputs, ++ const llama_memory_context_i * mctx, ++ bool split_only = false, ++ size_t * sizes = nullptr, ++ const skippy_graph_build_inputs & graph_build_inputs = {}, ++ bool embedding_input = false); + -+ggml_tensor * llm_graph_context::build_rs_impl( -+ ggml_tensor * s, -+ ggml_tensor * state_copy, -+ ggml_tensor * state_copy_main, -+ int32_t state_size, -+ int32_t n_seqs, -+ uint32_t n_rs, -+ uint32_t rs_head, -+ uint32_t rs_size, -+ int32_t rs_zero, -+ const llm_graph_get_rows_fn & get_state_rows, -+ const skippy_state_kind * kind, int il) const { - - GGML_UNUSED(rs_size); -+ if (kind != nullptr) { -+ state_read(*kind, s, il); -+ } - ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, s->ne[1]); - - // Clear a single state which will then be copied to the other cleared states. - // Note that this is a no-op when the view is zero-sized. - ggml_tensor * state_zero = ggml_view_1d(ctx0, states, state_size*(rs_zero >= 0), rs_zero*states->nb[1]*(rs_zero >= 0)); -- ggml_build_forward_expand(gf, ggml_scale_inplace(ctx0, state_zero, 0)); -+ ggml_tensor * zero_write = ggml_scale_inplace(ctx0, state_zero, 0); -+ ggml_build_forward_expand(gf, zero_write); -+ if (kind != nullptr) { -+ state_write(*kind, s, zero_write, il); -+ } - - // copy states - // NOTE: assuming the copy destinations are ALL contained between rs_head and rs_head + n_rs -@@ -3796,10 +4349,12 @@ ggml_tensor * llm_graph_context::build_rs( - - // copy extra states which won't be changed further (between n_seqs and n_rs) - ggml_tensor * states_extra = ggml_view_2d(ctx0, states_all, state_size, n_rs - n_seqs, states_all->nb[1], (n_seqs - i0)*states_all->nb[1]); -- ggml_build_forward_expand(gf, -- ggml_cpy(ctx0, -- states_extra, -- ggml_view_2d(ctx0, s, state_size, (n_rs - n_seqs), s->nb[1], (rs_head + n_seqs)*s->nb[1]))); -+ ggml_tensor * extra_destination = ggml_view_2d(ctx0, s, state_size, (n_rs - n_seqs), s->nb[1], (rs_head + n_seqs)*s->nb[1]); -+ ggml_tensor * extra_write = ggml_cpy(ctx0, states_extra, extra_destination); -+ ggml_build_forward_expand(gf, extra_write); -+ if (kind != nullptr) { -+ state_write(*kind, s, extra_write, il); -+ } - - return output_states; - } -@@ -3831,6 +4386,7 @@ llm_graph_input_rs * llm_graph_context::build_rs_inp() const { - const auto * mctx_cur = static_cast(mctx); ++ bool get_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; ++ bool get_input_activation_boundary(enum ggml_type & type, uint64_t & elements_per_token, uint64_t & bytes_per_token) const; ++ bool get_activation_frontier(std::vector & parts) const; ++ bool get_input_activation_frontier(std::vector & parts) const; - auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur); -+ request_inputs(inp.get()); + bool set_sampler(llama_seq_id seq_id, llama_sampler * sampler); - return (llm_graph_input_rs *) res->add_input(std::move(inp)); - } -@@ -3852,6 +4408,22 @@ ggml_tensor * llm_graph_context::build_rs( - get_state_rows); - } +@@ -280,7 +338,8 @@ private: + llm_graph_result * res, + const llama_ubatch & ubatch, + const llama_memory_context_i * mctx, +- llm_graph_type gtype) const; ++ llm_graph_type gtype, ++ const skippy_graph_build_inputs & graph_build_inputs = {}) const; -+ggml_tensor * llm_graph_context::build_rs( -+ llm_graph_input_rs * inp, -+ ggml_tensor * s, -+ int32_t state_size, -+ int32_t n_seqs, -+ skippy_state_kind kind, int il, -+ const llm_graph_get_rows_fn & get_state_rows) const { -+ const auto * kv_state = inp->mctx; -+ // the state kinds registered by this overload follow the same gather the plain overload uses -+ ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : inp->s_copy; -+ -+ return build_rs_impl(s, state_copy, inp->s_copy_main, state_size, n_seqs, -+ kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(), -+ get_state_rows, &kind, il); -+} -+ - ggml_tensor * llm_graph_context::build_rwkv_token_shift_load( - llm_graph_input_rs * inp, - const llama_ubatch & ubatch, -@@ -3866,7 +4438,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_load( + llm_graph_cb graph_get_cb() const; - ggml_tensor * token_shift = build_rs( - inp, token_shift_all, -- hparams.n_embd_r(), n_seqs); -+ hparams.n_embd_r(), n_seqs, skippy_state_kind::recurrent_conv, il); +@@ -295,7 +354,10 @@ private: - token_shift = ggml_reshape_3d(ctx0, token_shift, hparams.n_embd, token_shift_count, n_seqs); + // disable auto fused ops (Flash Attention, Gated Delta Net) whose op lands on a device + // that differs from the layer it belongs to (usually due to missing backend support) +- void resolve_fused_ops(const llama_memory_context_i * mctx, uint32_t n_seqs); ++ void resolve_fused_ops( ++ const llama_memory_context_i * mctx, ++ uint32_t n_seqs, ++ const skippy_graph_build_inputs & graph_build_inputs); -@@ -3886,11 +4458,14 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store( + // TODO: read/write lora adapters and cvec + size_t state_write_data(llama_io_write_i & io); +@@ -312,6 +374,10 @@ private: - const auto kv_head = mctx_cur->get_head(); + llama_cparams cparams; -- return ggml_cpy( -- ctx0, -- ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0), -- ggml_view_1d(ctx0, mctx_cur->get_r_l(il), hparams.n_embd_r()*n_seqs, hparams.n_embd_r()*kv_head*ggml_element_size(mctx_cur->get_r_l(il))) -- ); -+ ggml_tensor * token_shift_source = ggml_view_1d(ctx0, token_shift, n_embd * n_seqs * token_shift_count, 0); ++ const skippy_graph_build_inputs graph_build_inputs; ++ uint64_t computation_generation = 0; + -+ ggml_tensor * token_shift_destination = ggml_view_1d(ctx0, mctx_cur->get_r_l(il), hparams.n_embd_r()*n_seqs, -+ hparams.n_embd_r()*kv_head*ggml_element_size(mctx_cur->get_r_l(il))); + -+ ggml_tensor * token_shift_write = ggml_cpy(ctx0, token_shift_source, token_shift_destination); -+ state_write(skippy_state_kind::recurrent_conv, mctx_cur->get_r_l(il), token_shift_write, il); -+ return token_shift_write; - } - - llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { -@@ -3898,6 +4473,8 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { + llama_adapter_cvec_ptr cvec; + llama_adapter_loras_ptr loras; - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); - auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); -+ request_inputs(inp_rs.get()); -+ request_inputs(inp_attn.get()); +@@ -378,6 +444,7 @@ private: + ggml_backend_sched_ptr sched; - auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); + bool sched_need_reserve = true; ++ uint64_t sched_reserve_count = 0; -@@ -3909,6 +4486,8 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const + // whether the reserve graph has a logits tensor, set in sched_reserve() + // true until then, because the first output_reserve() runs before any graph is reserved +@@ -425,9 +492,32 @@ private: + // Separate arenas give batches with and without outputs distinct CUDA graph cache keys. + std::array gf_res_prev; + llm_graph_result_ptr gf_res_reserve; ++ // Intersect every reserved prefill/decode profile; no configuration can authorize state coverage. ++ uint32_t skippy_cache_capabilities = UINT32_MAX; ++ bool skippy_cache_profile_seen = false; ++ uint32_t skippy_cache_admitted_capabilities = 0; ++ bool skippy_cache_admission_bound = false; - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); - auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); -+ request_inputs(inp_rs.get()); -+ request_inputs(inp_attn.get()); + llm_graph_result * gf_res_prev_active = nullptr; - auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); ++ bool activation_boundary_observed = false; ++ bool activation_boundary_stable = true; ++ enum ggml_type activation_boundary_type = GGML_TYPE_COUNT; ++ uint64_t activation_boundary_elements_per_token = 0; ++ uint64_t activation_boundary_bytes_per_token = 0; ++ ++ bool input_activation_boundary_observed = false; ++ bool input_activation_boundary_stable = true; ++ enum ggml_type input_activation_boundary_type = GGML_TYPE_COUNT; ++ uint64_t input_activation_boundary_elements_per_token = 0; ++ uint64_t input_activation_boundary_bytes_per_token = 0; ++ bool activation_frontier_observed = false; ++ bool activation_frontier_stable = true; ++ std::vector activation_frontier; ++ bool input_activation_frontier_observed = false; ++ bool input_activation_frontier_stable = true; ++ std::vector input_activation_frontier; ++ + // host buffer for the model output (logits and embeddings) + ggml_backend_buffer_ptr buf_output; -@@ -3941,7 +4520,10 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() - inp_attn->self_kq_mask_swa_cnv = inp_attn->self_kq_mask_swa; - } +diff --git a/src/llama-ext.h b/src/llama-ext.h +index b55c0c357..9449e1da7 100644 +--- a/src/llama-ext.h ++++ b/src/llama-ext.h +@@ -75,6 +75,12 @@ LLAMA_API bool llama_quant_tensor_allows_quantization( + const quantize_state_impl * qs, + const ggml_tensor * tensor); -+ inp_attn->build_row_inputs(ctx0, ubatch); ++// Returns whether the selected tensor type requires importance weights. ++LLAMA_API bool llama_quant_tensor_requires_imatrix( ++ const ggml_tensor * tensor, ++ ggml_type type, ++ llama_ftype ftype); + - auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); -+ request_inputs(inp.get()); - - return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); - } + // Compute quantization type assignments for a list of tensors. + // All tensors should be quantizable (use llama_quant_tensor_allows_quantization to filter). + // result_types: caller-allocated array of n_tensors elements, filled with assigned types. diff --git a/src/llama-graph.h b/src/llama-graph.h index 9867c9540..7137c58d6 100644 --- a/src/llama-graph.h @@ -4780,19 +1516,6 @@ index 9867c9540..7137c58d6 100644 void set_input(const llama_ubatch * ubatch) override; -@@ -1246,7 +1280,11 @@ struct llm_graph_context { - ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] - int64_t n_kv_max, - float kq_scale, -- int il) const; -+ int il, -+ ggml_tensor * kv_rows = nullptr, -+ ggml_tensor * dense_mask = nullptr) const; -+ -+ bool supports_row_attn(const ggml_tensor * node, const ggml_tensor * storage) const; - - llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; - diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index f05b5d6bb..1a554d204 100644 --- a/src/llama-hparams.cpp @@ -6160,10 +2883,7 @@ index a1ec67e26..3648d3207 100644 + if (record_index >= record_count) { + error = "CacheGen records do not cover the native KV page"; + return false; - } -- -- for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) { -- cells.seq_add(idx, ubatch.seq_id[i][s]); ++ } + const auto & record = records[record_index++]; + const size_t rows = static_cast(record.token_count); + uint32_t expected_kind = SKIPPY_CACHEGEN_RECORD_F16; @@ -6192,12 +2912,11 @@ index a1ec67e26..3648d3207 100644 + error = "CacheGen record order or destination geometry is invalid"; + } + return false; - } ++ } + entry.tiles.push_back({ record.payload, record.payload_bytes, static_cast(token_offset), + static_cast(rows) }); + token_offset += rows; - } -- } ++ } + storage.push_back(std::move(entry)); + logical_offset += static_cast(desc.token_count) * row_bytes; + return true; @@ -7056,8 +3775,6 @@ index 5aafbebb3..152da5166 100644 uint32_t get_n_kv() const; uint32_t get_n_kv_rows() const; + uint32_t get_n_kv_pos_contiguous() const; -+ uint32_t get_n_kv_rows() const; -+ void set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const; ggml_type type_k() const; ggml_type type_v() const; @@ -7092,12 +3809,6 @@ index 5aafbebb3..152da5166 100644 // // update context -@@ -470,4 +552,5 @@ private: - // a heuristic, to avoid attending the full cache if it is not yet utilized - // as the cache gets filled, the benefit from this heuristic disappears - int32_t n_kv; -+ uint32_t n_kv_rows = 0; - }; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 85a8e0f75..4b50afe71 100644 --- a/src/llama-kv-cells.h @@ -7107,7 +3818,6 @@ index 85a8e0f75..4b50afe71 100644 seq_pos[s].clear(); std::fill(seq_bits[s].begin(), seq_bits[s].end(), 0); + seq_pos_index_mismatch[s] = 0; -+ std::fill(seq_bits[s].begin(), seq_bits[s].end(), 0); } } @@ -7122,34 +3832,34 @@ index 85a8e0f75..4b50afe71 100644 + assert(isrc < pos.size()); + assert(idst < pos.size()); + assert(isrc != idst); -+ -+ assert(pos[idst] == -1); -+ assert(seq[idst].none()); -+ assert(pos[isrc] != -1); - // assert(pos[idst] == -1); - // assert(pos[isrc] != -1); -+ seq_pos_rm(isrc); ++ assert(pos[idst] == -1); ++ assert(seq[idst].none()); ++ assert(pos[isrc] != -1); - // pos [idst] = pos [isrc]; - // shift[idst] = shift[isrc]; - // seq [idst] = seq [isrc]; ++ seq_pos_rm(isrc); + +- // pos [isrc] = -1; +- // shift[isrc] = 0; +- // seq [isrc].reset(); + pos [idst] = pos [isrc]; + ext [idst] = ext [isrc]; + shift[idst] = shift[isrc]; + seq [idst] = seq [isrc]; -- // pos [isrc] = -1; -- // shift[isrc] = 0; -- // seq [isrc].reset(); +- // used.erase (isrc); +- // used.insert(idst); +- //} + pos [isrc] = -1; + ext [isrc].reset(); + shift[isrc] = 0; + seq [isrc].reset(); - -- // used.erase (isrc); -- // used.insert(idst); -- //} ++ + used.erase (isrc); + used.insert(idst); + @@ -7178,45 +3888,6 @@ index 85a8e0f75..4b50afe71 100644 + return positions.begin()->first == 0 && pos_max >= 0 && + positions.size() == static_cast(pos_max) + 1; + } -+ -+ uint32_t seq_n_cells(llama_seq_id seq_id) const { -+ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); -+ return seq_pos[seq_id].size(); -+ } -+ -+ uint32_t seq_n_cells(llama_seq_id seq_id, llama_pos p_min) const { -+ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); -+ const auto & positions = seq_pos[seq_id]; -+ return std::distance(positions.lower_bound({p_min, 0}), positions.end()); -+ } -+ -+ // One ascending physical-cell list per owner, padded with -1. Shared -+ // cells appear in every owner's list; position cutoffs only remove rows -+ // hidden by SWA from every query of that slice. -+ void get_seq_cells(const std::vector & seq_ids, -+ const std::vector & p_min, int32_t * data, int64_t n_per_seq) const { -+ assert(!seq_ids.empty()); -+ assert(p_min.empty() || p_min.size() == seq_ids.size()); -+ const uint32_t n_words = (used_max_p1() + 63) / 64; -+ for (size_t s = 0; s < seq_ids.size(); ++s) { -+ assert(seq_ids[s] >= 0 && seq_ids[s] < LLAMA_MAX_SEQ); -+ const auto & bits = seq_bits[seq_ids[s]]; -+ const uint32_t n_w = std::min(n_words, bits.size()); -+ const llama_pos minimum = p_min.empty() ? 0 : p_min[s]; -+ int32_t * dst = data + s * n_per_seq; -+ int32_t * end = dst + n_per_seq; -+ for (uint32_t w = 0; w < n_w; ++w) { -+ for (uint64_t b = bits[w]; b != 0; b &= b - 1) { -+ const int32_t cell = 64 * w + llama_kv_ctz64(b); -+ if (pos[cell] >= minimum) { -+ GGML_ASSERT(dst < end); -+ *dst++ = cell; -+ } -+ } -+ } -+ std::fill(dst, end, -1); -+ } -+ } + // note: call only if the cell is not empty llama_pos pos_get(uint32_t i) const { @@ -7247,120 +3918,9 @@ index 85a8e0f75..4b50afe71 100644 + if (pos[i] != static_cast(i)) { + ++seq_pos_index_mismatch[s]; + } -+ if (seq_bits[s].empty()) { -+ seq_bits[s].assign((pos.size() + 63) / 64, 0); -+ } -+ seq_bits[s][i / 64] |= 1ull << (i % 64); } // remove cell i -diff --git a/src/llama-kv-rows.cpp b/src/llama-kv-rows.cpp -new file mode 100644 -index 000000000..57608f5ae ---- /dev/null -+++ b/src/llama-kv-rows.cpp -@@ -0,0 +1,101 @@ -+#include "llama-kv-cache.h" -+ -+#include "ggml-backend.h" -+ -+#include -+#include -+ -+uint32_t llama_kv_cache::get_n_kv_slices(const llama_ubatch & ubatch) { -+ if (!ubatch.n_tokens || !ubatch.n_seqs_unq || !ubatch.n_seq_id || !ubatch.seq_id || -+ !ubatch.seq_id_unq || ubatch.decision_order) { -+ return 0; -+ } -+ uint32_t slices = 0; -+ if (ubatch.n_seqs_unq == 1) { -+ slices = 1; -+ } else if (ubatch.equal_seqs() && ubatch.n_seqs == ubatch.n_seqs_unq) { -+ slices = ubatch.n_seqs; -+ } else if (ubatch.n_tokens == ubatch.n_seqs_unq) { -+ slices = ubatch.n_tokens; -+ } -+ if (!slices || ubatch.n_tokens % slices != 0) { -+ return 0; -+ } -+ // Query blocks determine stream order, not seq_id_unq's enumeration order. -+ const uint32_t per_slice = ubatch.n_tokens / slices; -+ std::set actual, expected; -+ for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { -+ expected.insert(ubatch.seq_id_unq[s]); -+ } -+ for (uint32_t s = 0; s < slices; ++s) { -+ const uint32_t first = s * per_slice; -+ if (ubatch.n_seq_id[first] != 1 || !ubatch.seq_id[first]) { -+ return 0; -+ } -+ const auto owner = ubatch.seq_id[first][0]; -+ if (owner < 0 || owner >= LLAMA_MAX_SEQ || !actual.insert(owner).second) { -+ return 0; -+ } -+ for (uint32_t i = first; i < first + per_slice; ++i) { -+ if (ubatch.n_seq_id[i] != 1 || !ubatch.seq_id[i] || ubatch.seq_id[i][0] != owner) { -+ return 0; -+ } -+ } -+ } -+ return actual == expected ? slices : 0; -+} -+ -+std::vector llama_kv_cache::get_kv_rows_p_min(const llama_ubatch & ubatch, uint32_t n_slices) const { -+ if (!n_swa || (swa_type != LLAMA_SWA_TYPE_STANDARD && swa_type != LLAMA_SWA_TYPE_CHUNKED)) { -+ return {}; -+ } -+ GGML_ASSERT(n_slices && ubatch.pos && ubatch.n_tokens % n_slices == 0); -+ const uint32_t per_slice = ubatch.n_tokens / n_slices; -+ std::vector result(n_slices); -+ for (uint32_t s = 0; s < n_slices; ++s) { -+ const auto * begin = ubatch.pos + s * per_slice; -+ const llama_pos minimum = *std::min_element(begin, begin + per_slice); -+ result[s] = swa_type == LLAMA_SWA_TYPE_STANDARD ? minimum - (llama_pos) n_swa + 1 : -+ (minimum / (llama_pos) n_swa) * (llama_pos) n_swa; -+ } -+ return result; -+} -+ -+uint32_t llama_kv_cache::get_n_kv_rows(const llama_ubatch & ubatch) const { -+ const uint32_t slices = get_n_kv_slices(ubatch); -+ if (n_stream != 1 || !slices) { -+ return 0; -+ } -+ const auto & cells = v_cells[0]; -+ const auto minimum = get_kv_rows_p_min(ubatch, slices); -+ const uint32_t per_slice = ubatch.n_tokens / slices; -+ uint32_t maximum = 0; -+ for (uint32_t s = 0; s < slices; ++s) { -+ const auto owner = ubatch.seq_id[s * per_slice][0]; -+ const auto count = minimum.empty() ? cells.seq_n_cells(owner) : cells.seq_n_cells(owner, minimum[s]); -+ maximum = std::max(maximum, count); -+ } -+ return std::min(GGML_PAD(maximum, 256u), get_size()); -+} -+ -+void llama_kv_cache::set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const { -+ GGML_ASSERT(rows && rows->buffer && ggml_backend_buffer_is_host(rows->buffer)); -+ GGML_ASSERT(n_stream == 1 && rows->type == GGML_TYPE_I32 && ggml_is_contiguous(rows)); -+ const uint32_t slices = get_n_kv_slices(*ubatch); -+ GGML_ASSERT(slices && rows->ne[1] == slices && rows->ne[2] == 1 && rows->ne[3] == 1); -+ const uint32_t per_slice = ubatch->n_tokens / slices; -+ std::vector owners(slices); -+ for (uint32_t s = 0; s < slices; ++s) { -+ owners[s] = ubatch->seq_id[s * per_slice][0]; -+ } -+ v_cells[0].get_seq_cells(owners, get_kv_rows_p_min(*ubatch, slices), -+ static_cast(rows->data), rows->ne[0]); -+} -+ -+uint32_t llama_kv_cache_context::get_n_kv_rows() const { -+ return n_kv_rows; -+} -+ -+void llama_kv_cache_context::set_input_kv_rows(ggml_tensor * rows, const llama_ubatch * ubatch) const { -+ kv->set_input_kv_rows(rows, ubatch); -+} diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 9213ac1dc..b7570d445 100644 --- a/src/llama-memory-recurrent.cpp diff --git a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch index 4a22b660de..34e9e0a62d 100644 --- a/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch +++ b/skippy/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch @@ -2584,7 +2584,7 @@ index 5e6099ce1..8c21125d5 100644 X(FA_AUX, fa_aux) \ X(FA_F16, fa_f16) \ X(FA_F32, fa_f32) \ -@@ -180,6 +183,11 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi +@@ -180,6 +183,11 @@ struct ggml_metal_library { ggml_metal_device_t dev; ggml_metal_pipelines_t pipelines; // cache of compiled pipelines @@ -3410,7 +3410,7 @@ index 426c48741..0a5980aaa 100644 # # libraries -@@ -47,6 +48,51 @@ set(LLAMA_CORE_SOURCES +@@ -47,6 +48,50 @@ set(LLAMA_CORE_SOURCES add_library(llama ../include/llama.h ${LLAMA_CORE_SOURCES} @@ -3453,7 +3453,6 @@ index 426c48741..0a5980aaa 100644 + skippy/stage_realization.cpp + skippy/stage_execution_contract.cpp + skippy/state.cpp -+ skippy/resident_prefix.cpp + skippy/state_memory.cpp + skippy/state_effects.cpp + skippy/speculative_decoding.cpp @@ -3744,7 +3743,6 @@ index 426c48741..0a5980aaa 100644 + target_link_libraries(skippy-graph-build-inputs PRIVATE llama) + add_dependencies(skippy-stage-slice-plan skippy-graph-build-inputs skippy-profile-residency) + add_test(NAME skippy_decode_input_width COMMAND skippy-graph-build-inputs --input-width) -+ add_test(NAME skippy_iswa_row_inputs COMMAND skippy-graph-build-inputs --iswa-rows) + + add_test( + NAME skippy_graph_build_inputs @@ -3773,14 +3771,12 @@ index 426c48741..0a5980aaa 100644 + set_tests_properties(skippy_generate_gemma_fixture PROPERTIES + FIXTURES_SETUP skippy-model-loader-fixtures) + -+ add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) ++ add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) + target_include_directories(skippy-sampling-history PRIVATE .) + target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) + target_link_libraries(skippy-sampling-history PRIVATE llama) -+ add_test(NAME skippy_resident_checkpoint_gpu_long COMMAND skippy-sampling-history resident-gpu-long) -+ set_tests_properties(skippy_resident_checkpoint_gpu_long PROPERTIES SKIP_RETURN_CODE 77) + function(add_skippy_sampling_history_tests family fixture state) -+ foreach(mode grammar penalty resident) ++ foreach(mode grammar penalty) + add_test(NAME skippy_sampling_history_${family}_${mode} + COMMAND skippy-sampling-history + "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index cf9189a48a..055f77523b 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -13,14 +13,13 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts .../tests/hardware_application_probe.cpp | 76 + src/skippy/tests/input_capabilities.cpp | 78 + .../tests/input_leaf_state_regression.h | 49 + - src/skippy/tests/iswa_row_inputs_cases.hpp | 307 +++ src/skippy/tests/live_graph_reference.h | 194 ++ src/skippy/tests/noalloc_graph_planning.cpp | 1137 +++++++++++ src/skippy/tests/profile_residency.cpp | 258 +++ .../tests/renamed_multishard_planning.cpp | 1665 +++++++++++++++++ .../tests/residual_checkpoint_regression.h | 52 + src/skippy/tests/runtime_events.cpp | 695 +++++++ - src/skippy/tests/sampling_history.cpp | 967 ++++++++++ + src/skippy/tests/sampling_history.cpp | 517 +++++ src/skippy/tests/stage_plan_header.c | 10 + src/skippy/tests/stage_plan_header.cpp | 13 + src/skippy/tests/stage_slice_plan.cpp | 1198 ++++++++++++ @@ -28,14 +27,13 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts tests/test-chat-auto-parser.cpp | 47 + tests/test-chat.cpp | 189 +- tests/test-deepseek4-mtp.h | 88 + - tests/test-flash-attn-rows.cpp | 536 ++++++ tests/test-graph-contract-fixture.h | 155 ++ tests/test-llama-archs.cpp | 351 +++- tests/test-reasoning-budget.cpp | 24 + tests/test-skippy-activation-validation.cpp | 18 + tests/test-skippy-cachegen-import.cpp | 347 ++++ tests/test-skippy-cachegen-metal.cpp | 399 ++++ - tests/test-skippy-kv-cells-contiguous.cpp | 118 ++ + tests/test-skippy-kv-cells-contiguous.cpp | 20 + tests/test-skippy-kv-page-export.cpp | 367 ++++ tests/test-skippy-model-loader-accounting.cpp | 320 ++++ .../test-skippy-recurrent-state-roundtrip.cpp | 160 ++ @@ -52,12 +50,10 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts create mode 100644 src/skippy/tests/hardware_application_probe.cpp create mode 100644 src/skippy/tests/input_capabilities.cpp create mode 100644 src/skippy/tests/input_leaf_state_regression.h - create mode 100644 src/skippy/tests/iswa_row_inputs_cases.hpp create mode 100644 src/skippy/tests/live_graph_reference.h create mode 100644 src/skippy/tests/noalloc_graph_planning.cpp create mode 100644 src/skippy/tests/profile_residency.cpp create mode 100644 src/skippy/tests/renamed_multishard_planning.cpp - create mode 100644 src/skippy/tests/resident_checkpoint_gpu.cpp create mode 100644 src/skippy/tests/residual_checkpoint_regression.h create mode 100644 src/skippy/tests/runtime_events.cpp create mode 100644 src/skippy/tests/sampling_history.cpp @@ -65,7 +61,6 @@ Subject: [PATCH 06/15] test(skippy): cover live graph and state contracts create mode 100644 src/skippy/tests/stage_plan_header.cpp create mode 100644 src/skippy/tests/stage_slice_plan.cpp create mode 100644 tests/test-deepseek4-mtp.h - create mode 100644 tests/test-flash-attn-rows.cpp create mode 100644 tests/test-graph-contract-fixture.h create mode 100644 tests/test-skippy-activation-validation.cpp create mode 100644 tests/test-skippy-cachegen-import.cpp @@ -239,8 +234,6 @@ index 000000000..cd2e4af3f +#include +#include + -+#include "iswa_row_inputs_cases.hpp" -+ +class recording_input final : public llm_graph_input_i { +public: + void set_build_inputs(const skippy_graph_build_inputs & inputs) override { @@ -785,7 +778,6 @@ index 000000000..cd2e4af3f +static const char * fused_op_name(llm_fused_op op) { + switch (op) { + case LLM_FUSED_OP_FLASH_ATTN: return "flash attention"; -+ case LLM_FUSED_OP_FLASH_ATTN_KV_ROWS: return "flash attention with KV rows"; + case LLM_FUSED_OP_GDN_AR: return "Gated Delta Net (autoregressive)"; + case LLM_FUSED_OP_GDN_CH: return "Gated Delta Net (chunked)"; + case LLM_FUSED_OP_LIGHTNING_INDEXER: return "Lightning Indexer"; @@ -1125,12 +1117,6 @@ index 000000000..cd2e4af3f + if (const int rc = check_embedding_execution_profiles()) { + return rc; + } -+ if (argc == 2 && std::strcmp(argv[1], "--iswa-rows") == 0) { -+ llama_backend_init(); -+ const int rc = check_iswa_row_inputs(); -+ llama_backend_free(); -+ return rc; -+ } + if (argc == 2 && std::strcmp(argv[1], "--input-width") == 0) { + return check_decode_input_width(); + } @@ -1889,319 +1875,6 @@ index 000000000..33d3faca9 + if (skippy_infer_state_effects({}, graph, boundaries, effects, error)) { return 96; } + return 0; +} -diff --git a/src/skippy/tests/iswa_row_inputs_cases.hpp b/src/skippy/tests/iswa_row_inputs_cases.hpp -new file mode 100644 -index 000000000..331607a34 ---- /dev/null -+++ b/src/skippy/tests/iswa_row_inputs_cases.hpp -@@ -0,0 +1,307 @@ -+#pragma once -+ -+#include "llama-kv-cache-iswa.h" -+#include "llama-memory-hybrid-iswa.h" -+ -+#include -+#include -+#include -+ -+// A tiny native cache/graph fixture, not a synthetic model certification. No -+// weights or family builders: the actual generic ISWA builder and two caches -+// own all row lists, masks, allocation, reuse and attention computations below. -+class iswa_row_fixture_model final : public llama_model { -+public: -+ iswa_row_fixture_model() : llama_model(llama_model_default_params()) { -+ arch = LLM_ARCH_LLAMA; -+ attn_rot = false; -+ hparams.n_layer_all = 2; -+ hparams.n_embd = 64; -+ hparams.n_embd_head_k_full = hparams.n_embd_head_v_full = 64; -+ hparams.n_embd_head_k_swa = hparams.n_embd_head_v_swa = 64; -+ hparams.n_head_arr.fill(1); -+ hparams.n_head_kv_arr.fill(1); -+ hparams.is_swa_impl[1] = 1; -+ hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; -+ hparams.n_swa = 2; -+ } -+ void load_stats(llama_model_loader &) override {} -+ void load_hparams(llama_model_loader &) override {} -+ void load_vocab(llama_model_loader &) override {} -+ bool load_tensors(llama_model_loader &) override { return false; } -+ void load_arch_hparams(llama_model_loader &) override {} -+ void load_arch_tensors(llama_model_loader &) override {} -+ std::unique_ptr build_arch_graph(const llm_graph_params &) const override { return nullptr; } -+}; -+ -+static void iswa_row_require(bool condition, const char * message) { -+ if (!condition) throw std::runtime_error(message); -+} -+ -+static llama_ubatch iswa_row_batch(uint32_t per_owner, llama_pos first, bool two_owners) { -+ llama_ubatch batch = {}; -+ batch.b_equal_seqs = 1; -+ batch.n_seq_tokens = per_owner; -+ batch.n_seqs = batch.n_seqs_unq = two_owners ? 2 : 1; -+ batch.n_tokens = per_owner * batch.n_seqs; -+ batch.n_pos = 1; -+ batch.data = std::make_shared(); -+ auto & data = *batch.data; -+ data.token.assign(batch.n_tokens, 1); -+ data.pos.resize(batch.n_tokens); -+ data.n_seq_id.assign(batch.n_tokens, 1); -+ data.seq_id_data.resize(batch.n_tokens); -+ data.seq_id.resize(batch.n_tokens); -+ data.seq_id_unq = two_owners ? std::vector{0, 1} : std::vector{0}; -+ data.output.assign(batch.n_tokens, 1); -+ data.seq_idx.assign(LLAMA_MAX_SEQ, -1); -+ for (uint32_t i = 0; i < batch.n_seqs_unq; ++i) data.seq_idx[data.seq_id_unq[i]] = i; -+ for (uint32_t i = 0; i < batch.n_tokens; ++i) { -+ // Deliberately different from seq_id_unq order: Q blocks own stream order. -+ data.seq_id_data[i] = two_owners ? 1 - i/per_owner : 0; -+ data.seq_id[i] = &data.seq_id_data[i]; -+ data.pos[i] = first + i%per_owner; -+ } -+ batch.token = data.token.data(); -+ batch.pos = data.pos.data(); -+ batch.n_seq_id = data.n_seq_id.data(); -+ batch.seq_id = data.seq_id.data(); -+ batch.seq_id_unq = data.seq_id_unq.data(); -+ batch.output = data.output.data(); -+ batch.seq_idx = data.seq_idx.data(); -+ return batch; -+} -+ -+static std::unique_ptr iswa_row_apply( -+ llama_kv_cache_iswa & cache, const llama_ubatch & batch) { -+ auto base = cache.get_base()->prepare({batch}); -+ auto swa = cache.get_swa()->prepare({batch}); -+ iswa_row_require(base.size() == 1 && swa.size() == 1, "ISWA prepare both pools"); -+ auto context = std::make_unique( -+ &cache, std::move(base), std::move(swa), std::vector{batch}); -+ iswa_row_require(context->apply(), "ISWA apply both pools"); -+ return context; -+} -+ -+static void iswa_row_check_pool( -+ const llama_kv_cache & cache, const llama_ubatch & batch, -+ const ggml_tensor * rows, const ggml_tensor * mask, bool swa) { -+ iswa_row_require(rows && mask && rows->buffer && mask->buffer, "ISWA both live inputs allocated"); -+ iswa_row_require(rows->type == GGML_TYPE_I32 && rows->ne[0] >= 256 && rows->ne[0] % 256 == 0 && rows->ne[1] == 2 && -+ mask->type == GGML_TYPE_F16 && mask->ne[0] == rows->ne[0] && mask->ne[1] == 2 && mask->ne[3] == 2, -+ "ISWA row/mask geometry"); -+ const uint32_t width = static_cast(rows->ne[0]); -+ const auto * actual_rows = static_cast(rows->data); -+ const auto * actual_mask = static_cast(mask->data); -+ for (uint32_t stream = 0; stream < 2; ++stream) { -+ const llama_seq_id owner = batch.seq_id[stream*2][0]; -+ const auto & cells = cache.get_cells(owner); -+ std::vector expected; -+ for (uint32_t physical = 0; physical < cells.size(); ++physical) { -+ // Independent scalar scan of actual membership and the known 2-row window. -+ if (cells.seq_has(physical, owner) && (!swa || cells.pos_get(physical) >= batch.pos[stream*2] - 1)) { -+ expected.push_back(static_cast(physical)); -+ } -+ } -+ iswa_row_require(!expected.empty() && expected.size() < width, "ISWA nonempty bounded expected rows"); -+ for (uint32_t column = 0; column < width; ++column) { -+ const int32_t physical = column < expected.size() ? expected[column] : -1; -+ iswa_row_require(actual_rows[stream*width + column] == physical, "ISWA current ascending owner rows"); -+ for (uint32_t q = 0; q < 2; ++q) { -+ const llama_pos query = batch.pos[stream*2 + q]; -+ const bool visible = physical >= 0 && cells.pos_get(physical) <= query && -+ (!swa || cells.pos_get(physical) > query - 2); -+ const float value = ggml_fp16_to_fp32(actual_mask[(stream*2 + q)*width + column]); -+ iswa_row_require(visible ? value == 0.0f : (std::isinf(value) && value < 0), -+ "ISWA exact causal/SWA compact mask"); -+ } -+ } -+ } -+} -+ -+static void iswa_row_check_bindings(const llm_graph_result & result, const llm_graph_input_attn_kv_iswa & input) { -+ const std::pair expected[] = { -+ {input.self_kv_rows, "attention.base.read_rows.0"}, -+ {input.self_read_mask, "attention.base.read_mask.0"}, -+ {input.self_kv_rows_swa, "attention.swa.read_rows.0"}, -+ {input.self_read_mask_swa, "attention.swa.read_mask.0"}, -+ }; -+ for (const auto & item : expected) { -+ iswa_row_require(item.first != nullptr, "ISWA missing declared input"); -+ const auto & bindings = result.get_request_input_bindings(); -+ const auto count = std::count_if(bindings.begin(), bindings.end(), [&](const skippy_request_input_binding & binding) { -+ return binding.tensor == item.first && binding.identity == item.second; -+ }); -+ iswa_row_require(count == 1, "ISWA semantic input binding"); -+ } -+} -+ -+static int check_iswa_row_inputs() { -+ try { -+ iswa_row_fixture_model model; -+ llama_kv_cache_iswa cache(model, GGML_TYPE_F16, GGML_TYPE_F16, false, false, -+ false, true, 512, 3, 16, 256, nullptr, nullptr, nullptr, nullptr); -+ auto prefix = iswa_row_batch(8, 0, false); -+ auto prefix_context = iswa_row_apply(cache, prefix); -+ cache.seq_cp(0, 1, -1, -1); -+ cache.seq_cp(0, 2, -1, -1); // parked owner keeps the shared prefix live -+ auto first = iswa_row_batch(2, 8, true); -+ auto first_context = iswa_row_apply(cache, first); -+ ggml_backend_ptr cpu(ggml_backend_cpu_init()); -+ iswa_row_require(cpu != nullptr, "ISWA CPU backend"); -+ ggml_backend_t backends[] = {cpu.get()}; -+ ggml_backend_sched_ptr scheduler(ggml_backend_sched_new(backends, nullptr, 1, 512, false, true)); -+ iswa_row_require(scheduler != nullptr, "ISWA CPU scheduler"); -+ llm_graph_result result(512); -+ llm_graph_params params = {}; -+ params.arch = model.arch; -+ params.hparams = model.hparams; -+ params.cparams.flash_attn = params.cparams.fused_kv_rows = true; -+ params.cparams.kv_unified = params.cparams.causal_attn = params.cparams.offload_kqv = true; -+ params.cparams.n_ctx = 512; -+ params.cparams.n_seq_max = 3; -+ params.ubatch = first; -+ params.mctx = first_context.get(); -+ params.sched = scheduler.get(); -+ params.backend_cpu = cpu.get(); -+ params.res = &result; -+ llm_graph_context graph(params); -+ auto * input = graph.build_attn_inp_kv_iswa(); -+ iswa_row_check_bindings(result, *input); -+ auto * q = ggml_new_tensor_3d(result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); -+ ggml_set_input(q); -+ std::vector outputs; -+ for (int layer = 0; layer < 2; ++layer) { -+ outputs.push_back(graph.build_attn(input, nullptr, nullptr, nullptr, q, nullptr, nullptr, -+ nullptr, nullptr, nullptr, 0.125f, layer)); -+ } -+ const auto & fused = result.get_fused_nodes(); -+ iswa_row_require(fused.size() == 2, "ISWA both attention layers"); -+ for (const auto & node : fused) { -+ const bool swa = model.hparams.is_swa(node.il); -+ iswa_row_require(node.op == LLM_FUSED_OP_FLASH_ATTN_KV_ROWS && node.tensor->src[6] == nullptr && -+ node.tensor->src[5] == (swa ? input->self_kv_rows_swa : input->self_kv_rows) && -+ node.tensor->src[3] == (swa ? input->self_read_mask_swa : input->self_read_mask) && -+ ggml_backend_supports_op(cpu.get(), node.tensor), "ISWA per-layer pool/route admission"); -+ } -+ iswa_row_require(ggml_backend_sched_alloc_graph(scheduler.get(), result.get_gf()), "ISWA graph allocation"); -+ std::vector zeros(64*4, 0.0f); -+ ggml_backend_tensor_set(q, zeros.data(), 0, zeros.size()*sizeof(float)); -+ const auto execute = [&](const llama_ubatch & batch) { -+ result.set_inputs(&batch); -+ iswa_row_check_pool(*cache.get_base(), batch, input->self_kv_rows, input->self_read_mask, false); -+ iswa_row_check_pool(*cache.get_swa(), batch, input->self_kv_rows_swa, input->self_read_mask_swa, true); -+ iswa_row_require(ggml_backend_sched_graph_compute(scheduler.get(), result.get_gf()) == GGML_STATUS_SUCCESS, -+ "ISWA finite graph compute"); -+ for (auto * output : outputs) { -+ std::vector values(ggml_nelements(output)); -+ ggml_backend_tensor_get(output, values.data(), 0, values.size()*sizeof(float)); -+ for (float value : values) iswa_row_require(std::isfinite(value) && value == 0.0f, "ISWA zero-KV finite output"); -+ } -+ }; -+ execute(first); -+ auto next = iswa_row_batch(2, 10, true); -+ auto next_context = iswa_row_apply(cache, next); -+ params.ubatch = next; -+ params.mctx = next_context.get(); -+ iswa_row_require(input->can_reuse(params) && input->mctx == next_context.get(), "ISWA refresh actual current mctx"); -+ execute(next); -+ for (const auto * pool : {cache.get_base(), cache.get_swa()}) { -+ const auto & cells = pool->get_cells(2); -+ for (uint32_t i = 0; i < 8; ++i) { -+ iswa_row_require(cells.seq_has(i, 0) && cells.seq_has(i, 1) && cells.seq_has(i, 2) && -+ cells.pos_get(i) == static_cast(i), "ISWA shared parked prefix retained"); -+ } -+ } -+ // Exercise the hybrid caller with real typed contexts too. The fixture -+ // has no recurrent layers: this checks attention delegation, not RS math. -+ llama_memory_hybrid_iswa hybrid(model, GGML_TYPE_F16, GGML_TYPE_F16, false, false, -+ 512, 16, 256, GGML_TYPE_F32, GGML_TYPE_F32, 3, 3, 0, false, true, -+ nullptr, [](int32_t) { return false; }); -+ auto * hybrid_cache = hybrid.get_mem_attn(); -+ auto hybrid_prefix = iswa_row_apply(*hybrid_cache, prefix); -+ hybrid_cache->seq_cp(0, 1, -1, -1); -+ hybrid_cache->seq_cp(0, 2, -1, -1); -+ auto hybrid_first = iswa_row_apply(*hybrid_cache, first); -+ auto hybrid_context = hybrid.init_full(); -+ auto * old_hybrid_context = static_cast(hybrid_context.get()); -+ ggml_backend_sched_ptr hybrid_scheduler(ggml_backend_sched_new(backends, nullptr, 1, 512, false, true)); -+ iswa_row_require(hybrid_scheduler != nullptr, "hybrid ISWA CPU scheduler"); -+ llm_graph_result hybrid_result(512); -+ auto hybrid_params = params; -+ hybrid_params.ubatch = first; -+ hybrid_params.mctx = hybrid_context.get(); -+ hybrid_params.res = &hybrid_result; -+ hybrid_params.sched = hybrid_scheduler.get(); -+ llm_graph_context hybrid_graph(hybrid_params); -+ auto * hybrid_input = hybrid_graph.build_inp_mem_hybrid_iswa(); -+ iswa_row_check_bindings(hybrid_result, *hybrid_input->get_attn()); -+ auto * hybrid_q = ggml_new_tensor_3d(hybrid_result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); -+ ggml_set_input(hybrid_q); -+ std::vector hybrid_outputs; -+ for (int layer = 0; layer < 2; ++layer) { -+ hybrid_outputs.push_back(hybrid_graph.build_attn(hybrid_input->get_attn(), nullptr, nullptr, nullptr, -+ hybrid_q, nullptr, nullptr, nullptr, nullptr, nullptr, 0.125f, layer)); -+ } -+ iswa_row_require(ggml_backend_sched_alloc_graph(hybrid_scheduler.get(), hybrid_result.get_gf()), -+ "hybrid ISWA graph allocation"); -+ ggml_backend_tensor_set(hybrid_q, zeros.data(), 0, zeros.size()*sizeof(float)); -+ const auto execute_hybrid = [&](const llama_ubatch & batch) { -+ hybrid_result.set_inputs(&batch); -+ const auto * attention = hybrid_input->get_attn(); -+ iswa_row_check_pool(*hybrid_cache->get_base(), batch, attention->self_kv_rows, attention->self_read_mask, false); -+ iswa_row_check_pool(*hybrid_cache->get_swa(), batch, attention->self_kv_rows_swa, attention->self_read_mask_swa, true); -+ iswa_row_require(ggml_backend_sched_graph_compute(hybrid_scheduler.get(), hybrid_result.get_gf()) == GGML_STATUS_SUCCESS, -+ "hybrid ISWA finite compute"); -+ for (auto * output : hybrid_outputs) { -+ std::vector values(ggml_nelements(output)); -+ ggml_backend_tensor_get(output, values.data(), 0, values.size()*sizeof(float)); -+ for (float value : values) iswa_row_require(std::isfinite(value) && value == 0.0f, "hybrid ISWA finite output"); -+ } -+ }; -+ execute_hybrid(first); -+ auto hybrid_next = iswa_row_apply(*hybrid_cache, next); -+ auto next_hybrid_context = hybrid.init_full(); -+ hybrid_params.ubatch = next; -+ hybrid_params.mctx = next_hybrid_context.get(); -+ const auto * actual_hybrid_context = static_cast(next_hybrid_context.get()); -+ iswa_row_require(actual_hybrid_context != old_hybrid_context && hybrid_input->can_reuse(hybrid_params) && -+ hybrid_input->mctx == actual_hybrid_context && hybrid_input->get_attn()->mctx == actual_hybrid_context->get_attn(), -+ "hybrid ISWA refresh both current context pointers"); -+ execute_hybrid(next); -+ -+ auto ragged = next; -+ ragged.b_equal_seqs = 0; -+ ragged.n_tokens = 3; -+ iswa_row_require(!input->can_reuse_row_inputs(ragged, params.cparams), "ISWA ragged topology rejects row reuse"); -+ auto ordinary = params.cparams; -+ ordinary.fused_kv_rows = false; -+ iswa_row_require(!input->can_reuse_row_inputs(next, ordinary), "ISWA row-enabled topology cannot reuse ordinary"); -+ ordinary = params.cparams; -+ ordinary.training = true; -+ iswa_row_require(!input->can_reuse_row_inputs(next, ordinary), "ISWA training cannot reuse row topology"); -+ // Test both ordinary pool builders without changing the product setting. -+ llm_graph_result ordinary_result(512); -+ params.cparams.fused_kv_rows = false; -+ params.res = &ordinary_result; -+ llm_graph_context ordinary_graph(params); -+ auto * ordinary_input = ordinary_graph.build_attn_inp_kv_iswa(); -+ iswa_row_require(!ordinary_input->self_kv_rows && !ordinary_input->self_kv_rows_swa, -+ "ISWA ordinary row inputs absent"); -+ auto * ordinary_q = ggml_new_tensor_3d(ordinary_result.get_ctx(), GGML_TYPE_F32, 64, 1, 4); -+ for (int layer = 0; layer < 2; ++layer) { -+ ordinary_graph.build_attn(ordinary_input, nullptr, nullptr, nullptr, ordinary_q, nullptr, nullptr, -+ nullptr, nullptr, nullptr, 0.125f, layer); -+ } -+ iswa_row_require(ordinary_result.get_fused_nodes().size() == 2, "ISWA both ordinary layers"); -+ for (const auto & node : ordinary_result.get_fused_nodes()) { -+ iswa_row_require(node.op == LLM_FUSED_OP_FLASH_ATTN && !node.tensor->src[5] && !node.tensor->src[6] && -+ node.tensor->src[3] == (model.hparams.is_swa(node.il) ? ordinary_input->self_kq_mask_swa : ordinary_input->self_kq_mask), -+ "ISWA ordinary per-layer mask"); -+ } -+ return 0; -+ } catch (const std::exception & error) { -+ std::fprintf(stderr, "ISWA row-input regression: %s\n", error.what()); -+ return 120; -+ } -+} diff --git a/src/skippy/tests/live_graph_reference.h b/src/skippy/tests/live_graph_reference.h new file mode 100644 index 000000000..73129bf07 @@ -5480,299 +5153,6 @@ index 000000000..0832b018e + llama_backend_free(); + return result; +} -diff --git a/src/skippy/tests/resident_checkpoint_gpu.cpp b/src/skippy/tests/resident_checkpoint_gpu.cpp -new file mode 100644 -index 000000000..691e92c37 ---- /dev/null -+++ b/src/skippy/tests/resident_checkpoint_gpu.cpp -@@ -0,0 +1,287 @@ -+// Opt-in real-model GPU proof: separate checkpoint ownership from HTTP scheduling. -+#include "skippy.h" -+#include "../runtime_types.h" -+#include "llama-model.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); -+ -+namespace { -+constexpr size_t lanes = 4; -+constexpr size_t suffix_steps = 32; -+constexpr size_t pressure_tokens = 4096; -+using Sessions = std::array; -+using Prefixes = std::array, lanes>; -+ -+#define REQUIRE(condition) do { if (!(condition)) { \ -+ std::fprintf(stderr, "long GPU checkpoint failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ -+ std::exit(1); } } while (0) -+ -+void ok(skippy_status status, skippy_error * error) { -+ if (status != SKIPPY_STATUS_OK) { -+ std::fprintf(stderr, "long GPU native error: %s\n", error ? error->message : "no detail"); -+ std::exit(1); -+ } -+ skippy_error_free(error); -+} -+ -+size_t prefix_tokens() { -+ const char * value = std::getenv("SKIPPY_NATIVE_TEST_PREFIX_TOKENS"); -+ if (!value) { return 23497; } -+ REQUIRE(*value && std::strspn(value, "0123456789") == std::strlen(value)); -+ const unsigned long count = std::strtoul(value, nullptr, 10); -+ REQUIRE(count >= 128 && count <= 65536); -+ return static_cast(count); -+} -+ -+Sessions create(skippy_model * model) { -+ Sessions sessions{}; -+ for (auto & session : sessions) { -+ skippy_error * error = nullptr; -+ const auto status = skippy_session_create(model, &session, &error); -+ ok(status, error); -+ } -+ return sessions; -+} -+ -+void release(Sessions & sessions) { -+ for (auto & session : sessions) { -+ skippy_error * error = nullptr; -+ const auto status = skippy_session_free(session, &error); -+ ok(status, error); -+ session = nullptr; -+ } -+} -+ -+void prefill(Sessions & sessions, const Prefixes & prefixes) { -+ // Identical explicit chunk and lane order in every cold reference arm. -+ for (size_t offset = 0; offset < prefixes[0].size(); offset += 512) { -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ const size_t count = std::min(512, prefixes[lane].size() - offset); -+ skippy_error * error = nullptr; -+ size_t bytes = 0; -+ const auto status = skippy_prefill_chunk(sessions[lane], prefixes[lane].data() + offset, -+ count, nullptr, 0, nullptr, 0, &bytes, &error); -+ ok(status, error); -+ } -+ } -+} -+ -+Prefixes tokens(size_t count, int32_t vocab_size, int32_t salt) { -+ REQUIRE(vocab_size > 64); -+ const int32_t span = std::min(vocab_size - 32, 4096); -+ Prefixes prefixes; -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ prefixes[lane].reserve(count); -+ for (size_t i = 0; i < count; ++i) { -+ prefixes[lane].push_back(32 + static_cast((i * 17 + lane * 101 + salt) % span)); -+ } -+ } -+ return prefixes; -+} -+ -+struct Components { -+ std::vector kv; -+ std::vector recurrent; -+}; -+ -+Components components(skippy_session * session) { -+ const int32_t layers = static_cast(session->stage_model->model->hparams.n_layer()); -+ skippy_kv_page_desc desc{}; -+ size_t bytes = 0; -+ skippy_error * error = nullptr; -+ auto status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, -+ &desc, nullptr, 0, &bytes, &error); -+ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); -+ skippy_error_free(error); -+ Components result; -+ result.kv.resize(bytes); -+ error = nullptr; -+ status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, -+ &desc, result.kv.data(), result.kv.size(), &bytes, &error); -+ ok(status, error); -+ result.kv.resize(bytes); -+ error = nullptr; -+ status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); -+ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); -+ skippy_error_free(error); -+ result.recurrent.resize(bytes); -+ error = nullptr; -+ status = skippy_export_recurrent_state(session, result.recurrent.data(), -+ result.recurrent.size(), &bytes, &error); -+ ok(status, error); -+ result.recurrent.resize(bytes); -+ return result; -+} -+ -+struct DecodeRows { -+ std::array greedy; -+ std::array, lanes> logits; -+}; -+ -+using DecodeTrace = std::vector; -+ -+DecodeTrace decode_fixed_suffix(Sessions & sessions, int32_t vocab_size) { -+ skippy_sampling_config sampling{}; -+ sampling.version = 1; -+ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; -+ sampling.repeat_penalty = 1.0f; -+ sampling.temperature = 0; -+ sampling.top_k = 1; -+ sampling.reasoning_budget_tokens = -1; -+ DecodeTrace trace; -+ trace.reserve(suffix_steps); -+ for (size_t step = 0; step < suffix_steps; ++step) { -+ std::array input{}; -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ input[lane] = 32 + static_cast((step * 11 + lane * 37) % (vocab_size - 32)); -+ } -+ DecodeRows rows; -+ skippy_error * error = nullptr; -+ std::array requests{}; -+ std::array sampled_indexes{}; -+ size_t sampled_count = 0; -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ requests[lane].session = sessions[lane]; -+ requests[lane].token_ids = &input[lane]; -+ requests[lane].token_count = 1; -+ requests[lane].sampling = &sampling; -+ requests[lane].sample_last = true; -+ } -+ const auto status = skippy_iteration_batch_sampled(requests.data(), requests.size(), -+ nullptr, nullptr, nullptr, nullptr, sampled_indexes.data(), rows.greedy.data(), -+ rows.greedy.size(), &sampled_count, &error); -+ ok(status, error); -+ REQUIRE(sampled_count == lanes); -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ REQUIRE(sampled_indexes[lane] == lane); -+ const float * logits = llama_get_logits_ith(sessions[lane]->ctx, static_cast(lane)); -+ REQUIRE(logits != nullptr); -+ rows.logits[lane].assign(logits, logits + vocab_size); -+ REQUIRE(std::all_of(rows.logits[lane].begin(), rows.logits[lane].end(), -+ [](float value) { return std::isfinite(value); })); -+ } -+ trace.push_back(std::move(rows)); -+ } -+ return trace; -+} -+ -+bool compare(const char * arm, const DecodeTrace & reference, const DecodeTrace & actual) { -+ REQUIRE(reference.size() == actual.size()); -+ float max_delta = 0; -+ size_t mismatched_greedy = 0; -+ for (size_t step = 0; step < reference.size(); ++step) { -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ mismatched_greedy += reference[step].greedy[lane] != actual[step].greedy[lane]; -+ REQUIRE(reference[step].logits[lane].size() == actual[step].logits[lane].size()); -+ for (size_t token = 0; token < reference[step].logits[lane].size(); ++token) { -+ max_delta = std::max(max_delta, -+ std::fabs(reference[step].logits[lane][token] - actual[step].logits[lane][token])); -+ } -+ } -+ } -+ std::fprintf(stderr, "%s: batch=4 steps=%zu max_logit_delta=%.9g greedy_mismatches=%zu\n", -+ arm, reference.size(), max_delta, mismatched_greedy); -+ return max_delta <= 1e-6f && mismatched_greedy == 0; -+} -+ -+void save(Sessions & sessions, size_t count) { -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ skippy_error * error = nullptr; -+ const auto status = skippy_session_save_prefix(sessions[lane], static_cast(8 + lane), count, &error); -+ ok(status, error); -+ } -+} -+ -+Sessions restore(skippy_model * model, const Prefixes & prefixes) { -+ Sessions sessions{}; -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ skippy_error * error = nullptr; -+ const auto status = skippy_session_create_from_resident_prefix(model, static_cast(8 + lane), -+ prefixes[lane].data(), prefixes[lane].size(), &sessions[lane], &error); -+ ok(status, error); -+ } -+ return sessions; -+} -+ -+void require_gpu_weights(skippy_model * model) { -+ REQUIRE(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), -+ [](const auto & item) { -+ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } -+ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( -+ ggml_backend_buffer_get_type(item.second->buffer))); -+ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; -+ })); -+} -+ -+} // namespace -+ -+int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config) { -+ REQUIRE(model_path && *model_path && config.n_gpu_layers > 0); -+ const size_t count = prefix_tokens(); -+ config.ctx_size = static_cast(count + pressure_tokens + suffix_steps + 64); -+ config.lane_count = lanes; -+ config.kv_unified = 1; -+ config.n_batch = 512; -+ config.n_ubatch = 512; -+ skippy_model * model = nullptr; -+ skippy_error * error = nullptr; -+ auto status = skippy_model_open(model_path, &config, &model, &error); -+ ok(status, error); -+ require_gpu_weights(model); -+ REQUIRE(config.ctx_size <= llama_model_n_ctx_train(model->model)); -+ const auto capabilities = skippy_model_memory_cache_capabilities(model); -+ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); -+ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); -+ const int32_t vocab_size = llama_vocab_n_tokens(llama_model_get_vocab(model->model)); -+ const auto prefixes = tokens(count, vocab_size, 0); -+ auto source = create(model); -+ prefill(source, prefixes); -+ save(source, count); -+ std::array expected; -+ for (size_t lane = 0; lane < lanes; ++lane) { expected[lane] = components(source[lane]); } -+ const auto reference = decode_fixed_suffix(source, vocab_size); -+ release(source); -+ -+ auto pressure = create(model); -+ prefill(pressure, tokens(pressure_tokens, vocab_size, 503)); -+ release(pressure); -+ auto warm = restore(model, prefixes); -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ const auto restored = components(warm[lane]); -+ std::fprintf(stderr, "checkpoint lane=%zu tokens=%zu kv_bytes=%zu recurrent_bytes=%zu kv_exact=%d recurrent_exact=%d\n", -+ lane, count, restored.kv.size(), restored.recurrent.size(), -+ restored.kv == expected[lane].kv, restored.recurrent == expected[lane].recurrent); -+ REQUIRE(restored.kv == expected[lane].kv); -+ REQUIRE(restored.recurrent == expected[lane].recurrent); -+ } -+ const auto restored_trace = decode_fixed_suffix(warm, vocab_size); -+ const bool passed = compare("resident restore vs reference", reference, restored_trace); -+ for (size_t lane = 0; lane < lanes; ++lane) { -+ error = nullptr; -+ status = skippy_session_drop_sequence(warm[0], static_cast(8 + lane), &error); -+ ok(status, error); -+ } -+ release(warm); -+ if (!passed) { -+ // Preserve the strict failure. A same-shape second cold reference -+ // distinguishes backend drift before any tolerance change is proposed. -+ auto repeated = create(model); -+ prefill(repeated, prefixes); -+ compare("cold reference vs repeated cold reference", reference, decode_fixed_suffix(repeated, vocab_size)); -+ release(repeated); -+ } -+ error = nullptr; -+ status = skippy_model_free(model, &error); -+ ok(status, error); -+ return passed ? 0 : 1; -+} diff --git a/src/skippy/tests/residual_checkpoint_regression.h b/src/skippy/tests/residual_checkpoint_regression.h new file mode 100644 index 000000000..31734bf56 @@ -6534,102 +5914,31 @@ index 000000000..00a6ff0ec +} diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp new file mode 100644 -index 000000000..ec345c761 +index 000000000..9e134586f --- /dev/null +++ b/src/skippy/tests/sampling_history.cpp -@@ -0,0 +1,967 @@ +@@ -0,0 +1,517 @@ +#include "skippy.h" +#include "../runtime_types.h" -+#include "../sampling_internal.h" -+#include "../sampling_argmax.h" +#include "../runtime_support.h" +#include "llama-model.h" -+#include "llama-graph.h" -+#include "ggml-backend.h" +#include "../../../common/sampling.h" + +#include -+#include +#include +#include +#include +#include +#include -+#include + +#define CHECK(condition) do { if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ + std::exit(1); } } while (0) + -+int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); -+ +namespace { + +bool require_recurrent = false; + -+int32_t cache_type(const char * name) { -+ for (const auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, -+ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}) { -+ if (std::strcmp(name, ggml_type_name(type)) == 0) { return type; } -+ } -+ CHECK(false && "unsupported test KV type"); -+ return -1; -+} -+ -+ggml_type verify_attention_read(skippy_model * model, ggml_tensor * input, int32_t stored_type) { -+ if (stored_type != GGML_TYPE_F32) { -+ CHECK(input->type == stored_type); -+ return input->type; -+ } -+ // Ordinary FA reads explicitly convert an F32 cache on its selected backend. -+ CHECK(input->type == GGML_TYPE_F16 && input->op == GGML_OP_CPY); -+ CHECK(input->src[0] && input->src[0]->type == GGML_TYPE_F32); -+ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), input); -+ CHECK(backend && std::strcmp(ggml_backend_name(backend), model->config.selected_backend_device) == 0); -+ return input->type; -+} -+ -+void verify_typed_attention(skippy_model * model, const skippy_kv_page_desc & page) { -+ const auto & config = model->config; -+ const auto check_types = [&](uint32_t k, uint32_t v) { -+ CHECK(k == static_cast(config.cache_type_k)); -+ CHECK(v == static_cast(config.cache_type_v)); -+ }; -+ if (page.component_count) { -+ CHECK(page.component_count <= std::size(page.components)); -+ for (uint32_t i = 0; i < page.component_count; ++i) { -+ check_types(page.components[i].k_type, page.components[i].v_type); -+ } -+ } else { -+ check_types(page.k_type, page.v_type); -+ } -+ auto * result = model->ctx->get_gf_res_prev_active(); -+ CHECK(result && result->get_gf()); -+ auto * graph = result->get_gf(); -+ int attention = 0; -+ ggml_type actual_k = GGML_TYPE_COUNT; -+ ggml_type actual_v = GGML_TYPE_COUNT; -+ for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { -+ auto * node = ggml_graph_node(graph, i); -+ if (node->op != GGML_OP_FLASH_ATTN_EXT) { continue; } -+ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), node); -+ CHECK(backend && std::strcmp(ggml_backend_name(backend), config.selected_backend_device) == 0); -+ CHECK(node->src[5] == nullptr && node->src[6] == nullptr); -+ actual_k = verify_attention_read(model, node->src[1], config.cache_type_k); -+ actual_v = verify_attention_read(model, node->src[2], config.cache_type_v); -+ ++attention; -+ } -+ int expected_attention = 0; -+ for (uint32_t layer = 0; layer < model->model->hparams.n_layer(); ++layer) { -+ expected_attention += !model->model->hparams.is_recr(layer); -+ } -+ CHECK(attention > 0 && attention == expected_attention); -+ std::fprintf(stderr, "typed resident: backend=%s stored_K=%s stored_V=%s FA_K=%s FA_V=%s attention=%d expected=%d components=%u read_layout=ordinary\n", -+ config.selected_backend_device, ggml_type_name(static_cast(config.cache_type_k)), -+ ggml_type_name(static_cast(config.cache_type_v)), ggml_type_name(actual_k), ggml_type_name(actual_v), -+ attention, expected_attention, page.component_count); -+} -+ +void ok(skippy_status status, skippy_error * error) { + if (status != SKIPPY_STATUS_OK) { + std::fprintf(stderr, "native failure: %s\n", error ? error->message : "no detail"); @@ -6638,31 +5947,6 @@ index 000000000..ec345c761 + skippy_error_free(error); +} + -+void configure_test_gpu(skippy_runtime_config & config) { -+ config.n_gpu_layers = 0; -+ const char * value = std::getenv("SKIPPY_NATIVE_TEST_GPU_LAYERS"); -+ if (!value) { return; } -+ CHECK(*value && std::strspn(value, "0123456789") == std::strlen(value)); -+ const unsigned long layers = std::strtoul(value, nullptr, 10); -+ CHECK(layers <= static_cast(std::numeric_limits::max())); -+ if (!layers) { return; } -+ size_t count = 0; -+ skippy_error * error = nullptr; -+ auto status = skippy_backend_device_count(&count, &error); -+ ok(status, error); -+ for (size_t i = 0; i < count; ++i) { -+ skippy_backend_device device{}; -+ error = nullptr; -+ status = skippy_backend_device_at(i, &device, &error); -+ ok(status, error); -+ if (device.type != SKIPPY_BACKEND_DEVICE_TYPE_GPU && device.type != SKIPPY_BACKEND_DEVICE_TYPE_IGPU) { continue; } -+ config.selected_backend_device = device.name; -+ config.n_gpu_layers = static_cast(layers); -+ return; -+ } -+ CHECK(false && "GPU layers requested but no GPU backend is available"); -+} -+ +void prefill(skippy_session * session, const std::vector & tokens) { + size_t bytes = 0; + skippy_error * error = nullptr; @@ -6894,10 +6178,6 @@ index 000000000..ec345c761 + ok(status, error); + CHECK(session->token_history.size() == prefix.size()); + CHECK(session->sampling_accepted_token_count <= session->token_history.size()); -+ CHECK(session->sampler == nullptr); -+ configure(session, sampling, false, prefix.size() + 1); -+ CHECK(decode(session, sampling, 2) == 42); -+ CHECK(decode(session, sampling, 42) == 43); + release(session); +} + @@ -6927,108 +6207,6 @@ index 000000000..ec345c761 + release(restored); +} + -+// Temperature 0 with the defaults and sampler order the serving layer sends. -+skippy_sampling_config temperature_zero_config() { -+ skippy_sampling_config config{}; -+ config.version = 1; -+ config.flags = SKIPPY_SAMPLING_FLAG_ENABLED; -+ config.temperature = 0.0f; -+ config.top_k = 40; -+ config.top_p = 0.95f; -+ config.min_p = 0.05f; -+ config.typical_p = 1.0f; -+ config.top_nsigma = -1.0f; -+ config.dynatemp_exponent = 1.0f; -+ config.repeat_penalty = 1.0f; -+ config.penalty_last_n = 64; -+ config.dry_base = 1.75f; -+ config.dry_allowed_length = 2; -+ config.dry_penalty_last_n = 64; -+ config.xtc_threshold = 0.1f; -+ config.mirostat_entropy = 5.0f; -+ config.mirostat_learning_rate = 0.1f; -+ config.reasoning_budget_tokens = -1; -+ config.sampler_count = 9; -+ for (uint32_t i = 0; i < config.sampler_count; ++i) { -+ config.samplers[i] = i + 1; -+ } -+ return config; -+} -+ -+// The token a freshly built chain selects from the row the last decode sampled. -+llama_token full_chain_token(skippy_session * session) { -+ auto * reference = common_sampler_clone(session->sampler); -+ CHECK(reference != nullptr); -+ common_sampler_reset(reference); -+ for (const llama_token token : session->token_history) { -+ common_sampler_accept(reference, token, true); -+ } -+ const auto token = common_sampler_sample(reference, session->ctx, -1); -+ CHECK(common_sampler_last(session->sampler) == session->token_history.back()); -+ CHECK(session->sampling_accepted_token_count == session->token_history.size()); -+ common_sampler_free(reference); -+ return token; -+} -+ -+// Count the decodes that took the argmax path and check each against the full chain. -+uint64_t argmax_decodes(skippy_model * model, const skippy_sampling_config & sampling, -+ std::vector * predicted) { -+ auto * session = create(model); -+ prefill(session, {1, 2, 3, 4, 5, 6, 7, 8}); -+ const uint64_t before = session->sampling_argmax_count; -+ llama_token previous = 9; -+ for (int step = 0; step < 6; ++step) { -+ previous = decode(session, sampling, previous); -+ CHECK(previous == full_chain_token(session)); -+ predicted->push_back(previous); -+ } -+ const uint64_t taken = session->sampling_argmax_count - before; -+ release(session); -+ return taken; -+} -+ -+void argmax_path(skippy_model * model) { -+ // Repeated biases apply in order to the original logit, without pre-summing. -+ skippy_argmax_plan plan; -+ skippy_prepare_argmax_plan(&plan, {{0, -1e20f}, {1, 0.0f}, {0, 1.0f}, {-1, 4.0f}}, 2); -+ const float logits[] = {1e20f, 0.5f}; -+ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); -+ skippy_prepare_argmax_plan(&plan, {}, 2); -+ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); -+ -+ // Each request can only select the top biased logit, so it must not run the full chain. -+ auto ignore_eos = temperature_zero_config(); -+ ignore_eos.flags |= SKIPPY_SAMPLING_FLAG_IGNORE_EOS; -+ ignore_eos.ignore_eos = 1; -+ auto logit_bias = temperature_zero_config(); -+ logit_bias.logit_bias_count = 2; -+ logit_bias.logit_bias[0] = {7, -3.0f}; -+ logit_bias.logit_bias[1] = {9, 2.5f}; -+ auto inert_penalties = temperature_zero_config(); -+ inert_penalties.presence_penalty = 0.5f; -+ inert_penalties.frequency_penalty = 0.5f; -+ inert_penalties.penalty_last_n = 0; -+ for (const auto & sampling : {ignore_eos, logit_bias, inert_penalties}) { -+ std::vector predicted; -+ const uint64_t taken = argmax_decodes(model, sampling, &predicted); -+ if (taken != predicted.size()) { -+ std::fprintf(stderr, "argmax path taken for %llu of %zu temperature-0 decodes\n", -+ static_cast(taken), predicted.size()); -+ } -+ CHECK(taken == predicted.size()); -+ } -+ -+ // Equal biased maxima keep the full chain's tie order. -+ auto tie = temperature_zero_config(); -+ tie.logit_bias_count = 2; -+ tie.logit_bias[0] = {3, 1e30f}; -+ tie.logit_bias[1] = {5, 1e30f}; -+ std::vector predicted; -+ CHECK(argmax_decodes(model, tie, &predicted) == 0); -+ for (const llama_token token : predicted) { -+ CHECK(token == 3 || token == 5); -+ } -+} + +int32_t stage_layers(skippy_session * session) { + return session->stage_model->model->hparams.n_layer(); @@ -7052,6 +6230,33 @@ index 000000000..ec345c761 + return payload; +} + ++std::vector export_recurrent(skippy_session * session) { ++ skippy_error * error = nullptr; ++ size_t bytes = 0; ++ auto status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); ++ CHECK(status == SKIPPY_STATUS_BUFFER_TOO_SMALL || status == SKIPPY_STATUS_OK); ++ skippy_error_free(error); ++ error = nullptr; ++ std::vector payload(bytes); ++ status = skippy_export_recurrent_state(session, payload.data(), payload.size(), &bytes, &error); ++ ok(status, error); ++ payload.resize(bytes); ++ return payload; ++} ++ ++void restore_recurrent(skippy_session * session, const std::vector & payload, ++ const std::vector & prefix) { ++ skippy_error * error = nullptr; ++ auto status = skippy_import_recurrent_state(session, payload.data(), payload.size(), &error); ++ ok(status, error); ++ error = nullptr; ++ status = skippy_session_set_position(session, prefix.size(), &error); ++ ok(status, error); ++ error = nullptr; ++ status = skippy_session_restore_token_history(session, prefix.data(), prefix.size(), &error); ++ ok(status, error); ++} ++ +skippy_sampling_config greedy_config() { + skippy_sampling_config config{}; + config.version = 1; @@ -7078,20 +6283,27 @@ index 000000000..ec345c761 + return std::vector(logits, logits + n_vocab); +} + -+// Exact hybrid restoration combines attention pages with a separate recurrent -+// checkpoint. The recurrent component must never duplicate full-attention KV. ++// A declared-exact stage checkpoint must be reconstructible from its export ++// alone. LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY is an alias of ++// LLAMA_STATE_SEQ_FLAGS_SWA_ONLY: it writes the recurrent and sliding-window ++// half of a hybrid memory and nothing from a full-attention KV cache, so a ++// session restored from that half carries no full-attention cells and decodes a ++// different continuation from an uninterrupted prefill. Compare the attention ++// page the restored session exposes with the source's page, and the next-token ++// logits of a restored prefix with those of the same prefix prefilled from ++// scratch. +void state_round_trip(skippy_model * model) { + const std::vector prefix(128, 1); + auto * source = create(model); + prefill(source, prefix); + const auto source_page = export_page(source, prefix.size()); + CHECK(!source_page.empty()); -+ const snapshot checkpoint(source, false); -+ CHECK(!checkpoint.recurrent.empty()); ++ const auto recurrent = export_recurrent(source); ++ CHECK(!recurrent.empty()); + release(source); + + auto * restored = create(model); -+ checkpoint.restore(restored, prefix); ++ restore_recurrent(restored, recurrent, prefix); + const auto restored_page = export_page(restored, prefix.size()); + CHECK(restored_page.size() == source_page.size()); + CHECK(std::memcmp(restored_page.data(), source_page.data(), source_page.size()) == 0); @@ -7104,7 +6316,7 @@ index 000000000..ec345c761 + const auto cold_logits = decode_logits(cold, suffix.back()); + release(cold); + auto * warm = create(model); -+ checkpoint.restore(warm, prefix); ++ restore_recurrent(warm, recurrent, prefix); + prefill(warm, suffix); + const auto warm_logits = decode_logits(warm, suffix.back()); + release(warm); @@ -7123,174 +6335,6 @@ index 000000000..ec345c761 + CHECK(max_delta == 0.0f); +} + -+void resident_prefix_ownership(skippy_model * model, bool typed = false) { -+ const auto capabilities = skippy_model_memory_cache_capabilities(model); -+ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT); -+ CHECK(bool(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) == require_recurrent); -+ const std::vector prefix(128, 1); -+ const std::vector suffix_a{2, 3, 4}; -+ const std::vector suffix_b{5, 6, 7}; -+ constexpr int32_t cache_id = 8; -+ auto * source = create(model); -+ prefill(source, prefix); -+ skippy_error * error = nullptr; -+ uint64_t before_cells = 0; -+ ok(skippy_session_memory_used_cells(source, &before_cells, &error), error); -+ error = nullptr; -+ ok(skippy_session_save_prefix(source, cache_id, prefix.size(), &error), error); -+ uint64_t after_cells = 0; -+ error = nullptr; -+ ok(skippy_session_memory_used_cells(source, &after_cells, &error), error); -+ CHECK(before_cells == after_cells); // Sharing must not allocate attention cells. -+ uint64_t checkpoint_bytes = 0; -+ error = nullptr; -+ ok(skippy_session_resident_prefix_bytes(source, cache_id, &checkpoint_bytes, &error), error); -+ CHECK(checkpoint_bytes >= prefix.size() * sizeof(llama_token)); -+ const auto source_page = export_page(source, prefix.size()); -+ snapshot persistent(source, false); -+ if (typed) { verify_typed_attention(model, persistent.page); } -+ if (require_recurrent) { -+ CHECK(checkpoint_bytes > prefix.size() * sizeof(llama_token)); -+ error = nullptr; -+ CHECK(skippy_session_save_prefix(source, cache_id, prefix.size() - 1, &error) -+ == SKIPPY_STATUS_INVALID_ARGUMENT); -+ skippy_error_free(error); -+ uint64_t unchanged_bytes = 0; -+ error = nullptr; -+ ok(skippy_session_resident_prefix_bytes(source, cache_id, &unchanged_bytes, &error), error); -+ CHECK(unchanged_bytes == checkpoint_bytes); -+ } -+ for (const auto token : suffix_a) { prefill(source, {token}); } -+ const auto expected_a = decode_logits(source, suffix_a.back()); -+ const auto expected_page_a = export_page(source, source->n_past); -+ release(source); // Originating lane and mutable recurrent row are gone. -+ -+ auto * recycled = create(model); -+ prefill(recycled, std::vector(32, 9)); -+ decode_logits(recycled, 10); -+ release(recycled); -+ auto * cold_b = create(model); -+ prefill(cold_b, prefix); -+ for (const auto token : suffix_b) { prefill(cold_b, {token}); } -+ const auto expected_b = decode_logits(cold_b, suffix_b.back()); -+ const auto expected_page_b = export_page(cold_b, cold_b->n_past); -+ release(cold_b); -+ -+ // Invalid identity and boundary must neither claim a lane nor damage the -+ // cached checkpoint; repeatedly exercising create catches leaked claims. -+ auto wrong_tokens = prefix; -+ wrong_tokens.back() = 12; -+ for (int attempt = 0; attempt < 4; ++attempt) { -+ skippy_session * invalid = nullptr; -+ error = nullptr; -+ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, -+ wrong_tokens.data(), wrong_tokens.size(), &invalid, &error) -+ == SKIPPY_STATUS_INVALID_ARGUMENT); -+ skippy_error_free(error); -+ CHECK(invalid == nullptr); -+ } -+ if (require_recurrent) { -+ skippy_session * invalid = nullptr; -+ error = nullptr; -+ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, -+ prefix.data(), prefix.size() - 1, &invalid, &error) -+ == SKIPPY_STATUS_INVALID_ARGUMENT); -+ skippy_error_free(error); -+ CHECK(invalid == nullptr); -+ } -+ auto restore = [&]() { -+ skippy_session * restored = nullptr; -+ error = nullptr; -+ ok(skippy_session_create_from_resident_prefix(model, cache_id, -+ prefix.data(), prefix.size(), &restored, &error), error); -+ CHECK(restored->token_history == prefix); -+ CHECK(export_page(restored, prefix.size()) == source_page); -+ return restored; -+ }; -+ auto * a = restore(); -+ auto * b = restore(); -+ // All execution lanes are occupied. Cold offload exports the cache-owned -+ // state directly, without restoring over either live borrower. -+ const auto history_a = a->token_history; -+ const auto history_b = b->token_history; -+ size_t kv_bytes = 0; -+ error = nullptr; -+ CHECK(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, -+ 0, prefix.size(), &persistent.page, nullptr, 0, &kv_bytes, &error) -+ == SKIPPY_STATUS_BUFFER_TOO_SMALL); -+ skippy_error_free(error); -+ CHECK(kv_bytes == persistent.payload.size()); -+ error = nullptr; -+ ok(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, -+ 0, prefix.size(), &persistent.page, persistent.payload.data(), kv_bytes, -+ &kv_bytes, &error), error); -+ CHECK(persistent.payload == source_page); -+ size_t recurrent_bytes = 0; -+ error = nullptr; -+ const auto recurrent_status = skippy_session_export_resident_recurrent_state(a, -+ cache_id, nullptr, 0, &recurrent_bytes, &error); -+ CHECK(recurrent_status == (require_recurrent ? SKIPPY_STATUS_BUFFER_TOO_SMALL : SKIPPY_STATUS_OK)); -+ skippy_error_free(error); -+ CHECK(recurrent_bytes == persistent.recurrent.size()); -+ if (recurrent_bytes) { -+ std::vector retained_recurrent(recurrent_bytes); -+ error = nullptr; -+ ok(skippy_session_export_resident_recurrent_state(a, cache_id, -+ retained_recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); -+ CHECK(retained_recurrent == persistent.recurrent); -+ } -+ CHECK(a->token_history == history_a && b->token_history == history_b); -+ CHECK(a->n_past == static_cast(prefix.size()) && b->n_past == a->n_past); -+ for (size_t i = 0; i < suffix_a.size(); ++i) { -+ prefill(a, {suffix_a[i]}); -+ prefill(b, {suffix_b[i]}); -+ } -+ // Evicting radix ownership must leave both active borrowers valid. -+ error = nullptr; -+ ok(skippy_session_drop_sequence(a, cache_id, &error), error); -+ uint64_t dropped_bytes = 1; -+ error = nullptr; -+ ok(skippy_session_resident_prefix_bytes(a, cache_id, &dropped_bytes, &error), error); -+ CHECK(dropped_bytes == 0); -+ const auto actual_a = decode_logits(a, suffix_a.back()); -+ const auto actual_b = decode_logits(b, suffix_b.back()); -+ float delta_a = 0, delta_b = 0; -+ for (size_t i = 0; i < actual_a.size(); ++i) { -+ delta_a = std::max(delta_a, std::fabs(actual_a[i] - expected_a[i])); -+ delta_b = std::max(delta_b, std::fabs(actual_b[i] - expected_b[i])); -+ } -+ std::fprintf(stderr, "resident fork: max delta a=%.9g b=%.9g page a=%d b=%d\n", delta_a, delta_b, -+ export_page(a, a->n_past) == expected_page_a, export_page(b, b->n_past) == expected_page_b); -+ // Different shared-pool occupancy changes the CPU attention reduction -+ // shape. Measured drift is below 2e-7; reject nonfinite or larger errors -+ // and require the selected greedy token to remain identical. -+ for (const auto value : actual_a) { CHECK(std::isfinite(value)); } -+ for (const auto value : actual_b) { CHECK(std::isfinite(value)); } -+ CHECK(delta_a <= 1e-6f && delta_b <= 1e-6f); -+ CHECK(std::max_element(actual_a.begin(), actual_a.end()) - actual_a.begin() -+ == std::max_element(expected_a.begin(), expected_a.end()) - expected_a.begin()); -+ CHECK(std::max_element(actual_b.begin(), actual_b.end()) - actual_b.begin() -+ == std::max_element(expected_b.begin(), expected_b.end()) - expected_b.begin()); -+ if (require_recurrent) { -+ CHECK(export_page(a, a->n_past) == expected_page_a); -+ CHECK(export_page(b, b->n_past) == expected_page_b); -+ } -+ release(a); -+ release(b); -+ // The resident owner has been evicted. The independently exported payload -+ // still reconstructs both attention and recurrent state in a new lane. -+ auto * persisted = create(model); -+ persistent.restore(persisted, prefix); -+ CHECK(export_page(persisted, prefix.size()) == source_page); -+ for (const auto token : suffix_a) { prefill(persisted, {token}); } -+ const auto persisted_logits = decode_logits(persisted, suffix_a.back()); -+ for (size_t i = 0; i < persisted_logits.size(); ++i) { -+ CHECK(std::isfinite(persisted_logits[i])); -+ CHECK(std::fabs(persisted_logits[i] - expected_a[i]) <= 1e-6f); -+ } -+ release(persisted); -+ } -+ +void adapter_contracts(skippy_model * model) { + auto * session = create(model); + prefill(session, {1, 2}); @@ -7317,7 +6361,6 @@ index 000000000..ec345c761 + error = nullptr; + + config = sampling_config(); -+ config.temperature = 0.8f; + config.ignore_eos = 1; + config.logit_bias_count = 3; + const auto * vocab = llama_model_get_vocab(model->model); @@ -7347,117 +6390,27 @@ index 000000000..ec345c761 + release(session); +} + -+void dense_resident_configuration(const char * path, skippy_runtime_config config) { -+ config.lane_count = 1; -+ config.kv_unified = SKIPPY_TRISTATE_AUTO; -+ skippy_model * model = nullptr; -+ skippy_error * error = nullptr; -+ ok(skippy_model_open(path, &config, &model, &error), error); -+ CHECK(model->ctx->get_cparams().kv_unified); -+ CHECK(skippy_model_memory_cache_capabilities(model) & SKIPPY_MEMORY_CACHE_RESIDENT); -+ constexpr int32_t cache_id = 8; -+ const std::vector tokens(16, 1); -+ auto * source = create(model); -+ prefill(source, tokens); -+ const auto page = export_page(source, tokens.size()); -+ error = nullptr; -+ ok(skippy_session_save_prefix(source, cache_id, tokens.size(), &error), error); -+ const auto expected = decode_logits(source, 2); -+ release(source); -+ skippy_session * restored = nullptr; -+ error = nullptr; -+ ok(skippy_session_create_from_resident_prefix(model, cache_id, -+ tokens.data(), tokens.size(), &restored, &error), error); -+ CHECK(export_page(restored, tokens.size()) == page); -+ CHECK(decode_logits(restored, 2) == expected); -+ release(restored); -+ error = nullptr; -+ ok(skippy_model_free(model, &error), error); -+ -+ // Explicit overrides remain supported, but must not claim resident APIs -+ // that reject this context. Cover both one stream and real multi-stream. -+ for (const uint32_t lanes : {1u, 2u}) { -+ config.lane_count = lanes; -+ config.kv_unified = SKIPPY_TRISTATE_FALSE; -+ model = nullptr; -+ error = nullptr; -+ ok(skippy_model_open(path, &config, &model, &error), error); -+ CHECK(!model->ctx->get_cparams().kv_unified); -+ const auto capabilities = skippy_model_memory_cache_capabilities(model); -+ CHECK(!(capabilities & (SKIPPY_MEMORY_CACHE_RESIDENT -+ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION -+ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT))); -+ CHECK(capabilities & SKIPPY_MEMORY_CACHE_KV_RECURRENT); -+ source = create(model); -+ prefill(source, tokens); -+ error = nullptr; -+ CHECK(skippy_session_save_prefix(source, cache_id, tokens.size(), &error) -+ == SKIPPY_STATUS_UNSUPPORTED); -+ skippy_error_free(error); -+ release(source); -+ error = nullptr; -+ ok(skippy_model_free(model, &error), error); -+ } -+} -+ +} // namespace + +int main(int argc, char ** argv) { -+ if (argc == 2 && std::strcmp(argv[1], "resident-gpu-long") == 0) { -+ const char * model_path = std::getenv("SKIPPY_NATIVE_TEST_REAL_MODEL"); -+ if (!model_path) { std::fprintf(stderr, "SKIPPY_NATIVE_TEST_REAL_MODEL is unset; skipping real GPU checkpoint proof\n"); return 77; } -+ auto config = skippy_runtime_config_default(); -+ config.selected_backend_device = "CPU"; -+ configure_test_gpu(config); -+ return skippy_test_resident_checkpoint_gpu(model_path, config); -+ } -+ CHECK(argc == 4 || argc == 6); ++ CHECK(argc == 4); + const bool grammar = std::strcmp(argv[2], "grammar") == 0; + const bool state = std::strcmp(argv[2], "state") == 0; -+ const bool resident = std::strcmp(argv[2], "resident") == 0; -+ CHECK(grammar || state || resident || std::strcmp(argv[2], "penalty") == 0); -+ const bool automatic = resident && std::strcmp(argv[3], "auto") == 0; -+ CHECK(automatic || std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); -+ CHECK(argc == 4 || resident); ++ CHECK(grammar || state || std::strcmp(argv[2], "penalty") == 0); ++ CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); + require_recurrent = std::strcmp(argv[3], "recurrent") == 0; + auto config = skippy_runtime_config_default(); + config.selected_backend_device = "CPU"; -+ configure_test_gpu(config); -+ if (argc == 6) { -+ config.cache_type_k = cache_type(argv[4]); -+ config.cache_type_v = cache_type(argv[5]); -+ config.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; -+ } + config.ctx_size = 512; -+ if (resident) { config.lane_count = 2; config.kv_unified = 1; } + skippy_model * model = nullptr; + skippy_error * error = nullptr; + const auto status = skippy_model_open(argv[1], &config, &model, &error); + ok(status, error); -+ if (automatic) { -+ const auto capabilities = skippy_model_memory_cache_capabilities(model); -+ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); -+ require_recurrent = capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT; -+ } -+ if (config.n_gpu_layers > 0) { -+ CHECK(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), -+ [](const auto & item) { -+ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } -+ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( -+ ggml_backend_buffer_get_type(item.second->buffer))); -+ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; -+ })); -+ std::fprintf(stderr, "GPU ownership test: device=%s requested_layers=%d\n", config.selected_backend_device, config.n_gpu_layers); -+ } -+ if (resident) { -+ resident_prefix_ownership(model, argc == 6); -+ } else if (state) { ++ if (state) { + // A dense stage's page already carries its whole checkpoint, so the + // partial side payload is intentionally empty there. + CHECK(require_recurrent); + state_round_trip(model); -+ } else if (argmax) { -+ argmax_path(model); + } else { + for (const bool full : {false, true}) { + if (grammar) { @@ -7480,9 +6433,6 @@ index 000000000..ec345c761 + error = nullptr; + const auto freed = skippy_model_free(model, &error); + ok(freed, error); -+ if (resident && !require_recurrent) { -+ dense_resident_configuration(argv[1], config); -+ } + return 0; +} diff --git a/src/skippy/tests/stage_plan_header.c b/src/skippy/tests/stage_plan_header.c @@ -9227,548 +8177,6 @@ index 000000000..87a499031 + } + return 0; +} -diff --git a/tests/test-flash-attn-rows.cpp b/tests/test-flash-attn-rows.cpp -new file mode 100644 -index 000000000..22e1bc3d9 ---- /dev/null -+++ b/tests/test-flash-attn-rows.cpp -@@ -0,0 +1,536 @@ -+#include "ggml.h" -+#include "ggml-alloc.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+namespace { -+constexpr int64_t kv_heads = 2; -+constexpr int64_t requests = 4; -+// Match test_flash_attn_ext::max_nmse_err in test-backend-ops.cpp. -+constexpr double max_nmse = 5e-4; -+ -+struct attention_case { -+ int64_t queries; -+ int64_t logical_rows; -+ bool mask; -+ bool sinks; -+ bool query_local = false; -+ bool strided_query = false; -+ ggml_type type_k = GGML_TYPE_F16; -+ ggml_type type_v = GGML_TYPE_F16; -+ int64_t dk = 256; -+ int64_t dv = 256; -+ float max_bias = 1.5f; -+ int64_t heads = 8; -+ float logit_softcap = 0.0f; -+}; -+ -+void require(bool condition, const char * message) { -+ if (!condition) { -+ throw std::runtime_error(message); -+ } -+} -+ -+struct inputs { -+ const attention_case spec; -+ const int64_t physical_rows; -+ const int64_t mask_queries; -+ std::vector q; -+ const size_t row_k; -+ const size_t row_v; -+ std::vector k, v, logical_k, logical_v; -+ std::vector mask; -+ std::vector rows; -+ std::array visible_rows{}; -+ std::vector sinks; -+ -+ explicit inputs(attention_case value) : spec(value), physical_rows(2*value.logical_rows + 257), -+ mask_queries((value.queries + 63)/64*64), -+ q(value.dk*value.queries*value.heads*requests), -+ row_k(ggml_row_size(value.type_k, value.dk)), row_v(ggml_row_size(value.type_v, value.dv)), -+ k(row_k*physical_rows*kv_heads), v(row_v*physical_rows*kv_heads), -+ logical_k(row_k*value.logical_rows*kv_heads*requests), -+ logical_v(row_v*value.logical_rows*kv_heads*requests), -+ mask(value.logical_rows*mask_queries*requests), -+ rows(value.logical_rows*requests), sinks(value.heads) { -+ std::mt19937 random(34791); -+ std::uniform_real_distribution sample(-0.75f, 0.75f); -+ for (float & item : q) { -+ item = sample(random); -+ } -+ std::vector values(std::max(value.dk, value.dv)*physical_rows*kv_heads); -+ for (float & item : values) { -+ item = sample(random); -+ } -+ ggml_quantize_chunk(value.type_k, values.data(), k.data(), 0, physical_rows*kv_heads, value.dk, nullptr); -+ for (float & item : values) { -+ item = sample(random); -+ } -+ ggml_quantize_chunk(value.type_v, values.data(), v.data(), 0, physical_rows*kv_heads, value.dv, nullptr); -+ for (float & item : sinks) { -+ item = sample(random); -+ } -+ } -+ -+ void refresh(int phase) { -+ const int64_t width = spec.logical_rows; -+ std::fill(rows.begin(), rows.end(), -1); -+ std::fill(logical_k.begin(), logical_k.end(), 0); -+ std::fill(logical_v.begin(), logical_v.end(), 0); -+ const int epoch = phase % 2; -+ const std::array counts = epoch == 0 ? -+ std::array{0, 31, 65, int32_t(width - 7)} : -+ std::array{65, int32_t(width - 9), 0, 31}; -+ for (int64_t request = 0; request < requests; ++request) { -+ visible_rows[request] = spec.mask ? counts[request] : int32_t(width); -+ for (int32_t slot = 0; slot < visible_rows[request]; ++slot) { -+ // Shared first rows plus interleaved, nonmonotonic physical rows. -+ const int32_t physical = int32_t((slot*37 + (slot < 5 ? 0 : request*53) + epoch*101) % physical_rows); -+ rows[request*width + slot] = physical; -+ } -+ for (int64_t slot = 0; slot < width; ++slot) { -+ const int32_t physical = std::max(0, rows[request*width + slot]); -+ for (int64_t head = 0; head < kv_heads; ++head) { -+ const size_t src = head*physical_rows + physical; -+ const size_t dst = (request*kv_heads + head)*width + slot; -+ // Preserve the exact encoded block bytes, not re-quantized floats. -+ std::copy_n(k.data() + src*row_k, row_k, logical_k.data() + dst*row_k); -+ std::copy_n(v.data() + src*row_v, row_v, logical_v.data() + dst*row_v); -+ } -+ } -+ for (int64_t query = 0; query < mask_queries; ++query) { -+ const int32_t count = std::max(0, visible_rows[request] - (spec.query_local ? int32_t(query % 3) : 0)); -+ for (int64_t slot = 0; slot < width; ++slot) { -+ float bias = -std::numeric_limits::infinity(); -+ if (query < spec.queries && slot < count) { -+ bias = spec.mask ? -0.025f*float(slot % 7) : 0.0f; -+ if (spec.mask && slot % 11 == 3) { -+ bias = -std::numeric_limits::infinity(); -+ } -+ } -+ mask[(request*mask_queries + query)*width + slot] = ggml_fp32_to_fp16(bias); -+ } -+ } -+ } -+ } -+}; -+ -+struct graph_fixture { -+ ggml_context * ctx = nullptr; -+ ggml_backend_buffer_t buffer = nullptr; -+ ggml_tensor * q = nullptr; -+ ggml_tensor * k = nullptr; -+ ggml_tensor * v = nullptr; -+ ggml_tensor * mask = nullptr; -+ ggml_tensor * rows = nullptr; -+ ggml_tensor * sinks = nullptr; -+ ggml_tensor * output = nullptr; -+ ggml_cgraph * graph = nullptr; -+ const bool row_based; -+ -+ graph_fixture(ggml_backend_t backend, const inputs & data, bool use_rows) : row_based(use_rows) { -+ ggml_init_params params{32*ggml_tensor_overhead() + ggml_graph_overhead_custom(32, false), nullptr, true}; -+ ctx = ggml_init(params); -+ require(ctx != nullptr, "allocate graph context"); -+ if (data.spec.strided_query) { -+ auto storage = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, 2*data.spec.queries, data.spec.heads, requests); -+ q = ggml_view_4d(ctx, storage, data.spec.dk, data.spec.queries, data.spec.heads, requests, -+ 2*storage->nb[1], storage->nb[2], storage->nb[3], 0); -+ } else { -+ q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, data.spec.queries, data.spec.heads, requests); -+ } -+ const int64_t storage_rows = row_based ? data.physical_rows : data.spec.logical_rows; -+ const int64_t streams = row_based ? 1 : requests; -+ k = ggml_new_tensor_4d(ctx, data.spec.type_k, data.spec.dk, storage_rows, kv_heads, streams); -+ v = ggml_new_tensor_4d(ctx, data.spec.type_v, data.spec.dv, storage_rows, kv_heads, streams); -+ // The ordinary reference materializes exactly the same row0 padding. -+ if (row_based || data.spec.mask) { -+ mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, data.spec.logical_rows, data.mask_queries, 1, requests); -+ } -+ if (row_based) { -+ rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, data.spec.logical_rows, requests); -+ output = ggml_flash_attn_ext_rows(ctx, q, k, v, mask, rows, -+ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, -+ data.spec.logit_softcap); -+ } else { -+ output = ggml_flash_attn_ext(ctx, q, k, v, mask, -+ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, -+ data.spec.logit_softcap); -+ } -+ if (data.spec.sinks) { -+ sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, data.spec.heads); -+ ggml_flash_attn_ext_add_sinks(output, sinks); -+ } -+ ggml_prec_set_acc(output, GGML_PREC_F32); -+ require(output->src[5] == rows && output->src[6] == nullptr, -+ "row constructor must preserve the src5-only contract"); -+ if (rows) { -+ require(rows->type == GGML_TYPE_I32 && rows->ne[0] == data.spec.logical_rows && -+ rows->ne[1] == requests && rows->ne[2] == 1 && rows->ne[3] == 1, -+ "row constructor must use one physical table per query stream"); -+ } -+ require(ggml_backend_supports_op(backend, output), "selected backend does not support rows test shape"); -+ graph = ggml_new_graph_custom(ctx, 32, false); -+ ggml_build_forward_expand(graph, output); -+ buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); -+ require(buffer != nullptr, "allocate backend graph tensors"); -+ } -+ -+ ~graph_fixture() { -+ ggml_backend_buffer_free(buffer); -+ ggml_free(ctx); -+ } -+ graph_fixture(const graph_fixture &) = delete; -+ graph_fixture & operator=(const graph_fixture &) = delete; -+ -+ std::vector run(ggml_backend_t backend, const inputs & data) { -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t head = 0; head < data.spec.heads; ++head) { -+ for (int64_t query = 0; query < data.spec.queries; ++query) { -+ const size_t offset = request*q->nb[3] + head*q->nb[2] + query*q->nb[1]; -+ const size_t source = ((request*data.spec.heads + head)*data.spec.queries + query)*data.spec.dk; -+ ggml_backend_tensor_set(q, data.q.data() + source, offset, data.spec.dk*sizeof(float)); -+ } -+ } -+ } -+ ggml_backend_tensor_set(k, row_based ? data.k.data() : data.logical_k.data(), 0, ggml_nbytes(k)); -+ ggml_backend_tensor_set(v, row_based ? data.v.data() : data.logical_v.data(), 0, ggml_nbytes(v)); -+ if (mask) { -+ ggml_backend_tensor_set(mask, data.mask.data(), 0, ggml_nbytes(mask)); -+ } -+ if (rows) { -+ ggml_backend_tensor_set(rows, data.rows.data(), 0, ggml_nbytes(rows)); -+ } -+ if (sinks) { -+ ggml_backend_tensor_set(sinks, data.sinks.data(), 0, ggml_nbytes(sinks)); -+ } -+ require(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS, "compute attention graph"); -+ std::vector result(ggml_nelements(output)); -+ ggml_backend_tensor_get(output, result.data(), 0, ggml_nbytes(output)); -+ return result; -+ } -+}; -+ -+bool exceptional_query(const inputs & data, int64_t request, int64_t query) { -+ if (data.spec.sinks) { return false; } -+ const auto begin = data.mask.begin() + (request*data.mask_queries + query)*data.spec.logical_rows; -+ return std::all_of(begin, begin + data.spec.logical_rows, -+ [](ggml_fp16_t value) { return ggml_fp16_to_fp32(value) == -INFINITY; }); -+} -+ -+int result_class(float value) { -+ if (std::isfinite(value)) { return 0; } -+ if (std::isnan(value)) { return 1; } -+ return std::signbit(value) ? 3 : 2; -+} -+ -+void exceptional_result_control(const std::vector & ordinary, const std::vector & rows, -+ const inputs & data, const char * backend, int phase) { -+ std::array ordinary_classes{}, rows_classes{}; -+ size_t mismatches = 0, elements = 0; -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t query = 0; query < data.spec.queries; ++query) { -+ if (!exceptional_query(data, request, query)) { continue; } -+ const size_t begin = (request*data.spec.queries + query)*data.spec.heads*data.spec.dv; -+ for (size_t i = begin; i < begin + data.spec.heads*data.spec.dv; ++i) { -+ const int left = result_class(ordinary[i]), right = result_class(rows[i]); -+ ++ordinary_classes[left]; ++rows_classes[right]; -+ mismatches += left != right; ++elements; -+ } -+ } -+ } -+ if (!elements) { return; } -+ std::printf("EXCEPTIONAL_RESULT backend=%s phase=%d elements=%zu ordinary_finite_nan_posinf_neginf=%zu,%zu,%zu,%zu rows_finite_nan_posinf_neginf=%zu,%zu,%zu,%zu class_mismatches=%zu no_finite_qualification=1\n", -+ backend, phase, elements, ordinary_classes[0], ordinary_classes[1], ordinary_classes[2], ordinary_classes[3], -+ rows_classes[0], rows_classes[1], rows_classes[2], rows_classes[3], mismatches); -+ require(mismatches == 0, "same-backend all-masked ordinary/rows result classes differ"); -+} -+ -+void compare(const std::vector & expected, const std::vector & actual, -+ const inputs & data, const char * backend, int phase) { -+ double maximum_nmse = 0.0; -+ float max_absolute = 0.0f; -+ const size_t request_elements = data.spec.dv*data.spec.heads*data.spec.queries; -+ std::vector exceptional(requests*data.spec.queries); -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t query = 0; query < data.spec.queries; ++query) { -+ exceptional[request*data.spec.queries + query] = exceptional_query(data, request, query); -+ } -+ } -+ for (int64_t request = 0; request < requests; ++request) { -+ double error = 0.0, energy = 0.0; -+ for (size_t i = request*request_elements; i < (request + 1)*request_elements; ++i) { -+ const int64_t query = (i - request*request_elements) / (data.spec.heads*data.spec.dv); -+ if (exceptional[request*data.spec.queries + query]) { continue; } -+ require(std::isfinite(expected[i]) && std::isfinite(actual[i]), "non-finite attention output"); -+ const double delta = double(expected[i]) - actual[i]; -+ error += delta*delta; -+ energy += double(expected[i])*expected[i]; -+ max_absolute = std::max(max_absolute, float(std::abs(delta))); -+ } -+ if (energy == 0.0) { -+ require(error == 0.0, "zero-energy finite-domain output must remain exact"); -+ } else { -+ maximum_nmse = std::max(maximum_nmse, error/energy); -+ require(error/energy <= max_nmse, "rows attention exceeds existing FA NMSE tolerance"); -+ } -+ } -+ std::printf("PASS finite-domain backend=%s K=%s V=%s dk=%lld dv=%lld heads=%lld bias=%.2f q=%lld logical=%lld mask=%d sinks=%d query_local=%d strided_q=%d softcap=%.2f phase=%d max_request_nmse=%.9g max_abs=%.9g\n", -+ backend, ggml_type_name(data.spec.type_k), ggml_type_name(data.spec.type_v), -+ (long long) data.spec.dk, (long long) data.spec.dv, (long long) data.spec.heads, -+ data.spec.mask ? data.spec.max_bias : 0.0f, (long long) data.spec.queries, (long long) data.spec.logical_rows, -+ data.spec.mask, data.spec.sinks, data.spec.query_local, data.spec.strided_query, -+ data.spec.logit_softcap, phase, maximum_nmse, max_absolute); -+} -+ -+void set_threads(ggml_backend_t backend) { -+ const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)); -+ const auto setter = reinterpret_cast( -+ ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads")); -+ if (setter) { -+ setter(backend, 4); -+ } -+} -+ -+// Accept an exact device (e.g. MTL0/CUDA0) or its registry (Metal/CUDA). -+ggml_backend_t open_backend(const char * name) { -+ if (auto exact = ggml_backend_init_by_name(name, nullptr)) { -+ return exact; -+ } -+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { -+ auto device = ggml_backend_dev_get(i); -+ const auto registry = ggml_backend_dev_backend_reg(device); -+ if (std::strcmp(ggml_backend_reg_name(registry), name) == 0) { -+ return ggml_backend_dev_init(device, nullptr); -+ } -+ } -+ return nullptr; -+} -+ -+void run_case(ggml_backend_t cpu, ggml_backend_t target, attention_case spec) { -+ inputs data(spec); -+ graph_fixture reference(cpu, data, false); -+ graph_fixture row_based(cpu, data, true); -+ require(reference.output->src[5] == nullptr && reference.output->src[6] == nullptr, -+ "ordinary FA must remain free of row metadata"); -+ if (!spec.mask) { -+ require(reference.mask == nullptr && row_based.mask != nullptr, -+ "ordinary unmasked input and required rows zero-mask metadata are distinct representations"); -+ std::printf("REPRESENTATION ordinary_mask=null rows_mask=explicit_zero logical_values=unmasked\n"); -+ } -+ require(std::memcmp(reference.output->op_params, row_based.output->op_params, -+ sizeof(reference.output->op_params)) == 0, "rows must retain ordinary arithmetic parameters"); -+ std::unique_ptr device; -+ std::unique_ptr device_ordinary; -+ if (target != cpu) { -+ if (ggml_backend_supports_op(target, row_based.output)) { -+ require(ggml_backend_supports_op(target, reference.output), "rows require an ordinary same-backend control"); -+ device = std::make_unique(target, data, true); -+ device_ordinary = std::make_unique(target, data, false); -+ std::printf("ADMISSION rows backend=%s K=%s V=%s dk=%lld dv=%lld q=%lld mask=%d\n", -+ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), -+ (long long) spec.dk, (long long) spec.dv, (long long) spec.queries, spec.mask); -+ } else { -+ const bool dense_supported = ggml_backend_supports_op(target, reference.output); -+ if (dense_supported) { -+ device = std::make_unique(target, data, false); -+ } -+ std::printf("%s backend=%s K=%s V=%s q=%lld mask=%d query_local=%d softcap=%.2f rows_admission=0 ordinary_admission=%d; CPU reference is separate\n", -+ dense_supported ? "FALLBACK ordinary-selected-backend" : "SKIP unsupported-selected-backend", -+ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), -+ (long long) spec.queries, spec.mask, spec.query_local, spec.logit_softcap, dense_supported); -+ } -+ } -+ // Changed row tables and masks must remain visible after graph reuse. -+ for (int phase = 0; phase < 4; ++phase) { -+ data.refresh(phase); -+ const auto expected = reference.run(cpu, data); -+ if (phase == 0) { -+ const auto repeated = reference.run(cpu, data); -+ require(expected.size() == repeated.size(), "ordinary repeat output size"); -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t query = 0; query < spec.queries; ++query) { -+ const size_t begin = (request*spec.queries + query)*spec.heads*spec.dv; -+ const size_t count = spec.heads*spec.dv; -+ if (exceptional_query(data, request, query)) { -+ for (size_t i = begin; i < begin + count; ++i) { -+ require(result_class(expected[i]) == result_class(repeated[i]), "ordinary exceptional repeat class"); -+ } -+ } else { -+ require(std::memcmp(expected.data() + begin, repeated.data() + begin, -+ count*sizeof(float)) == 0, "ordinary finite-domain output must self-repeat exactly"); -+ } -+ } -+ } -+ } -+ const auto cpu_rows = row_based.run(cpu, data); -+ exceptional_result_control(expected, cpu_rows, data, ggml_backend_name(cpu), phase); -+ compare(expected, cpu_rows, data, ggml_backend_name(cpu), phase); -+ if (device) { -+ const auto actual = device->run(target, data); -+ if (device_ordinary && spec.mask && !spec.sinks) { -+ const auto ordinary = device_ordinary->run(target, data); -+ exceptional_result_control(ordinary, actual, data, ggml_backend_name(target), phase); -+ } -+ compare(expected, actual, data, ggml_backend_name(target), phase); -+ } -+ } -+} -+ -+void run_unquantized_vector_cases(ggml_backend_t cpu, ggml_backend_t target) { -+ const std::array types = {GGML_TYPE_F16, GGML_TYPE_BF16}; -+ // Wide GQA must retain the shared hardware policy rather than force vec. -+ for (auto type_k : types) { -+ for (auto type_v : types) { -+ for (int64_t queries : {1, 2}) { -+ run_case(cpu, target, {queries, 256, true, false, false, false, -+ type_k, type_v, 256, 256, 0.0f, 16}); -+ } -+ } -+ } -+ for (int64_t dimension : {64, 128, 256}) { -+ for (auto type_k : types) { -+ for (auto type_v : types) { -+ for (int64_t queries : {1, 2}) { -+ if (dimension != 256) { -+ run_case(cpu, target, {queries, 256, true, true, false, false, -+ type_k, type_v, dimension, dimension}); -+ } -+ run_case(cpu, target, {queries, 256, false, false, false, false, -+ type_k, type_v, dimension, dimension}); -+ if (dimension != 64) { -+ run_case(cpu, target, {queries, 256, true, true, false, false, -+ type_k, type_v, dimension, dimension, 0.0f, 8, 4.0f}); -+ } -+ } -+ } -+ } -+ } -+ run_case(cpu, target, {2, 256, true, true, false, true, -+ GGML_TYPE_F16, GGML_TYPE_BF16, 128, 128}); -+} -+ -+void run_softcap_capability_cases(ggml_backend_t cpu, ggml_backend_t target) { -+ const auto registry = ggml_backend_dev_backend_reg(ggml_backend_get_device(target)); -+ const bool cuda = std::strcmp(ggml_backend_reg_name(registry), "CUDA") == 0; -+ for (auto type_k : {GGML_TYPE_F16, GGML_TYPE_BF16}) { -+ for (auto type_v : {GGML_TYPE_F16, GGML_TYPE_BF16}) { -+ for (int64_t queries : {1, 2}) { -+ attention_case spec{queries, 256, true, true, false, false, -+ type_k, type_v, 64, 64, 0.0f, 8, 4.0f}; -+ if (cuda) { -+ inputs data(spec); -+ graph_fixture dense(cpu, data, false); -+ graph_fixture row_based(cpu, data, true); -+ require(!ggml_backend_supports_op(target, dense.output) && -+ !ggml_backend_supports_op(target, row_based.output), -+ "CUDA must refuse head64 softcap without a compiled kernel"); -+ std::printf("PASS CUDA admission refuses unsupported softcap K=%s V=%s dk=64 q=%lld\n", -+ ggml_type_name(type_k), ggml_type_name(type_v), (long long) queries); -+ } -+ // CPU reference coverage is separate; a CUDA skip is not a GPU pass. -+ run_case(cpu, target, spec); -+ } -+ } -+ } -+ const std::array, 5> shapes = {{{192, 128, 16}, -+ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; -+ for (const auto & shape : shapes) { -+ for (auto type : {GGML_TYPE_F16, GGML_TYPE_BF16}) { -+ for (int64_t queries : {1, 2}) { -+ run_case(cpu, target, {queries, 256, true, true, false, false, -+ type, type, shape[0], shape[1], 0.0f, shape[2], 4.0f}); -+ } -+ } -+ } -+} -+} // namespace -+ -+int main(int argc, char ** argv) { -+ try { -+ require(argc == 1 || (argc == 3 && std::strcmp(argv[1], "--backend") == 0), -+ "usage: test-flash-attn-rows [--backend DEVICE_NAME]"); -+ ggml_backend_load_all(); -+ using backend_ptr = std::unique_ptr; -+ backend_ptr cpu(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr), ggml_backend_free); -+ require(cpu != nullptr, "CPU reference backend unavailable"); -+ set_threads(cpu.get()); -+ backend_ptr selected(nullptr, ggml_backend_free); -+ if (argc == 3) { -+ selected.reset(open_backend(argv[2])); -+ require(selected != nullptr, "requested backend unavailable"); -+ } else { -+ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)); -+ if (!selected) { -+ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr)); -+ } -+ } -+ const bool selected_cpu = selected && -+ ggml_backend_dev_type(ggml_backend_get_device(selected.get())) == GGML_BACKEND_DEVICE_TYPE_CPU; -+ auto target = selected && !selected_cpu ? selected.get() : cpu.get(); -+ std::printf("rows FA: CPU reference and target=%s; per-request NMSE limit=%.9g\n", ggml_backend_name(target), max_nmse); -+ for (int64_t queries : {1, 2, 4, 31, 32, 64}) { -+ run_case(cpu.get(), target, {queries, 256, true, true}); -+ } -+ run_case(cpu.get(), target, {1, 4352, true, true}); -+ run_case(cpu.get(), target, {4, 256, false, false}); -+ run_case(cpu.get(), target, {31, 256, true, false, true}); -+ run_case(cpu.get(), target, {32, 256, true, true, false, true}); -+ const std::array types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, -+ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}; -+ for (auto type_k : types) { -+ for (auto type_v : types) { -+ for (int64_t queries : {1, 2, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, type_k, type_v}); -+ } -+ } -+ } -+ run_unquantized_vector_cases(cpu.get(), target); -+ run_softcap_capability_cases(cpu.get(), target); -+ const std::array, 13> head_shapes = {{{32, 32}, {64, 64}, {96, 96}, -+ {96, 64}, {128, 128}, {128, 96}, {192, 192}, {192, 128}, {256, 256}, -+ {320, 256}, {512, 512}, {576, 512}, {128, 64}}}; -+ for (const auto & dimensions : head_shapes) { -+ for (auto type : types) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimensions[0], dimensions[1]}); -+ } -+ } -+ } -+ // CUDA's larger-head kernels require zero ALiBi and admitted GQA tile ratios. -+ const std::array, 5> wide_shapes = {{{192, 128, 16}, -+ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; -+ for (const auto & dimensions : wide_shapes) { -+ for (auto type : types) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimensions[0], dimensions[1], 0.0f, dimensions[2]}); -+ } -+ } -+ } -+ for (int64_t dimension : {40, 48, 72, 80, 112}) { -+ for (auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimension, dimension}); -+ } -+ } -+ } -+ return 0; -+ } catch (const std::exception & error) { -+ std::fprintf(stderr, "rows FA test failed: %s\n", error.what()); -+ return 1; -+ } -+} diff --git a/tests/test-graph-contract-fixture.h b/tests/test-graph-contract-fixture.h new file mode 100644 index 000000000..c45915888 @@ -11285,127 +9693,29 @@ index 000000000..b15b5e53a +} diff --git a/tests/test-skippy-kv-cells-contiguous.cpp b/tests/test-skippy-kv-cells-contiguous.cpp new file mode 100644 -index 000000000..d922e73c0 +index 000000000..0e95c35b2 --- /dev/null +++ b/tests/test-skippy-kv-cells-contiguous.cpp -@@ -0,0 +1,118 @@ +@@ -0,0 +1,20 @@ +#include "../src/llama-kv-cells.h" + -+#include -+#include -+#include -+#include -+ -+namespace { -+void check(bool pass, const char * reason) { -+ if (!pass) { throw std::runtime_error(reason); } -+} -+ -+void check_rows(const llama_kv_cells & cells) { -+ const std::vector owners = {0, 1, 2, 3, 4}; -+ const std::vector minima = {0, 2, 4, 1, 0}; -+ for (int cutoff : {0, 1, 2}) { -+ const auto minimum = cutoff == 0 ? std::vector{} : -+ cutoff == 1 ? minima : std::vector(owners.size(), -100); -+ std::vector actual(cells.size() * owners.size(), -2); -+ cells.get_seq_cells(owners, minimum, actual.data(), cells.size()); -+ for (size_t s = 0; s < owners.size(); ++s) { -+ std::vector expected; -+ std::set> positions; -+ for (uint32_t i = 0; i < cells.size(); ++i) { -+ if (cells.is_empty(i) || !cells.seq_has(i, owners[s])) { continue; } -+ positions.emplace(cells.pos_get(i), i); -+ if (minimum.empty() || cells.pos_get(i) >= minimum[s]) { expected.push_back(i); } -+ } -+ check(positions == cells.seq_pos_get(owners[s]), "logical position index differs from physical owners"); -+ expected.resize(cells.size(), -1); -+ check(std::equal(expected.begin(), expected.end(), actual.begin() + s*cells.size()), -+ "row bitmap differs from physical-order owner scan or padding"); -+ } -+ } -+} -+ -+void contiguous_positions() { ++int main() { + llama_kv_cells cells; + cells.resize(8); + for (uint32_t i = 0; i < 4; ++i) { + cells.pos_set(i, static_cast(i)); + cells.seq_add(i, 0); + } -+ check(cells.seq_pos_is_cell_contiguous(0), "dense prefix must remain resident-admissible"); -+ check_rows(cells); ++ if (!cells.seq_pos_is_cell_contiguous(0)) return 1; ++ + cells.mv(1, 4); -+ check(!cells.seq_pos_is_cell_contiguous(0), "moved prefix must not appear physically contiguous"); -+ check_rows(cells); ++ if (cells.seq_pos_is_cell_contiguous(0)) return 2; + cells.mv(4, 1); -+ check(cells.seq_pos_is_cell_contiguous(0), "restored physical prefix must regain admission"); -+ check(cells.seq_rm(2, 0) && cells.is_empty(2), "removed sole owner must clear cell"); -+ check(!cells.seq_pos_is_cell_contiguous(0), "prefix hole must reject complete-prefix admission"); -+ check_rows(cells); -+} -+ -+void shared_ownership_and_restore() { -+ llama_kv_cells cells; -+ cells.resize(192); -+ for (uint32_t i = 0; i < 8; ++i) { -+ cells.pos_set(i, i); -+ for (llama_seq_id owner = 0; owner < 5; ++owner) { cells.seq_add(i, owner); } -+ } -+ for (const auto & item : {std::pair{130, 8}, {63, 10}, {64, 9}}) { -+ cells.pos_set(item.first, item.second); -+ cells.seq_add(item.first, 1); -+ } -+ check(!cells.seq_pos_is_cell_contiguous(1), "scattered tail must reject contiguous resident admission"); -+ check(cells.seq_pos_is_cell_contiguous(4), "parked alias must retain complete prefix admission"); -+ check_rows(cells); -+ for (uint32_t i = 0; i < 8; ++i) { -+ check(!cells.seq_rm(i, 0), "removing one alias must preserve shared cell"); -+ } -+ check_rows(cells); -+ cells.pos_set(191, 40); cells.seq_add(191, 0); -+ cells.rm(191); -+ cells.pos_set(191, 0); cells.seq_add(191, 0); -+ check_rows(cells); -+ cells.mv(64, 65); -+ cells.pos_add(63, 7); -+ cells.pos_div(130, 2); -+ check_rows(cells); -+ check(cells.seq_pos_is_cell_contiguous(4), "other owners' shifts must not invalidate parked prefix"); -+ cells.reset_shift(); -+ const auto sparse = cells.cp(std::vector{130, 65, 0, 191}); -+ const auto contiguous = cells.cp(0, 8); -+ llama_kv_cells restored; -+ restored.resize(192); -+ restored.set(std::vector{64, 127, 129, 190}, sparse); -+ check_rows(restored); -+ restored.set(0, contiguous); -+ check_rows(restored); -+ llama_kv_cells empty; empty.resize(1); -+ restored.set(64, empty); -+ check_rows(restored); -+ check(!cells.seq_keep(0, 4), "keeping parked alias must retain its shared payload"); -+ check(cells.seq_keep(65, 4), "keeping absent alias must clear its cell"); -+ check(cells.seq_pos_is_cell_contiguous(4) && !cells.seq_pos_is_cell_contiguous(1), -+ "keeping a shared owner must update each resident prefix index"); -+ check_rows(cells); -+ check(cells.pos_add(191, -1), "negative logical shift must remove recycled row"); -+ check_rows(cells); -+ cells.reset(); check_rows(cells); -+ cells.resize(65); check_rows(cells); -+ cells.pos_set(64, 0); cells.seq_add(64, 4); check_rows(cells); -+ cells.resize(8); check_rows(cells); -+} -+} // namespace ++ if (!cells.seq_pos_is_cell_contiguous(0)) return 3; + -+int main() { -+ try { -+ contiguous_positions(); -+ shared_ownership_and_restore(); -+ return 0; -+ } catch (const std::exception & error) { -+ std::fprintf(stderr, "KV cell ownership test failed: %s\n", error.what()); -+ return 1; -+ } ++ if (!cells.seq_rm(2, 0)) return 4; ++ if (cells.seq_pos_is_cell_contiguous(0)) return 5; ++ return 0; +} diff --git a/tests/test-skippy-kv-page-export.cpp b/tests/test-skippy-kv-page-export.cpp new file mode 100644 @@ -11453,12 +9763,12 @@ index 000000000..30c88b490 + }); + return skippy_graph_cache_capabilities(result); + }; -+ const uint32_t dense = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | ++ const uint32_t dense = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | + SKIPPY_MEMORY_CACHE_FULL_STATE; + if (capabilities(skippy_state_kind::kv_key) != dense || + capabilities(skippy_state_kind::kv_value) != dense || -+ capabilities(skippy_state_kind::recurrent_conv) != dense || -+ capabilities(skippy_state_kind::recurrent_ssm) != dense || ++ capabilities(skippy_state_kind::recurrent_conv) != (SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || ++ capabilities(skippy_state_kind::recurrent_ssm) != (SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || + capabilities(skippy_state_kind::derived_persistent) != SKIPPY_MEMORY_CACHE_FULL_STATE) { + return false; + } @@ -11533,7 +9843,7 @@ index 000000000..30c88b490 + {}); + + if (skippy_memory_cache_capabilities(&kv) != -+ (SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || ++ (SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE) || + skippy_model_memory_cache_capabilities(nullptr) != 0) { + return 1; + } @@ -12116,8 +10426,6 @@ index 000000000..0fae7bbd4 +#include "../src/llama-io.h" +#include "../src/llama-memory-recurrent.h" +#include "../src/llama-model.h" -+#include "../src/skippy/state_memory.h" -+#include "skippy/state.h" + +#include "ggml-backend.h" + @@ -12204,13 +10512,6 @@ index 000000000..0fae7bbd4 + model->hparams.ssm_d_inner = 2; + + auto source = make_memory(*model); -+ const auto capabilities = skippy_memory_cache_capabilities(&source); -+ if (!(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) -+ || !(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT) -+ || (capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION)) { -+ std::fprintf(stderr, "pure recurrent memory has an incorrect resident attention contract\n"); -+ return 13; -+ } + llama_pos source_pos = 7; + llama_seq_id source_seq_id = 0; + llama_seq_id * source_seq_ids = &source_seq_id; @@ -12279,37 +10580,6 @@ index 000000000..0fae7bbd4 + return 7; + } + -+ // Immutable cache-owned bytes survive source lane removal and reuse. -+ if (!source.seq_rm(source_seq_id, -1, -1)) { return 8; } -+ const std::vector changed_r = { 91.0f, 92.0f, 93.0f, 94.0f }; -+ ggml_backend_tensor_set(source.r_l[0], changed_r.data(), 0, changed_r.size() * sizeof(float)); -+ buffer_reader second_reader(writer.data); -+ destination.state_read(second_reader, 0, LLAMA_STATE_SEQ_FLAGS_NONE); -+ const auto a_row = destination.cells[0].tail; -+ const auto b_row = destination.cells[1].tail; -+ if (a_row < 0 || b_row < 0 || a_row == b_row) { -+ std::fprintf(stderr, "restored recurrent borrowers did not receive private mutable rows\n"); -+ return 9; -+ } -+ ggml_backend_tensor_set(destination.r_l[0], changed_r.data(), -+ destination.r_l[0]->nb[1] * a_row, changed_r.size() * sizeof(float)); -+ buffer_writer preserved_b; -+ destination.state_write(preserved_b, 1, LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (preserved_b.data != writer.data) { -+ std::fprintf(stderr, "diverging borrower changed another recurrent checkpoint\n"); -+ return 10; -+ } -+ // The original checkpoint can restore again after either borrower is freed. -+ if (!destination.seq_rm(0, -1, -1)) { return 11; } -+ buffer_reader third_reader(writer.data); -+ destination.state_read(third_reader, 0, LLAMA_STATE_SEQ_FLAGS_NONE); -+ buffer_writer restored_a; -+ destination.state_write(restored_a, 0, LLAMA_STATE_SEQ_FLAGS_NONE); -+ if (restored_a.data != writer.data) { -+ std::fprintf(stderr, "recurrent checkpoint changed after repeated lane recycling\n"); -+ return 12; -+ } -+ + return 0; +} diff --git a/tests/test-skippy-rerank-template.cpp b/tests/test-skippy-rerank-template.cpp diff --git a/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch b/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch index 57b1e2eeff..4dc41fd716 100644 --- a/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch +++ b/skippy/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch @@ -220,10 +220,10 @@ index d8276944d..3a147d14d 100644 + skippy_native_mtp_draft * out_mtp_draft, + skippy_error ** out_error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index cf0838051..b2f394444 100644 +index f035ea13f..15c48419d 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp -@@ -733,7 +733,7 @@ enum skippy_status skippy_trim_session( +@@ -852,7 +852,7 @@ enum skippy_status skippy_trim_session( if (session->signal_history.size() > token_count) { session->signal_history.resize(static_cast(token_count)); } diff --git a/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch b/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch index ad2b45ebad..80935de3e1 100644 --- a/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch +++ b/skippy/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch @@ -23,10 +23,10 @@ resets, instead of attaching rebuilt chains to the backend. 5 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index ba072fe82..db3392ddf 100644 +index 38ebae8d7..f44e874d9 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -165,6 +165,11 @@ struct skippy_session { +@@ -158,6 +158,11 @@ struct skippy_session { // detached -- e.g. so a sampled verify window can output every row -- // it must never be re-attached; only building a fresh chain clears this. bool sampling_backend_retired = false; @@ -61,10 +61,10 @@ index 6fd1240e3..de5fa6ba5 100644 // scheduler may reset and reuse the same chain on every iteration; // attaching it again violates llama_sampler_chain's one-shot init diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index be612007f..0653347a7 100644 +index f1de95cc5..36c972d92 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -389,6 +389,7 @@ enum skippy_status skippy_session_reset( +@@ -392,6 +392,7 @@ enum skippy_status skippy_session_reset( skippy_clear_chat_sampling(session); } skippy_mtp_clear_session_state(session); diff --git a/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch b/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch index 1a4bb67da3..c6ffd15514 100644 --- a/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch +++ b/skippy/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch @@ -37,7 +37,7 @@ index b9b5259af..df831c43e 100644 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index b47c55f82..c930d9c3b 100644 +index 799bdca2d..bc4da9a07 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -117,6 +117,12 @@ struct skippy_runtime_config { @@ -132,7 +132,7 @@ index 554d2bdd3..e3649e713 100644 const skippy_runtime_config * config, llama_context_params & params); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index d6e24cd2a..4082fa198 100644 +index 60a27669f..7305cc529 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -962,10 +962,12 @@ enum skippy_status skippy_model_open_impl( diff --git a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch b/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch deleted file mode 100644 index ddb7d03b48..0000000000 --- a/skippy/llama_cpp/patches/0013-feat-ggml-read-request-local-KV-indices-in-flash-att.patch +++ /dev/null @@ -1,3975 +0,0 @@ -From 49e7635856484a30c1e98fc5755e50c933d26306 Mon Sep 17 00:00:00 2001 -From: Mesh-LLM CI -Date: Sat, 31 Oct 2026 17:14:46 +1100 -Subject: [PATCH] feat(ggml): read request-local KV indices in flash attention - ---- - ggml/include/ggml.h | 18 + - ggml/src/ggml-backend-meta.cpp | 5 + - ggml/src/ggml-cann/ggml-cann.cpp | 3 + - ggml/src/ggml-cpu/CMakeLists.txt | 2 + - ggml/src/ggml-cpu/attention-indexed.cpp | 121 ++++++ - ggml/src/ggml-cpu/attention-indexed.h | 7 + - ggml/src/ggml-cpu/ops.cpp | 5 + - ggml/src/ggml-cpu/spacemit/ime.cpp | 3 + - ggml/src/ggml-cuda/common.cuh | 1 + - ggml/src/ggml-cuda/fattn-common.cuh | 66 ++- - ggml/src/ggml-cuda/fattn-indexed.cuh | 45 +++ - ggml/src/ggml-cuda/fattn-mma-f16.cuh | 208 ++++++---- - ggml/src/ggml-cuda/fattn-tile.cuh | 95 ++++- - ggml/src/ggml-cuda/fattn-vec.cuh | 53 ++- - ggml/src/ggml-cuda/fattn.cu | 68 +++- - ggml/src/ggml-cuda/ggml-cuda.cu | 1 + - ggml/src/ggml-et/ggml-et.cpp | 3 + - ggml/src/ggml-hexagon/ggml-hexagon.cpp | 2 +- - .../ggml-metal/ggml-metal-attention-indexed.h | 90 +++++ - ggml/src/ggml-metal/ggml-metal-device.cpp | 12 +- - ggml/src/ggml-metal/ggml-metal-device.m | 5 + - ggml/src/ggml-metal/ggml-metal-impl.h | 10 + - ggml/src/ggml-metal/ggml-metal-ops.cpp | 62 ++- - ggml/src/ggml-metal/kernels/fa_common.metal | 144 ++++++- - .../ggml-metal/kernels/fa_vec_common.metal | 29 +- - ggml/src/ggml-opencl/ggml-opencl.cpp | 3 + - ggml/src/ggml-openvino/ggml-openvino.cpp | 3 + - ggml/src/ggml-sycl/ggml-sycl.cpp | 2 +- - ggml/src/ggml-vulkan/ggml-vulkan.cpp | 3 + - ggml/src/ggml-webgpu/ggml-webgpu.cpp | 2 +- - ggml/src/ggml.c | 44 +- - src/CMakeLists.txt | 2 + - src/llama-graph-kv-read.cpp | 134 +++++++ - src/llama-graph.cpp | 85 ++-- - src/llama-graph.h | 21 +- - src/llama-kv-cache.h | 2 + - src/llama-kv-read.cpp | 148 +++++++ - src/llama-kv-read.h | 20 + - tests/CMakeLists.txt | 2 + - tests/test-flash-attn-indexed.cpp | 378 ++++++++++++++++++ - 40 files changed, 1698 insertions(+), 209 deletions(-) - create mode 100644 ggml/src/ggml-cpu/attention-indexed.cpp - create mode 100644 ggml/src/ggml-cpu/attention-indexed.h - create mode 100644 ggml/src/ggml-cuda/fattn-indexed.cuh - create mode 100644 ggml/src/ggml-cuda/fattn-vec-dense.cuh - create mode 100644 ggml/src/ggml-metal/ggml-metal-attention-indexed.h - create mode 100644 src/llama-graph-kv-read.cpp - create mode 100644 src/llama-kv-read.cpp - create mode 100644 src/llama-kv-read.h - create mode 100644 tests/test-flash-attn-indexed.cpp - -diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h -index c37ba9471..315f554a7 100644 ---- a/ggml/include/ggml.h -+++ b/ggml/include/ggml.h -@@ -2499,6 +2499,24 @@ extern "C" { - float max_bias, - float logit_softcap); - -+ // Same attention operation with request-local reads from shared physical K/V. -+ // indices: I32 [logical_kv, query_rows, heads, requests], broadcast over Q. -+ // lengths: I32 [1, query_rows, heads, requests], matching indices dimensions. -+ // The F16 mask addresses logical slots; indices address physical K/V rows. -+ // Each valid index must be in [0, k->ne[1]); padding beyond lengths is -1. -+ // K/V sequence dimensions may be 1 (shared pool) or match Q. -+ GGML_API struct ggml_tensor * ggml_flash_attn_ext_indexed( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, -+ struct ggml_tensor * k, -+ struct ggml_tensor * v, -+ struct ggml_tensor * mask, -+ struct ggml_tensor * indices, -+ struct ggml_tensor * lengths, -+ float scale, -+ float max_bias, -+ float logit_softcap); -+ - GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec), -diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp -index 679d5216d..bc0407094 100644 ---- a/ggml/src/ggml-backend-meta.cpp -+++ b/ggml/src/ggml-backend-meta.cpp -@@ -153,6 +153,11 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type( - - static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { - GGML_ASSERT(ggml_backend_dev_is_meta(dev)); -+ // The split-state planner does not yet partition/broadcast logical row -+ // tables alongside head-sharded attention inputs. -+ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { -+ return false; -+ } - const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; - return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), - [op](ggml_backend_dev_t simple_dev) { return ggml_backend_dev_supports_op(simple_dev, op); }); -diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp -index 28e17f3f7..b6e2d7d5e 100644 ---- a/ggml/src/ggml-cann/ggml-cann.cpp -+++ b/ggml/src/ggml-cann/ggml-cann.cpp -@@ -2664,6 +2664,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten - return true; - case GGML_OP_FLASH_ATTN_EXT: - { -+ if (op->src[5]) { -+ return false; -+ } - #ifdef ASCEND_310P - // FA not support on 310p device - return false; -diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt -index d347757e1..d817dca43 100644 ---- a/ggml/src/ggml-cpu/CMakeLists.txt -+++ b/ggml/src/ggml-cpu/CMakeLists.txt -@@ -56,6 +56,8 @@ function(ggml_add_cpu_backend_variant_impl tag_name) - ggml-cpu/vec.cpp - ggml-cpu/ops.h - ggml-cpu/ops.cpp -+ ggml-cpu/attention-indexed.cpp -+ ggml-cpu/attention-indexed.h - ) - - target_compile_features(${GGML_CPU_NAME} PRIVATE c_std_11 cxx_std_17) -diff --git a/ggml/src/ggml-cpu/attention-indexed.cpp b/ggml/src/ggml-cpu/attention-indexed.cpp -new file mode 100644 -index 000000000..0f62a5185 ---- /dev/null -+++ b/ggml/src/ggml-cpu/attention-indexed.cpp -@@ -0,0 +1,121 @@ -+#include "attention-indexed.h" -+ -+#include "ggml-cpu.h" -+#include "ggml-cpu-impl.h" -+#include "ggml-impl.h" -+#include "vec.h" -+ -+#include -+#include -+#include -+#include -+ -+// CPU reference for the existing attention op's optional logical read tables. -+// K/V remain in their shared physical storage; only row addresses are indirect. -+void ggml_compute_forward_flash_attn_indexed( -+ const ggml_compute_params * params, ggml_tensor * dst) { -+ const auto * q = dst->src[0]; -+ const auto * k = dst->src[1]; -+ const auto * v = dst->src[2]; -+ const auto * mask = dst->src[3]; -+ const auto * sinks = dst->src[4]; -+ const auto * indices = dst->src[5]; -+ const auto * lengths = dst->src[6]; -+ const int64_t dk = q->ne[0]; -+ const int64_t dv = v->ne[0]; -+ const auto * kt = ggml_get_type_traits_cpu(k->type); -+ const auto * qt = ggml_get_type_traits_cpu(kt->vec_dot_type); -+ const auto * vt = ggml_get_type_traits(v->type); -+ GGML_ASSERT(q->type == GGML_TYPE_F32 && kt->vec_dot && qt->from_float); -+ GGML_ASSERT(v->type == GGML_TYPE_F32 || vt->to_float); -+ -+ float scale, max_bias, softcap; -+ memcpy(&scale, dst->op_params, sizeof(float)); -+ memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); -+ memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(float)); -+ if (softcap != 0.0f) { -+ scale /= softcap; -+ } -+ const uint32_t head_power = 1u << (uint32_t) std::floor(std::log2(q->ne[2])); -+ const float m0 = std::pow(2.0f, -max_bias / head_power); -+ const float m1 = std::pow(2.0f, -(max_bias / 2.0f) / head_power); -+ std::vector converted_q(dk); -+ std::vector converted_v(dv); -+ std::vector accum(dv); -+ -+ const int64_t rows = q->ne[1] * q->ne[2] * q->ne[3]; -+ for (int64_t row = params->ith; row < rows; row += params->nth) { -+ const int64_t request = row / (q->ne[1] * q->ne[2]); -+ const int64_t head = (row / q->ne[1]) % q->ne[2]; -+ const int64_t query = row % q->ne[1]; -+ const auto * ids = (const int32_t *) ((const char *) indices->data + -+ (query % indices->ne[1]) * indices->nb[1] + -+ (head % indices->ne[2]) * indices->nb[2] + -+ (request % indices->ne[3]) * indices->nb[3]); -+ const int32_t count = *(const int32_t *) ((const char *) lengths->data + -+ (query % lengths->ne[1]) * lengths->nb[1] + -+ (head % lengths->ne[2]) * lengths->nb[2] + -+ (request % lengths->ne[3]) * lengths->nb[3]); -+ GGML_ASSERT(count >= 0 && count <= indices->ne[0]); -+ const auto * pm = mask ? (const ggml_fp16_t *) ((const char *) mask->data + -+ query * mask->nb[1] + (head % mask->ne[2]) * mask->nb[2] + -+ (request % mask->ne[3]) * mask->nb[3]) : nullptr; -+ const auto * pq = (const float *) ((const char *) q->data + query * q->nb[1] + -+ head * q->nb[2] + request * q->nb[3]); -+ qt->from_float(pq, converted_q.data(), dk); -+ const float slope = max_bias > 0 ? (head < head_power ? -+ std::pow(m0, head + 1) : std::pow(m1, 2 * (head - head_power) + 1)) : 1.0f; -+ const size_t k_offset = (head / (q->ne[2] / k->ne[2])) * k->nb[2] + -+ (request / (q->ne[3] / k->ne[3])) * k->nb[3]; -+ const size_t v_offset = (head / (q->ne[2] / v->ne[2])) * v->nb[2] + -+ (request / (q->ne[3] / v->ne[3])) * v->nb[3]; -+ std::fill(accum.begin(), accum.end(), 0.0f); -+ float maximum = -INFINITY; -+ float sum = 0.0f; -+ for (int32_t slot = 0; slot < count; ++slot) { -+ const int32_t physical = ids[slot]; -+ GGML_ASSERT(physical >= 0 && physical < k->ne[1] && physical < v->ne[1]); -+ const float bias = pm ? slope * GGML_FP16_TO_FP32(pm[slot]) : 0.0f; -+ if (bias == -INFINITY) { -+ continue; -+ } -+ float score; -+ const char * pk = (const char *) k->data + physical * k->nb[1] + k_offset; -+ kt->vec_dot(dk, &score, 0, pk, 0, converted_q.data(), 0, 1); -+ score *= scale; -+ if (softcap != 0) { -+ score = softcap * std::tanh(score); -+ } -+ score += bias; -+ const float next_max = std::max(maximum, score); -+ const float old_scale = std::exp(maximum - next_max); -+ const float weight = std::exp(score - next_max); -+ const char * pv = (const char *) v->data + physical * v->nb[1] + v_offset; -+ const float * values = (const float *) pv; -+ if (v->type != GGML_TYPE_F32) { -+ vt->to_float(pv, converted_v.data(), dv); -+ values = converted_v.data(); -+ } -+ for (int64_t d = 0; d < dv; ++d) { -+ accum[d] = accum[d] * old_scale + values[d] * weight; -+ } -+ sum = sum * old_scale + weight; -+ maximum = next_max; -+ } -+ if (sinks && count > 0) { -+ const float sink = ((const float *) sinks->data)[head]; -+ const float next_max = std::max(maximum, sink); -+ const float old_scale = std::exp(maximum - next_max); -+ for (float & value : accum) { -+ value *= old_scale; -+ } -+ sum = sum * old_scale + std::exp(sink - next_max); -+ } -+ const float inverse = sum > 0 ? 1.0f / sum : 0.0f; -+ auto * output = (float *) ((char *) dst->data + query * dst->nb[2] + -+ head * dst->nb[1] + request * dst->nb[3]); -+ for (int64_t d = 0; d < dv; ++d) { -+ output[d] = accum[d] * inverse; -+ } -+ } -+} -diff --git a/ggml/src/ggml-cpu/attention-indexed.h b/ggml/src/ggml-cpu/attention-indexed.h -new file mode 100644 -index 000000000..675c343d5 ---- /dev/null -+++ b/ggml/src/ggml-cpu/attention-indexed.h -@@ -0,0 +1,7 @@ -+#pragma once -+ -+struct ggml_compute_params; -+struct ggml_tensor; -+ -+void ggml_compute_forward_flash_attn_indexed( -+ const ggml_compute_params * params, ggml_tensor * dst); -diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp -index 7a73e138e..6dacbd226 100644 ---- a/ggml/src/ggml-cpu/ops.cpp -+++ b/ggml/src/ggml-cpu/ops.cpp -@@ -1,4 +1,5 @@ - #include "ops.h" -+#include "attention-indexed.h" - - #include "ggml-cpu.h" - #include "ggml-impl.h" -@@ -9654,6 +9655,10 @@ static void ggml_compute_forward_flash_attn_ext_f16( - void ggml_compute_forward_flash_attn_ext( - const ggml_compute_params * params, - ggml_tensor * dst) { -+ if (dst->src[5]) { -+ ggml_compute_forward_flash_attn_indexed(params, dst); -+ return; -+ } - switch (dst->op_params[3]) { - case GGML_PREC_DEFAULT: - case GGML_PREC_F32: -diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp -index 81e86b9dd..294d75a23 100644 ---- a/ggml/src/ggml-cpu/spacemit/ime.cpp -+++ b/ggml/src/ggml-cpu/spacemit/ime.cpp -@@ -1626,6 +1626,9 @@ class extra_buffer_type : ggml::cpu::extra_buffer_type { - } - - ggml::cpu::tensor_traits * get_tensor_traits(const ggml_tensor * op) override { -+ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { -+ return nullptr; -+ } - switch (op->op) { - case GGML_OP_MUL_MAT: - case GGML_OP_MUL_MAT_ID: -diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh -index fea1cf9c4..bb8aba163 100644 ---- a/ggml/src/ggml-cuda/common.cuh -+++ b/ggml/src/ggml-cuda/common.cuh -@@ -1282,6 +1282,7 @@ struct ggml_cuda_graph { - struct node_properties { - ggml_tensor node; - void * node_src_data_ptrs[GGML_MAX_SRC]; -+ ggml_type node_src_types[GGML_MAX_SRC]; - int64_t node_src_ne[GGML_MAX_SRC][GGML_MAX_DIMS]; - size_t node_src_nb[GGML_MAX_SRC][GGML_MAX_DIMS]; - }; -diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh -index 41d948335..dd38e078e 100644 ---- a/ggml/src/ggml-cuda/fattn-common.cuh -+++ b/ggml/src/ggml-cuda/fattn-common.cuh -@@ -3,6 +3,7 @@ - #include "common.cuh" - #include "convert.cuh" - #include "vecdotq.cuh" -+#include "fattn-indexed.cuh" - - #include - -@@ -18,6 +19,19 @@ - // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . - #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) - -+// Optional request-local logical-to-physical rows. The dense/null descriptor -+// retains the original FA path; indexed metadata never selects sparse mask scan. -+struct ggml_cuda_fattn_indexed { -+ const int32_t * indices = nullptr; -+ const int32_t * lengths = nullptr; -+ int32_t physical_rows = 0; -+ int32_t sequences = 0; -+ int64_t index_stride = 0; -+ int64_t length_stride = 0; -+ ggml_type type_K = GGML_TYPE_F16; -+ ggml_type type_V = GGML_TYPE_F16; -+}; -+ - typedef void (* fattn_kernel_t)( - const char * __restrict__ Q, - const char * __restrict__ K, -@@ -39,7 +53,8 @@ typedef void (* fattn_kernel_t)( - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, - const int32_t ne31, const int32_t ne32, const int32_t ne33, -- const int32_t nb31, const int32_t nb32, const int64_t nb33); -+ const int32_t nb31, const int32_t nb32, const int64_t nb33, -+ const ggml_cuda_fattn_indexed indexed); - - typedef float (*vec_dot_KQ_t)( - const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); -@@ -737,7 +752,8 @@ static __global__ void flash_attn_stream_k_fixup_uniform( - const int blocks_per_tile, - const uint3 fd_iter_j_z_ne12, - const uint3 fd_iter_j_z, -- const uint3 fd_iter_j) { -+ const uint3 fd_iter_j, -+ const ggml_cuda_fattn_indexed indexed) { - constexpr int ncols = ncols1*ncols2; - ggml_cuda_pdl_lc(); - float * GGML_CUDA_RESTRICT dst = dst_ptr; -@@ -805,7 +821,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform( - } - - // Write back final result: -- *dst = dst_val / rowsum; -+ *dst = indexed.indices && rowsum == 0.0f ? 0.0f : dst_val / rowsum; - } - - // General fixup kernel for the case where the number of blocks per tile is not uniform across tiles -@@ -821,7 +837,8 @@ static __global__ void flash_attn_stream_k_fixup_general( - const uint3 fd_iter_k_j_z_ne12, - const uint3 fd_iter_k_j_z, - const uint3 fd_iter_k_j, -- const uint3 fd_iter_k) { -+ const uint3 fd_iter_k, -+ const ggml_cuda_fattn_indexed indexed) { - float * GGML_CUDA_RESTRICT dst = dst_ptr; - const float2 * GGML_CUDA_RESTRICT dst_fixup = dst_fixup_ptr; - constexpr int ncols = ncols1*ncols2; -@@ -916,7 +933,7 @@ static __global__ void flash_attn_stream_k_fixup_general( - } - - // Write back final result: -- *dst = dst_val / rowsum; -+ *dst = indexed.indices && rowsum == 0.0f ? 0.0f : dst_val / rowsum; - } - - template // D == head size -@@ -925,7 +942,8 @@ static __global__ void flash_attn_combine_results( - const float * VKQ_parts_ptr, - const float2 * VKQ_meta_ptr, - float * dst_ptr, -- const int parallel_blocks) { -+ const int parallel_blocks, -+ const ggml_cuda_fattn_indexed indexed) { - ggml_cuda_pdl_lc(); - const float * GGML_CUDA_RESTRICT VKQ_parts = VKQ_parts_ptr; - const float2 * GGML_CUDA_RESTRICT VKQ_meta = VKQ_meta_ptr; -@@ -974,7 +992,7 @@ static __global__ void flash_attn_combine_results( - VKQ_denominator += KQ_max_scale * meta[l].y; - } - -- dst[tid] = VKQ_numerator / VKQ_denominator; -+ dst[tid] = indexed.indices && VKQ_denominator == 0.0f ? 0.0f : VKQ_numerator / VKQ_denominator; - } - - template -@@ -993,6 +1011,21 @@ void launch_fattn( - - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; -+ const ggml_tensor * row_indices = dst->src[5]; -+ const ggml_tensor * row_lengths = dst->src[6]; -+ ggml_cuda_fattn_indexed indexed; -+ if (row_indices) { -+ GGML_ASSERT(row_lengths && !use_sparse); -+ GGML_ASSERT(row_indices->ne[1] == 1 && row_indices->ne[2] == 1); -+ indexed.indices = (const int32_t *) row_indices->data; -+ indexed.lengths = (const int32_t *) row_lengths->data; -+ indexed.physical_rows = K->ne[1]; -+ indexed.type_K = K->type; -+ indexed.type_V = V->type; -+ indexed.sequences = row_indices->ne[3]; -+ indexed.index_stride = row_indices->nb[3] / sizeof(int32_t); -+ indexed.length_stride = row_lengths->nb[3] / sizeof(int32_t); -+ } - - ggml_tensor * KQV = dst; - -@@ -1012,7 +1045,7 @@ void launch_fattn( - const int nsm = ggml_cuda_info().devices[id].nsm; - - const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra = -- ggml_cuda_flash_attn_ext_get_f16_extra_data(KQV, need_f16_K, need_f16_V); -+ ggml_cuda_flash_attn_ext_get_f16_extra_data(KQV, need_f16_K && !row_indices, need_f16_V && !row_indices); - - ggml_cuda_pool_alloc KV_max(pool); - ggml_cuda_pool_alloc dst_tmp(pool); -@@ -1028,7 +1061,7 @@ void launch_fattn( - size_t nb22 = V->nb[2]; - size_t nb23 = V->nb[3]; - -- if (need_f16_K && K->type != GGML_TYPE_F16) { -+ if (!row_indices && need_f16_K && K->type != GGML_TYPE_F16) { - const size_t bs = ggml_blck_size(K->type); - const size_t ts = ggml_type_size(K->type); - -@@ -1056,7 +1089,7 @@ void launch_fattn( - K_data = (char *) K_f16; - } - -- if (need_f16_V && V->type != GGML_TYPE_F16) { -+ if (!row_indices && need_f16_V && V->type != GGML_TYPE_F16) { - if (V_is_K_view) { - V_data = K_data; - nb21 = nb11; -@@ -1114,7 +1147,7 @@ void launch_fattn( - // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. - // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or - // multiple sequences of possibly different lengths. -- const bool scan_mask = !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); -+ const bool scan_mask = !row_indices && !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); - if (scan_mask) { - const int64_t s31 = mask->nb[1] / sizeof(half2); - const int64_t s33 = mask->nb[3] / sizeof(half2); -@@ -1138,7 +1171,7 @@ void launch_fattn( - GGML_ASSERT(max_blocks_per_sm > 0); - int parallel_blocks = max_blocks_per_sm; - -- const int64_t n_kv = use_sparse ? n_kv_max : K->ne[1]; -+ const int64_t n_kv = row_indices ? row_indices->ne[0] : (use_sparse ? n_kv_max : K->ne[1]); - const int ntiles_KV = (n_kv + nbatch_fa - 1) / nbatch_fa; // Max. number of parallel blocks limited by KV cache length. - - dim3 blocks_num; -@@ -1261,7 +1294,8 @@ void launch_fattn( - K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, - nb21, nb22, nb23, - mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, -- mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 -+ mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0, -+ indexed - ); - CUDA_CHECK(cudaGetLastError()); - -@@ -1282,7 +1316,7 @@ void launch_fattn( - ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_uniform, launch_params, - (float *) KQV->data, dst_tmp_meta.ptr, - Q->ne[1], Q->ne[2], K->ne[2], nblocks_sk, -- gqa_ratio, bpt, fd0, fd1, fd2); -+ gqa_ratio, bpt, fd0, fd1, fd2, indexed); - } else if (ntiles_dst % blocks_num.x != 0) { - // General fixup for the cases where nblocks_stream_k < ntiles_dst. - const int total_work = ntiles_KV * ntiles_dst; -@@ -1299,7 +1333,7 @@ void launch_fattn( - ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_general, launch_params, - (float *) KQV->data, dst_tmp_meta.ptr, - Q->ne[1], Q->ne[2], gqa_ratio, total_work, -- fd_k_j_z_ne12, fd_k_j_z, fd_k_j, fd_k); -+ fd_k_j_z_ne12, fd_k_j_z, fd_k_j, fd_k, indexed); - } - } else if (parallel_blocks > 1) { - const dim3 block_dim_combine(DV, 1, 1); -@@ -1308,7 +1342,7 @@ void launch_fattn( - - const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream); - ggml_cuda_kernel_launch(flash_attn_combine_results, launch_params, -- dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks); -+ dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks, indexed); - } - CUDA_CHECK(cudaGetLastError()); - } -diff --git a/ggml/src/ggml-cuda/fattn-indexed.cuh b/ggml/src/ggml-cuda/fattn-indexed.cuh -new file mode 100644 -index 000000000..c1d2fafdc ---- /dev/null -+++ b/ggml/src/ggml-cuda/fattn-indexed.cuh -@@ -0,0 +1,45 @@ -+#pragma once -+ -+#include "dequantize.cuh" -+ -+// A physical head view. Quantized row strides are byte strides (not half2 -+// strides: e.g. a 96-element Q4_0 row occupies 54 bytes). -+struct ggml_cuda_fattn_row { -+ const char * data = nullptr; -+ int64_t stride = 0; -+ ggml_type type = GGML_TYPE_F16; -+}; -+ -+static __device__ __forceinline__ half ggml_cuda_fattn_read_half( -+ const ggml_cuda_fattn_row row, const int physical, const int element) { -+ const char * src = row.data + int64_t(physical)*row.stride; -+ if (row.type == GGML_TYPE_F16) { -+ return ((const half *) src)[element]; -+ } -+ if (row.type == GGML_TYPE_F32) { -+ return __float2half(((const float *) src)[element]); -+ } -+ if (row.type == GGML_TYPE_BF16) { -+ const uint32_t bits = uint32_t(((const uint16_t *) src)[element]) << 16; -+ return __float2half(__uint_as_float(bits)); -+ } -+ float2 value; -+ const int block = element / 32; -+ const int offset = element % 32; -+ switch (row.type) { -+ case GGML_TYPE_Q4_0: dequantize_q4_0(src, block, offset % 16, value); break; -+ case GGML_TYPE_Q4_1: dequantize_q4_1(src, block, offset % 16, value); break; -+ case GGML_TYPE_Q5_0: dequantize_q5_0(src, block, offset % 16, value); break; -+ case GGML_TYPE_Q5_1: dequantize_q5_1(src, block, offset % 16, value); break; -+ case GGML_TYPE_Q8_0: dequantize_q8_0(src, block, offset & ~1, value); break; -+ default: return __float2half(0.0f); // Rejected by host admission. -+ } -+ return __float2half(row.type == GGML_TYPE_Q8_0 ? -+ (offset & 1 ? value.y : value.x) : (offset >= 16 ? value.y : value.x)); -+} -+ -+static __device__ __forceinline__ half2 ggml_cuda_fattn_read_half2( -+ const ggml_cuda_fattn_row row, const int physical, const int element) { -+ return __halves2half2(ggml_cuda_fattn_read_half(row, physical, element), -+ ggml_cuda_fattn_read_half(row, physical, element + 1)); -+} -diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh -index 296aa2b34..a12a21093 100644 ---- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh -+++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh -@@ -383,7 +383,25 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages( - template - static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV, -- const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { -+ const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices, -+ const int physical_rows, const ggml_cuda_fattn_row row = {}) { -+ // Decode only the selected physical rows into the original MMA shared tile. -+ // The F16 branch below retains its original vectorized/cp.async loads. -+ if (row.data && row.type != GGML_TYPE_F16) { -+ const int element0 = int(((const char *) KV - row.data) / sizeof(half)); -+ constexpr int warp_size = ggml_cuda_get_physical_warp_size(); -+ const int tid = threadIdx.y*warp_size + threadIdx.x; -+ for (int x = tid; x < nbatch_fa*D2; x += nwarps*warp_size) { -+ const int i = x / D2; -+ const int k = x % D2; -+ const int logical = k_VKQ_0 + i; -+ const int physical = i < i_sup ? (indices ? indices[logical] : logical) : -1; -+ const half2 value = physical >= 0 && physical < physical_rows ? -+ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*k) : make_half2(0.0f, 0.0f); -+ *swizzle(tile_KV, i*stride_tile + k, i) = value; -+ } -+ return; -+ } - constexpr int warp_size = ggml_cuda_get_physical_warp_size(); - // K/V data is loaded with decreasing granularity for D for better memory bandwidth. - // The minimum granularity is 16 bytes. -@@ -420,6 +438,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - // padded slots gather row 0, the -inf mask removes their contribution - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; - i_KV = index >= 0 ? index : 0; -+ } else if (indices) { -+ const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; -+ i_KV = index >= 0 && index < physical_rows ? index : -1; - } else { - i_KV = k_VKQ_0 + i; - } -@@ -428,7 +449,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { - const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); - -- cp_async_cg_16(tile_KV_32 + swizzle(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk); -+ if (i_KV >= 0) { -+ cp_async_cg_16(tile_KV_32 + swizzle(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk); -+ } else { -+ auto * target = swizzle(tile_KV, i*stride_tile + k*h2_per_chunk, i); -+ *reinterpret_cast(target) = make_uint4(0, 0, 0, 0); -+ } - } - } - }; -@@ -467,6 +493,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - if constexpr (use_sparse) { - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; - src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; -+ } else if (indices) { -+ const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; -+ src = index >= 0 && index < physical_rows ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; - } else { - src = !oob_check || i < i_sup ? KV + int64_t(k_VKQ_0 + i)*stride_KV + k*h2_per_chunk : zero; - } -@@ -600,7 +629,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - float * const __restrict__ KQ_rowsum, - const int jt, - const int kb0, -- const int k_VKQ_sup) { -+ const int k_VKQ_sup, -+ const int physical_rows, -+ const int logical_rows, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V) { - #if defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) - constexpr int warp_size = ggml_cuda_get_physical_warp_size(); - constexpr int ncols = ncols1 * ncols2; -@@ -634,7 +665,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - cp_async_wait_all(); - __syncthreads(); - flash_attn_ext_f16_load_tile -- (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, nullptr); -+ (V_h2, tile_V, nbatch_V2, stride_V, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_V); - } else { - // the sparse mask values are gathered per element, always load them synchronously - constexpr bool use_cp_async = nstages == 1 && !use_sparse; -@@ -654,7 +685,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - const int k0_diff = k0_stop - k0_start; - constexpr bool use_cp_async = nstages == 1; - flash_attn_ext_f16_load_tile -- (K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices); -+ (K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_K); - if (use_cp_async) { - cp_async_wait_all(); - } -@@ -991,7 +1022,9 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - (mask_h, tile_mask, stride_mask, k_VKQ_0 + nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); - } - flash_attn_ext_f16_load_tile -- (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, k_VKQ_sup, nullptr); -+ (K_h2, tile_K, nbatch_K2, stride_K, k_VKQ_0 + nbatch_fa, -+ indices && !use_sparse ? min(nbatch_fa, max(0, logical_rows - k_VKQ_0 - nbatch_fa)) : k_VKQ_sup, -+ indices, physical_rows, row_K); - } - } - -@@ -1007,7 +1040,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - if (!V_is_K_view || i0_stop > 2*nbatch_K2) { - constexpr bool use_cp_async = nstages == 1; - flash_attn_ext_f16_load_tile -- (V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices); -+ (V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices, physical_rows, row_V); - if (use_cp_async) { - cp_async_wait_all(); - } -@@ -1066,7 +1099,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( - scale, slope, logit_softcap, ne01, ne02, - stride_K, stride_V, stride_mask, - tile_Q, tile_K, tile_V, tile_mask, -- Q_B, VKQ_C, KQ_max, KQ_rowsum, kb0); -+ Q_B, VKQ_C, KQ_max, KQ_rowsum, kb0, physical_rows, logical_rows, row_K, row_V); - NO_DEVICE_CODE; - #endif // defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) - } -@@ -1211,7 +1244,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - const int jt, - const int zt_gqa, - const int kb0_start, -- const int kb0_stop) { -+ const int kb0_stop, -+ const int physical_rows, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V) { - #if defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) - //In this kernel Q, K, V are matrices while i, j, k are matrix indices. - -@@ -1331,62 +1365,66 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - - int kb0 = kb0_start; - -- // Preload mask and K data for first iteration when using cp_async with multiple stages: -- if constexpr (nstages > 1) { -- static_assert(!use_sparse, "sparse gather not implemented for multi-stage loading"); -- static_assert(nbatch_K2 == DKQ/2, "batching not implemented for multi-stage pipeline"); -- constexpr bool use_cp_async = true; -- constexpr bool oob_check = false; -- constexpr int k_VKQ_sup = nbatch_fa; -- if (ncols2 > 1 || mask_h) { -- flash_attn_ext_f16_load_mask -- (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); -+ // Empty request-local intervals still execute the original output/fixup -+ // epilogue, but must not issue an unconditional final K/V iteration. -+ if (kb0_start < kb0_stop) { -+ // Preload mask and K data for first iteration when using cp_async with multiple stages: -+ if constexpr (nstages > 1) { -+ static_assert(!use_sparse, "sparse gather not implemented for multi-stage loading"); -+ static_assert(nbatch_K2 == DKQ/2, "batching not implemented for multi-stage pipeline"); -+ constexpr bool use_cp_async = true; -+ constexpr bool oob_check = false; -+ const int k_VKQ_sup = indices && !use_sparse ? min(nbatch_fa, max(0, ne11 - kb0*nbatch_fa)) : nbatch_fa; -+ if (ncols2 > 1 || mask_h) { -+ flash_attn_ext_f16_load_mask -+ (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); -+ } -+ flash_attn_ext_f16_load_tile -+ (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, indices, physical_rows, row_K); - } -- flash_attn_ext_f16_load_tile -- (K_h2, tile_K, nbatch_K2, stride_K, kb0*nbatch_fa, k_VKQ_sup, nullptr); -- } - -- // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. -- if constexpr (ncols2 == 1 || use_sparse) { -- constexpr bool oob_check = true; -- for (; kb0 < kb0_stop-1; ++kb0) { -- constexpr bool last_iter = false; -- constexpr int k_VKQ_sup = nbatch_fa; -+ // kb0_start is always < kb0_stop so the last iter can be executed unconditionally. -+ if constexpr (ncols2 == 1 || use_sparse) { -+ constexpr bool oob_check = true; -+ for (; kb0 < kb0_stop-1; ++kb0) { -+ constexpr bool last_iter = false; -+ constexpr int k_VKQ_sup = nbatch_fa; -+ flash_attn_ext_f16_iter -+ -+ (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, -+ ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -+ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); -+ } -+ constexpr bool last_iter = true; -+ const int k_VKQ_sup = ne11 - kb0*nbatch_fa; - flash_attn_ext_f16_iter - -+ T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ> - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); -- } -- constexpr bool last_iter = true; -- const int k_VKQ_sup = ne11 - kb0*nbatch_fa; -- flash_attn_ext_f16_iter -- -- (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, -- ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); -- } else { -- constexpr bool oob_check = false; -- for (; kb0 < kb0_stop-1; ++kb0) { -- constexpr bool last_iter = false; -- constexpr int k_VKQ_sup = nbatch_fa; -+ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); -+ } else { -+ constexpr bool oob_check = false; -+ for (; kb0 < kb0_stop-1; ++kb0) { -+ constexpr bool last_iter = false; -+ constexpr int k_VKQ_sup = nbatch_fa; -+ flash_attn_ext_f16_iter -+ -+ (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, -+ ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -+ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); -+ } -+ constexpr bool last_iter = true; -+ const int k_VKQ_sup = indices && !use_sparse ? min(nbatch_fa, max(0, ne11 - kb0*nbatch_fa)) : nbatch_fa; - flash_attn_ext_f16_iter - - (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); -+ KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup, physical_rows, ne11, row_K, row_V); - } -- constexpr bool last_iter = true; -- constexpr int k_VKQ_sup = nbatch_fa; -- flash_attn_ext_f16_iter -- -- (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, -- ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, -- KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); - } - - // With multi-stage loading there is no __syncthreads at the end of the iter, -@@ -1426,7 +1464,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - // If attention sinks are used, potentially re-scale if KQ_max is small. - // Also add the sink as a value to KQ_rowsum, this is done after synchronization of KQ_rowsum - // so it's being done unconditionally for every thread. -- if (!is_fixup && (np == 1 || threadIdx.y % np == 0) && sinks_f) { -+ if (!is_fixup && (np == 1 || threadIdx.y % np == 0) && sinks_f && -+ (physical_rows == INT32_MAX || ne11 != 0)) { - float KQ_max_scale[cols_per_thread]; - #pragma unroll - for (int col = 0; col < cols_per_thread; ++col) { -@@ -1759,8 +1798,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - - if (!needs_fixup && !is_fixup) { - const float KQ_rowsum_j = meta_j[1]; -- dstk_val.x /= KQ_rowsum_j; -- dstk_val.y /= KQ_rowsum_j; -+ if (physical_rows != INT32_MAX && KQ_rowsum_j == 0.0f) { -+ dstk_val = make_float2(0.0f, 0.0f); -+ } else { -+ dstk_val.x /= KQ_rowsum_j; -+ dstk_val.y /= KQ_rowsum_j; -+ } - } - - if (is_fixup) { -@@ -1780,7 +1823,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( - GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dstk_fixup, - scale, slope, logit_softcap, ne01, ne02, gqa_ratio, - stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, -- jt, kb0_start, kb0_stop); -+ jt, kb0_start, kb0_stop, physical_rows, row_K, row_V); - NO_DEVICE_CODE; - #endif // defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE) - } -@@ -1816,7 +1859,8 @@ static __global__ void flash_attn_ext_f16( - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, - const int32_t ne31, const int32_t ne32, const int32_t ne33, -- const int32_t nb31, const int32_t nb32, const int64_t nb33) { -+ const int32_t nb31, const int32_t nb32, const int64_t nb33, -+ const ggml_cuda_fattn_indexed indexed) { - ggml_cuda_pdl_sync(); // TODO optimize placement - #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) - const char * GGML_CUDA_RESTRICT Q = Q_ptr; -@@ -1917,14 +1961,20 @@ static __global__ void flash_attn_ext_f16( - const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. - - const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); -- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); -- const half * mask_h = ncols2 == 1 && !mask ? nullptr : -+ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; -+ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*z_KV); -+ const half * mask_h = !mask ? nullptr : - (const half *) (mask + nb33*(sequence % ne33)); - float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); - -- const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); -+ const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*kv_sequence + nb22*z_KV); -+ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; -+ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; -- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; -+ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; -+ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : -+ (indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr); -+ const int live_n_kv = indexed.indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; - - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; - -@@ -1933,17 +1983,24 @@ static __global__ void flash_attn_ext_f16( - } else if (KV_max) { - kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); - } -+ if (indexed.indices) { -+ kb0_stop = min(kb0_stop, (live_n_kv + nbatch_fa - 1) / nbatch_fa); -+ } - constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. - if (kb0_start == 0) { - constexpr bool needs_fixup = false; // CUDA block is working on an entire tile. - flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, -- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); -+ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, -+ indexed.indices ? indexed.physical_rows : INT32_MAX, -+ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); - } else { - constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile. - flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, -- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); -+ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, -+ indexed.indices ? indexed.physical_rows : INT32_MAX, -+ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); - } - - kbc += iter_k; -@@ -1966,14 +2023,20 @@ static __global__ void flash_attn_ext_f16( - const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. - - const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); -- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); -- const half * mask_h = ncols2 == 1 && !mask ? nullptr : -+ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; -+ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*z_KV); -+ const half * mask_h = !mask ? nullptr : - (const half *) (mask + nb33*(sequence % ne33)); - float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); - -- const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); -+ const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*kv_sequence + nb22*z_KV); -+ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; -+ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; -- const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : nullptr; -+ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; -+ const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : -+ (indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr); -+ const int live_n_kv = indexed.indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; - - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; - -@@ -1982,12 +2045,17 @@ static __global__ void flash_attn_ext_f16( - } else if (KV_max) { - kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); - } -+ if (indexed.indices) { -+ kb0_stop = min(kb0_stop, (live_n_kv + nbatch_fa - 1) / nbatch_fa); -+ } - - constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. - constexpr bool needs_fixup = false; - flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, -- ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); -+ ne01, ne02, gqa_ratio, live_n_kv, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop, -+ indexed.indices ? indexed.physical_rows : INT32_MAX, -+ indexed.indices ? row_K : ggml_cuda_fattn_row{}, indexed.indices ? row_V : ggml_cuda_fattn_row{}); - #else - GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, - max_bias, m0, m1, n_head_log2, logit_softcap, -@@ -1997,7 +2065,7 @@ static __global__ void flash_attn_ext_f16( - nb11, nb12, nb13, - nb21, nb22, nb23, - ne31, ne32, ne33, -- nb31, nb32, nb33); -+ nb31, nb32, nb33, indexed); - NO_DEVICE_CODE; - #endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) - } -diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh -index b5ea915e1..8a1474017 100644 ---- a/ggml/src/ggml-cuda/fattn-tile.cuh -+++ b/ggml/src/ggml-cuda/fattn-tile.cuh -@@ -376,7 +376,23 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, - // TODO: deduplicate with mma-f16 - template - static __device__ __forceinline__ void flash_attn_tile_load_tile( -- const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { -+ const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup, -+ const ggml_cuda_fattn_row row = {}, const int32_t * indices = nullptr, -+ const int logical0 = 0, const int element0 = 0, const int physical_rows = 0) { -+ if (indices) { -+ if constexpr (J >= 2) { -+ const int tid = threadIdx.y*warp_size + threadIdx.x; -+ for (int x = tid; x < I*(J/2); x += nwarps*warp_size) { -+ const int i = x / (J/2); -+ const int j = x % (J/2); -+ const int physical = i < i_sup ? indices[logical0 + i] : -1; -+ const half2 value = physical >= 0 && physical < physical_rows ? -+ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*j) : make_half2(0.0f, 0.0f); -+ tile_KV[i*(J/2 + J_padding) + j] = value; -+ } -+ } -+ return; -+ } - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - -@@ -426,7 +442,25 @@ static __device__ __forceinline__ void flash_attn_tile_load_tile( - - template - static __device__ __forceinline__ void flash_attn_tile_load_tile( -- const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { -+ const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup, -+ const ggml_cuda_fattn_row row = {}, const int32_t * indices = nullptr, -+ const int logical0 = 0, const int element0 = 0, const int physical_rows = 0) { -+ if (indices) { -+ if constexpr (J >= 2) { -+ const int tid = threadIdx.y*warp_size + threadIdx.x; -+ for (int x = tid; x < I*(J/2); x += nwarps*warp_size) { -+ const int i = x / (J/2); -+ const int j = x % (J/2); -+ const int physical = i < i_sup ? indices[logical0 + i] : -1; -+ const half2 value = physical >= 0 && physical < physical_rows ? -+ ggml_cuda_fattn_read_half2(row, physical, element0 + 2*j) : make_half2(0.0f, 0.0f); -+ const float2 f = __half22float2(value); -+ tile_KV[i*(J + J_padding) + 2*j] = f.x; -+ tile_KV[i*(J + J_padding) + 2*j + 1] = f.y; -+ } -+ } -+ return; -+ } - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - -@@ -490,7 +524,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( - const int k_VKQ_0, - const int k_VKQ_sup, - const int k_KQ_0, -- float * KQ_acc) { -+ float * KQ_acc, const ggml_cuda_fattn_row row_K, const int32_t * indices, const int physical_rows) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - -@@ -499,7 +533,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( - constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column - - flash_attn_tile_load_tile -- (K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup); -+ (indices ? K_h2 : K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup, row_K, indices, k_VKQ_0, k_KQ_0, physical_rows); - __syncthreads(); - - #ifdef FAST_FP16_AVAILABLE -@@ -575,7 +609,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter( - T_acc * const VKQ, - const int k_VKQ_0, - const int k_VKQ_max, -- const int col_Q_0) { -+ const int col_Q_0, const ggml_cuda_fattn_row row_K, const ggml_cuda_fattn_row row_V, -+ const int32_t * indices, const int physical_rows) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - -@@ -608,12 +643,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter( - #pragma unroll - for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) { - flash_attn_tile_iter_KQ( -- Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); -+ Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, row_K, indices, physical_rows); - } - if (nbatch_K_last > 0) { - constexpr int k_KQ_0 = DKQ - nbatch_K_last; - flash_attn_tile_iter_KQ( -- Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc); -+ Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, row_K, indices, physical_rows); - } - - // Apply logit softcap + mask, update KQ_max: -@@ -719,7 +754,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( - #pragma unroll - for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { - flash_attn_tile_load_tile -- (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); -+ (indices ? V_h2 : V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0, row_V, indices, k_VKQ_0 + k0, 0, physical_rows); - __syncthreads(); - - #ifdef FAST_FP16_AVAILABLE -@@ -811,7 +846,9 @@ static __global__ void flash_attn_tile( - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, - const int32_t ne31, const int32_t ne32, const int32_t ne33, -- const int32_t nb31, const int32_t nb32, const int64_t nb33) { -+ const int32_t nb31, const int32_t nb32, const int64_t nb33, -+ const ggml_cuda_fattn_indexed indexed) { -+ - #ifdef FLASH_ATTN_AVAILABLE - const char * GGML_CUDA_RESTRICT Q = Q_ptr; - const char * GGML_CUDA_RESTRICT K = K_ptr; -@@ -833,7 +870,7 @@ static __global__ void flash_attn_tile( - nb11, nb12, nb13, - nb21, nb22, nb23, - ne31, ne32, ne33, -- nb31, nb32, nb33); -+ nb31, nb32, nb33, indexed); - NO_DEVICE_CODE; - return; - } -@@ -854,11 +891,17 @@ static __global__ void flash_attn_tile( - const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) - const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. - const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); -- const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio)); -- const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape -+ const int kv_sequence = indexed.indices ? sequence % ne13 : sequence; -+ const half2 * K_h2 = (const half2 *) (K + nb13*kv_sequence + nb12*(head0 / gqa_ratio)); -+ const half2 * V_h2 = (const half2 *) (V + nb23*kv_sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape - - const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33)) : nullptr; - -+ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; -+ const int32_t * indices = indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr; -+ const int live_n_kv = indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; -+ const ggml_cuda_fattn_row row_K{(const char *) K_h2, nb11, indexed.type_K}; -+ const ggml_cuda_fattn_row row_V{(const char *) V_h2, nb21, indexed.type_V}; - const int stride_K2 = nb11 / sizeof(half2); - const int stride_V2 = nb21 / sizeof(half2); - const int stride_mask = nb31 / sizeof(half); -@@ -951,22 +994,22 @@ static __global__ void flash_attn_tile( - __syncthreads(); - - // Main loop over KV cache: -- const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; -- if (ncols2 == 1) { -+ const int k_VKQ_max = indices ? live_n_kv : (KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11); -+ if (ncols2 == 1 || indices) { - // Branch with out-of-bounds checks. - int k_VKQ_0 = blockIdx.y*nbatch_fa; - while (k_VKQ_0 < k_VKQ_max - nbatch_fa) { - constexpr bool oob_check = false; - flash_attn_tile_iter - (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, -- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); -+ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); - k_VKQ_0 += gridDim.y*nbatch_fa; - } - if (k_VKQ_0 < k_VKQ_max) { - constexpr bool oob_check = true; - flash_attn_tile_iter - (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, -- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); -+ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); - } - } else { - // Branch without out-of-bounds checks. -@@ -974,7 +1017,7 @@ static __global__ void flash_attn_tile( - constexpr bool oob_check = false; - flash_attn_tile_iter - (Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, -- stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0); -+ stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, row_K, row_V, indices, indexed.physical_rows); - } - } - -@@ -1050,7 +1093,7 @@ static __global__ void flash_attn_tile( - } - - // Attention sink: adjust KQ max and sum only for the first of all parallel blocks: -- if (sinks && blockIdx.y == 0) { -+ if (sinks && blockIdx.y == 0 && (!indices || live_n_kv != 0)) { - #pragma unroll - for (int jc0 = 0; jc0 < cpw; ++jc0) { - const int jc = jc0 + (threadIdx.y/np)*cpw; -@@ -1091,7 +1134,7 @@ static __global__ void flash_attn_tile( - return; - } - -- const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f; -+ const float scale = indices && KQ_sum[jc0] == 0.0f ? 0.0f : (gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f); - - const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y; - -@@ -1140,7 +1183,7 @@ static __global__ void flash_attn_tile( - nb11, nb12, nb13, - nb21, nb22, nb23, - ne31, ne32, ne33, -- nb31, nb32, nb33); -+ nb31, nb32, nb33, indexed); - NO_DEVICE_CODE; - #endif // FLASH_ATTN_AVAILABLE - } -@@ -1221,7 +1264,9 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm - } - - if constexpr (ncols2 <= 2) { -- constexpr int cols_per_block = 2; -+ // The wide indexed nonalias path has a valid four-column config, -+ // including when only one request query is live. -+ constexpr int cols_per_block = DKQ == 576 ? 4 : 2; - const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; - const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; -@@ -1250,7 +1295,7 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm - // However, for DKQ == 576, DV == 512 only the kernel variant with GQA optimizations is implemented. - const bool nvidia = GGML_CUDA_CC_IS_NVIDIA(ggml_cuda_info().devices[ggml_cuda_get_device()].cc); - const int gqa_limit = nvidia && gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX; -- const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; - - if constexpr (DKQ == 320) { - // This branch is only used for Mistral Small 4 which has a GQA ratio of 32. -@@ -1272,6 +1317,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm - } - - if constexpr (DKQ == 576) { -+ if (dst->src[5]) { -+ // Independent V pools cannot use the MLA K-tile alias. Group one -+ // head at a time so every admitted GQA ratio (including two) works. -+ launch_fattn_tile_switch_ncols1(ctx, dst); -+ return; -+ } - if (use_gqa_opt && gqa_ratio % 16 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); - return; -diff --git a/ggml/src/ggml-cuda/fattn-vec-dense.cuh b/ggml/src/ggml-cuda/fattn-vec-dense.cuh -new file mode 100644 -index 000000000..a84a35900 ---- /dev/null -+++ b/ggml/src/ggml-cuda/fattn-vec-dense.cuh -@@ -0,0 +1,511 @@ -+// Preserve the ordinary VEC arithmetic and resource usage independently of -+// indexed row loading. Only the unused common launch descriptor is appended. -+template // D == head size -+__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) -+static __global__ void flash_attn_ext_vec( -+ const char * Q_ptr, -+ const char * K_ptr, -+ const char * V_ptr, -+ const char * mask_ptr, -+ const char * sinks_ptr, -+ const int * KV_max_ptr, -+ float * dst_ptr, -+ float2 * dst_meta_ptr, -+ const float scale, -+ const float max_bias, -+ const float m0, -+ const float m1, -+ const uint32_t n_head_log2, -+ const float logit_softcap, -+ const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, -+ const int32_t nb01, const int32_t nb02, const int32_t nb03, -+ const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, -+ const int32_t nb11, const int32_t nb12, const int64_t nb13, -+ const int32_t nb21, const int32_t nb22, const int64_t nb23, -+ const int32_t ne31, const int32_t ne32, const int32_t ne33, -+ const int32_t nb31, const int32_t nb32, const int64_t nb33, -+ const ggml_cuda_fattn_indexed /* unused */) { -+ ggml_cuda_pdl_lc(); -+#ifdef FLASH_ATTN_AVAILABLE -+ const char * GGML_CUDA_RESTRICT Q = Q_ptr; -+ const char * GGML_CUDA_RESTRICT K = K_ptr; -+ const char * GGML_CUDA_RESTRICT V = V_ptr; -+ const char * GGML_CUDA_RESTRICT mask = mask_ptr; -+ const char * GGML_CUDA_RESTRICT sinks = sinks_ptr; -+ const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; -+ float * GGML_CUDA_RESTRICT dst = dst_ptr; -+ float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; -+ -+ // Skip unused kernel variants for faster compilation: -+ if (use_logit_softcap && !(D == 128 || D == 256)) { -+ GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale, -+ max_bias, m0, m1, n_head_log2, logit_softcap, -+ ne00, ne01, ne02, ne03, -+ nb01, nb02, nb03, -+ ne10, ne11, ne12, ne13, -+ nb11, nb12, nb13, -+ nb21, nb22, nb23, -+ ne31, ne32, ne33, -+ nb31, nb32, nb33); -+ NO_DEVICE_CODE; -+ return; -+ } -+ -+ //In this kernel Q, K, V are matrices while i, j, k are matrix indices. -+ -+ constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); -+ constexpr int cpy_ne = cpy_nb / 4; -+ -+#ifdef GGML_USE_HIP -+#ifdef RDNA -+ constexpr int nthreads_KQ_q = 2; -+#else -+ constexpr int nthreads_KQ_q = 4; -+#endif // RDNA -+ constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32); -+#else -+ constexpr int nthreads_KQ_q = (D/4 < 32 ? D/4 : 32); -+ constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32); -+#endif // GGML_USE_HIP -+ -+ constexpr int nthreads = ggml_cuda_fattn_vec_get_nthreads_device(); -+ constexpr int nthreads_KQ = (type_K == GGML_TYPE_F16 || type_K == GGML_TYPE_BF16) ? 128 / cpy_nb : nthreads_KQ_q; -+ constexpr int nthreads_V = (type_V == GGML_TYPE_F16 || type_V == GGML_TYPE_BF16) ? 128 / cpy_nb : nthreads_V_q; -+ -+ static_assert(WARP_SIZE % nthreads_KQ == 0, "bad nthreads_K"); -+ static_assert(WARP_SIZE % nthreads_V == 0, "bad nthreads_V"); -+ -+ constexpr int V_rows_per_thread = (type_V == GGML_TYPE_F16 || type_V == GGML_TYPE_BF16) ? 2*cpy_ne : 4; -+ constexpr int V_cols_per_iter = WARP_SIZE / nthreads_V; -+ -+ constexpr vec_dot_KQ_t vec_dot_KQ = get_vec_dot_KQ(); -+ constexpr bool Q_q8_1 = type_K != GGML_TYPE_F16 && type_K != GGML_TYPE_BF16; -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ constexpr dequantize_V_t dequantize_V = get_dequantize_V(); -+#else -+ constexpr dequantize_V_t dequantize_V = get_dequantize_V(); -+#endif // V_DOT2_F32_F16_AVAILABLE -+ -+ const int ic0 = blockIdx.x * ncols; // Index of the Q/QKV column to work on. -+ -+ const int sequence = blockIdx.z / ne02; -+ const int head = blockIdx.z - sequence*ne02; -+ const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. -+ Q += nb03*sequence + nb02* head + nb01*ic0; -+ K += nb13*sequence + nb12*(head / gqa_ratio); -+ V += nb23*sequence + nb22*(head / gqa_ratio); -+ -+ const half * maskh = (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0); -+ -+ const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); -+ -+ static_assert(D % (2*WARP_SIZE) == 0, "D not divisible by 2*WARP_SIZE == 64."); -+ constexpr int nwarps = nthreads / WARP_SIZE; -+ const int tid = WARP_SIZE*threadIdx.y + threadIdx.x; -+ __builtin_assume(tid < nthreads); -+ -+ constexpr int ne_KQ = ncols*D; -+ constexpr int ne_combine = nwarps*V_cols_per_iter*D; -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ half2 VKQ[ncols][(D/2)/nthreads_V] = {{{0.0f, 0.0f}}}; -+ __shared__ half KQ[ne_KQ > ne_combine ? ne_KQ : ne_combine]; -+#else -+ float2 VKQ[ncols][(D/2)/nthreads_V] = {{{0.0f, 0.0f}}}; -+ __shared__ float KQ[ne_KQ > ne_combine ? ne_KQ : ne_combine]; -+#endif // V_DOT2_F32_F16_AVAILABLE -+ -+ float KQ_max[ncols]; -+ float KQ_sum[ncols]; -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ KQ_max[j] = -FLT_MAX/2.0f; -+ KQ_sum[j] = 0.0f; -+ } -+ -+ // Convert Q to float2 (f16 K) or q8_1 (quantized K) and store in registers: -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ half2 Q_reg[ncols][(D/2)/nthreads_KQ]; // Will be initialized completely. -+#else -+ __align__(16) float2 Q_reg[ncols][(D/2)/nthreads_KQ] = {{{0.0f, 0.0f}}}; // May be only partially initialized. -+#endif // V_DOT2_F32_F16_AVAILABLE -+ int Q_i32[ncols][1 > D/(sizeof(int)*nthreads_KQ) ? 1 : D/(sizeof(int)*nthreads_KQ)]; -+ float2 Q_ds[ncols][1 > D/(sizeof(int)*nthreads_KQ) ? 1 : D/(sizeof(int)*nthreads_KQ)]; -+ -+ ggml_cuda_pdl_sync(); -+ if constexpr (Q_q8_1) { -+#pragma unroll -+ for (int j0 = 0; j0 < ncols; j0 += nwarps) { -+ const int j = j0 + threadIdx.y; -+ -+ if (j0 + nwarps > ncols && j >= ncols) { -+ break; -+ } -+ -+ // Reuse KQ as temporary storage for converting Q to q8_1: -+ int * tmp_q_i32 = (int *) &KQ[j*D]; -+ float2 * tmp_q_ds = (float2 *) (tmp_q_i32 + D/sizeof(int)); -+ -+ // Set memory to zero if out of bounds: -+ if (ncols > 1 && ic0 + j >= int(ne01.z)) { -+#pragma unroll -+ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += WARP_SIZE) { -+ const int i = i0 + threadIdx.x; -+ -+ if (i0 + WARP_SIZE <= int(D/sizeof(int)) || i < int(D/sizeof(int))) { -+ tmp_q_i32[i] = 0; -+ } -+ } -+ if (threadIdx.x < D/QK8_1) { -+ tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f); -+ } -+ } else { -+ const float * Q_f = (const float *) (Q + j*nb01); -+ constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE; -+#pragma unroll -+ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) { -+ quantize_q8_1_to_shared -+ (Q_f + i0*sizeof(int), scale, tmp_q_i32 + i0, tmp_q_ds + i0/QI8_1); -+ } -+ } -+ } -+ -+ __syncthreads(); -+ -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ int * tmp_q_i32 = (int *) &KQ[j*D]; -+ float2 * tmp_q_ds = (float2 *) (tmp_q_i32 + D/sizeof(int)); -+ -+#pragma unroll -+ for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_KQ) { -+ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ); -+ -+ Q_i32[j][i0/nthreads_KQ] = tmp_q_i32[i]; -+ Q_ds[j][i0/nthreads_KQ] = tmp_q_ds[i/QI8_1]; -+ } -+ } -+ -+ __syncthreads(); -+ } else { -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ const half2 scale_h2 = make_half2(scale, scale); -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ const float2 * Q_j = (const float2 *) (Q + j*nb01); -+#pragma unroll -+ for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { -+ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; -+ -+ __align__(16) float2 tmp[cpy_ne] = {{0.0f, 0.0f}}; -+ if (ncols == 1 || ic0 + j < int(ne01.z)) { -+ ggml_cuda_memcpy_1(tmp, &Q_j[i]); -+ ggml_cuda_memcpy_1(tmp + cpy_ne/2, &Q_j[i + cpy_ne/2]); -+ } -+#pragma unroll -+ for (int i1 = 0; i1 < cpy_ne; ++i1) { -+ Q_reg[j][i0/nthreads_KQ + i1] = make_half2(tmp[i1].x, tmp[i1].y); -+ } -+ } -+#pragma unroll -+ for (int k = 0; k < (D/2)/nthreads_KQ; ++k) { -+ Q_reg[j][k] *= scale_h2; -+ } -+ } -+#else -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ const float2 * Q_j = (const float2 *) (Q + j*nb01); -+#pragma unroll -+ for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { -+ const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; -+ if (ncols == 1 || ic0 + j < int(ne01.z)) { -+ ggml_cuda_memcpy_1(&Q_reg[j][i0/nthreads_KQ], &Q_j[i]); -+ ggml_cuda_memcpy_1(&Q_reg[j][i0/nthreads_KQ + cpy_ne/2], &Q_j[i + cpy_ne/2]); -+ } -+ } -+#pragma unroll -+ for (int k = 0; k < (D/2)/nthreads_KQ; ++k) { -+ Q_reg[j][k].x *= scale; -+ Q_reg[j][k].y *= scale; -+ } -+ } -+#endif // V_DOT2_F32_F16_AVAILABLE -+ } -+ -+ const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; -+ K += blockIdx.y*nthreads * nb11; -+ V += blockIdx.y*nthreads * nb21; -+ maskh += blockIdx.y*nthreads; -+ for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, -+ // Increment pointers after each loop: -+ K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { -+ -+ // Calculate KQ tile and keep track of new maximum KQ values: -+ float KQ_reg[ncols]; // KQ in registers. -+ -+ float KQ_max_new[ncols]; -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ KQ_max_new[j] = KQ_max[j]; -+ } -+ -+#pragma unroll -+ for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) { -+ const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0; -+ -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); -+ sum = warp_reduce_sum(sum); -+ -+ if (use_logit_softcap) { -+ sum = logit_softcap*tanhf(sum); -+ } -+ -+ if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) { -+ sum += slope*__half2float(maskh[j*ne11 + i_KQ]); -+ } -+ -+ KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); -+ -+ if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { -+ KQ_reg[j] = sum; -+ } -+ } -+ } -+ -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+#pragma unroll -+ for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) { -+ KQ_max_new[j] = fmaxf(KQ_max_new[j], __shfl_xor_sync(0xFFFFFFFF, KQ_max_new[j], offset, WARP_SIZE)); -+ } -+ const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]); -+ KQ_max[j] = KQ_max_new[j]; -+ -+ KQ_reg[j] = expf(KQ_reg[j] - KQ_max[j]); -+ KQ_sum[j] = KQ_sum[j]*KQ_max_scale + KQ_reg[j]; -+ KQ[j*nthreads + tid] = KQ_reg[j]; -+ -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale, KQ_max_scale); -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j][i_VKQ_0/nthreads_V] *= KQ_max_scale_h2; -+ } -+#else -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j][i_VKQ_0/nthreads_V].x *= KQ_max_scale; -+ VKQ[j][i_VKQ_0/nthreads_V].y *= KQ_max_scale; -+ } -+#endif // V_DOT2_F32_F16_AVAILABLE -+ } -+ -+ ggml_cuda_syncwarp(); -+ -+#pragma unroll -+ for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { -+ const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); -+ -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ half2 KQ_k[ncols]; -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ KQ_k[j] = __half2half2(KQ[j*nthreads + k]); -+ } -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -+ half2 tmp[V_rows_per_thread/2]; -+ if constexpr (type_V == GGML_TYPE_BF16) { -+ float2 tmp_f[V_rows_per_thread/2]; -+ dequantize_V(V + k*nb21, tmp_f, -+ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); -+#pragma unroll -+ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { -+ tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); -+ } -+ } else { -+ dequantize_V(V + k*nb21, tmp, -+ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); -+ } -+#pragma unroll -+ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1] += tmp[i_VKQ_1]*KQ_k[j]; -+ } -+ } -+ } -+#else -+ float KQ_k[ncols]; -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ KQ_k[j] = KQ[j*nthreads + k]; -+ } -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -+ float2 tmp[V_rows_per_thread/2]; -+ dequantize_V(V + k*nb21, tmp, -+ 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); -+#pragma unroll -+ for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1].x += tmp[i_VKQ_1].x*KQ_k[j]; -+ VKQ[j][i_VKQ_0/nthreads_V + i_VKQ_1].y += tmp[i_VKQ_1].y*KQ_k[j]; -+ } -+ } -+ } -+#endif // V_DOT2_F32_F16_AVAILABLE -+ } -+ } -+ -+ if (sinks && blockIdx.y == 0) { -+ const float sink = ((const float *) sinks)[head]; -+ -+#pragma unroll -+ for (int j0 = 0; j0 < ncols; j0 += nwarps) { -+ const int j = j0 + threadIdx.y; -+ -+ if (j0 + nwarps > ncols && j >= ncols) { -+ break; -+ } -+ -+ const float kqmax_new_j = fmaxf(sink, KQ_max[j]); -+ const float KQ_max_scale = expf(KQ_max[j] - kqmax_new_j); -+ KQ_max[j] = kqmax_new_j; -+ -+ KQ_sum[j] = KQ_sum[j]*KQ_max_scale + (threadIdx.x == 0 ? expf(sink - KQ_max[j]) : 0.0f); -+ -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ const half2 KQ_max_scale_h2 = make_half2(KQ_max_scale, KQ_max_scale); -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j][i_VKQ_0/nthreads_V] *= KQ_max_scale_h2; -+ } -+#else -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j][i_VKQ_0/nthreads_V].x *= KQ_max_scale; -+ VKQ[j][i_VKQ_0/nthreads_V].y *= KQ_max_scale; -+ } -+#endif // V_DOT2_F32_F16_AVAILABLE -+ } -+ } -+ -+ __shared__ float KQ_max_shared[ncols][WARP_SIZE]; -+ __shared__ float KQ_sum_shared[ncols][WARP_SIZE]; -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ if (threadIdx.y == 0) { -+ KQ_max_shared[j][threadIdx.x] = -FLT_MAX/2.0f; -+ KQ_sum_shared[j][threadIdx.x] = 0.0f; -+ } -+ } -+ -+ __syncthreads(); -+ -+#pragma unroll -+ for (int j = 0; j < ncols; ++j) { -+ if (threadIdx.x == 0) { -+ KQ_max_shared[j][threadIdx.y] = KQ_max[j]; -+ } -+ } -+ __syncthreads(); -+ -+#pragma unroll -+ for (int j_VKQ = 0; j_VKQ < ncols; ++j_VKQ) { -+ if (ncols > 1 && ic0 + j_VKQ >= int(ne01.z)) { -+ break; -+ } -+ -+ float kqmax_new = KQ_max_shared[j_VKQ][threadIdx.x]; -+ kqmax_new = warp_reduce_max(kqmax_new); -+ const float kqmax_scale = expf(KQ_max[j_VKQ] - kqmax_new); -+ KQ_max[j_VKQ] = kqmax_new; -+ -+#ifdef V_DOT2_F32_F16_AVAILABLE -+ half2 * VKQ_tmp = (half2 *) KQ + threadIdx.y*(V_cols_per_iter*D/2) -+ + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V)*(D/2); -+ -+ const half2 kqmax_scale_h2 = make_half2(kqmax_scale, kqmax_scale); -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j_VKQ][i_VKQ_0/nthreads_V] *= kqmax_scale_h2; -+ } -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -+ const int i_VKQ = i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*(V_rows_per_thread/2); -+ -+ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ, &VKQ[j_VKQ][i_VKQ_0/nthreads_V]); -+ } -+#else -+ float2 * VKQ_tmp = (float2 *) KQ + threadIdx.y*(V_cols_per_iter*D/2) -+ + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V)*(D/2); -+ -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V) { -+ VKQ[j_VKQ][i_VKQ_0/nthreads_V].x *= kqmax_scale; -+ VKQ[j_VKQ][i_VKQ_0/nthreads_V].y *= kqmax_scale; -+ } -+#pragma unroll -+ for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -+ const int i_VKQ = i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*(V_rows_per_thread/2); -+ -+ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ, &VKQ[j_VKQ][i_VKQ_0/nthreads_V]); -+ ggml_cuda_memcpy_1(VKQ_tmp + i_VKQ + V_rows_per_thread/4, &VKQ[j_VKQ][i_VKQ_0/nthreads_V + V_rows_per_thread/4]); -+ } -+#endif // V_DOT2_F32_F16_AVAILABLE -+ -+ KQ_sum[j_VKQ] *= kqmax_scale; -+ KQ_sum[j_VKQ] = warp_reduce_sum(KQ_sum[j_VKQ]); -+ if (threadIdx.x == 0) { -+ KQ_sum_shared[j_VKQ][threadIdx.y] = KQ_sum[j_VKQ]; -+ } -+ -+ __syncthreads(); -+ -+ if (nthreads <= D || tid < D) { -+ KQ_sum[j_VKQ] = KQ_sum_shared[j_VKQ][threadIdx.x]; -+ KQ_sum[j_VKQ] = warp_reduce_sum(KQ_sum[j_VKQ]); -+ -+#pragma unroll -+ for (int i0 = 0; i0 < D; i0 += nthreads) { -+ float dst_val = 0; -+#pragma unroll -+ for (int w = 0; w < nwarps; ++w) { -+#pragma unroll -+ for (int v = 0; v < V_cols_per_iter; ++v) { -+ dst_val += float(KQ[w*V_cols_per_iter*D + v*D + i0 + tid]); -+ } -+ } -+ if (gridDim.y == 1) { -+ dst_val /= KQ_sum[j_VKQ]; -+ } -+ dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val; -+ } -+ } -+ -+ if (j_VKQ < ncols-1) { -+ __syncthreads(); -+ } -+ -+ } -+ -+ if (gridDim.y != 1 && tid < ncols && (ncols == 1 || ic0 + tid < int(ne01.z))) { -+ dst_meta[((sequence*int(ne01.z) + ic0 + tid)*ne02 + head)*gridDim.y + blockIdx.y] = make_float2(KQ_max[tid], KQ_sum[tid]); -+ } -+#else -+ GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, -+ max_bias, m0, m1, n_head_log2, logit_softcap, -+ ne00, ne01, ne02, ne03, -+ nb01, nb02, nb03, -+ ne10, ne11, ne12, ne13, -+ nb11, nb12, nb13, -+ nb21, nb22, nb23, -+ ne31, ne32, ne33, -+ nb31, nb32, nb33); -+ NO_DEVICE_CODE; -+#endif // FLASH_ATTN_AVAILABLE -+} -diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh -index 57a285565..5a54419c4 100644 ---- a/ggml/src/ggml-cuda/fattn-vec.cuh -+++ b/ggml/src/ggml-cuda/fattn-vec.cuh -@@ -16,9 +16,11 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wpass-failed" - #endif // __clang__ -+#include "fattn-vec-dense.cuh" -+ - template // D == head size - __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) --static __global__ void flash_attn_ext_vec( -+static __global__ void flash_attn_ext_vec_indexed( - const char * Q_ptr, - const char * K_ptr, - const char * V_ptr, -@@ -39,7 +41,9 @@ static __global__ void flash_attn_ext_vec( - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, - const int32_t ne31, const int32_t ne32, const int32_t ne33, -- const int32_t nb31, const int32_t nb32, const int64_t nb33) { -+ const int32_t nb31, const int32_t nb32, const int64_t nb33, -+ const ggml_cuda_fattn_indexed indexed) { -+ - ggml_cuda_pdl_lc(); - #ifdef FLASH_ATTN_AVAILABLE - const char * GGML_CUDA_RESTRICT Q = Q_ptr; -@@ -61,7 +65,7 @@ static __global__ void flash_attn_ext_vec( - nb11, nb12, nb13, - nb21, nb22, nb23, - ne31, ne32, ne33, -- nb31, nb32, nb33); -+ nb31, nb32, nb33, indexed); - NO_DEVICE_CODE; - return; - } -@@ -107,10 +111,10 @@ static __global__ void flash_attn_ext_vec( - const int head = blockIdx.z - sequence*ne02; - const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. - Q += nb03*sequence + nb02* head + nb01*ic0; -- K += nb13*sequence + nb12*(head / gqa_ratio); -- V += nb23*sequence + nb22*(head / gqa_ratio); -+ K += nb13*(indexed.indices ? sequence % ne13 : sequence) + nb12*(head / gqa_ratio); -+ V += nb23*(indexed.indices ? sequence % ne13 : sequence) + nb22*(head / gqa_ratio); - -- const half * maskh = (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0); -+ const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb31*ic0) : nullptr; - - const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); - -@@ -247,13 +251,16 @@ static __global__ void flash_attn_ext_vec( - #endif // V_DOT2_F32_F16_AVAILABLE - } - -- const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; -- K += blockIdx.y*nthreads * nb11; -- V += blockIdx.y*nthreads * nb21; -- maskh += blockIdx.y*nthreads; -+ const int indexed_sequence = indexed.indices ? sequence % indexed.sequences : 0; -+ const int32_t * indices = indexed.indices ? indexed.indices + indexed_sequence*indexed.index_stride : nullptr; -+ const int live_n_kv = indices ? max(0, min(ne11, indexed.lengths[indexed_sequence*indexed.length_stride])) : ne11; -+ const int k_VKQ_max = indices ? live_n_kv : (KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11); -+ K += indices ? 0 : blockIdx.y*nthreads * nb11; -+ V += indices ? 0 : blockIdx.y*nthreads * nb21; -+ maskh = mask ? maskh + blockIdx.y*nthreads : nullptr; - for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, - // Increment pointers after each loop: -- K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { -+ K += indices ? 0 : gridDim.y*nthreads*nb11, V += indices ? 0 : gridDim.y*nthreads*nb21, maskh = mask ? maskh + gridDim.y*nthreads : nullptr) { - - // Calculate KQ tile and keep track of new maximum KQ values: - float KQ_reg[ncols]; // KQ in registers. -@@ -270,7 +277,9 @@ static __global__ void flash_attn_ext_vec( - - #pragma unroll - for (int j = 0; j < ncols; ++j) { -- float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); -+ const int physical = indices ? (k_VKQ_0 + i_KQ < live_n_kv ? indices[k_VKQ_0 + i_KQ] : -1) : i_KQ; -+ const bool valid = !indices || (physical >= 0 && physical < indexed.physical_rows); -+ float sum = valid ? vec_dot_KQ(K + int64_t(physical)*nb11, Q_reg[j], Q_i32[j], Q_ds[j]) : 0.0f; - sum = warp_reduce_sum(sum); - - if (use_logit_softcap) { -@@ -281,6 +290,9 @@ static __global__ void flash_attn_ext_vec( - sum += slope*__half2float(maskh[j*ne11 + i_KQ]); - } - -+ if (!valid) { -+ sum = -INFINITY; -+ } - KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET); - - if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) { -@@ -322,6 +334,9 @@ static __global__ void flash_attn_ext_vec( - #pragma unroll - for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) { - const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V); -+ const int physical = indices ? (k_VKQ_0 + k < live_n_kv ? indices[k_VKQ_0 + k] : -1) : k; -+ const bool valid = !indices || (physical >= 0 && physical < indexed.physical_rows); -+ const char * V_row = valid ? V + int64_t(physical)*nb21 : V; - - #ifdef V_DOT2_F32_F16_AVAILABLE - half2 KQ_k[ncols]; -@@ -331,17 +346,17 @@ static __global__ void flash_attn_ext_vec( - } - #pragma unroll - for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -- half2 tmp[V_rows_per_thread/2]; -+ half2 tmp[V_rows_per_thread/2] = {}; - if constexpr (type_V == GGML_TYPE_BF16) { -- float2 tmp_f[V_rows_per_thread/2]; -- dequantize_V(V + k*nb21, tmp_f, -+ float2 tmp_f[V_rows_per_thread/2] = {}; -+ if (valid) dequantize_V(V_row, tmp_f, - 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); - #pragma unroll - for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { - tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); - } - } else { -- dequantize_V(V + k*nb21, tmp, -+ if (valid) dequantize_V(V_row, tmp, - 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); - } - #pragma unroll -@@ -360,8 +375,8 @@ static __global__ void flash_attn_ext_vec( - } - #pragma unroll - for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { -- float2 tmp[V_rows_per_thread/2]; -- dequantize_V(V + k*nb21, tmp, -+ float2 tmp[V_rows_per_thread/2] = {}; -+ if (valid) dequantize_V(V_row, tmp, - 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); - #pragma unroll - for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { -@@ -376,7 +391,7 @@ static __global__ void flash_attn_ext_vec( - } - } - -- if (sinks && blockIdx.y == 0) { -+ if (sinks && blockIdx.y == 0 && (!indices || live_n_kv != 0)) { - const float sink = ((const float *) sinks)[head]; - - #pragma unroll -@@ -496,7 +511,7 @@ static __global__ void flash_attn_ext_vec( - } - } - if (gridDim.y == 1) { -- dst_val /= KQ_sum[j_VKQ]; -+ dst_val = indices && KQ_sum[j_VKQ] == 0.0f ? 0.0f : dst_val / KQ_sum[j_VKQ]; - } - dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val; - } -@@ -520,7 +535,7 @@ static __global__ void flash_attn_ext_vec( - nb11, nb12, nb13, - nb21, nb22, nb23, - ne31, ne32, ne33, -- nb31, nb32, nb33); -+ nb31, nb32, nb33, indexed); - NO_DEVICE_CODE; - #endif // FLASH_ATTN_AVAILABLE - } -@@ -534,7 +549,9 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm - - const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc); - const int nwarps = nthreads / WARP_SIZE; -- fattn_kernel_t fattn_kernel = flash_attn_ext_vec; -+ fattn_kernel_t fattn_kernel = dst->src[5] -+ ? flash_attn_ext_vec_indexed -+ : flash_attn_ext_vec; - const bool need_f16_K = type_K == GGML_TYPE_F16; - const bool need_f16_V = type_V == GGML_TYPE_F16; - constexpr size_t nbytes_shared = 0; -diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu -index 5fa3e5308..b74322b6f 100644 ---- a/ggml/src/ggml-cuda/fattn.cu -+++ b/ggml/src/ggml-cuda/fattn.cu -@@ -130,6 +130,9 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ - GGML_UNUSED_VARS(cc, dst, ncols1, ncols2); - return false; - #else -+ if (dst->src[5]) { -+ return false; // Explicit logical rows bypass mask-derived sparse lists. -+ } - const ggml_tensor * Q = dst->src[0]; - const ggml_tensor * K = dst->src[1]; - const ggml_tensor * mask = dst->src[3]; -@@ -204,7 +207,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con - - // Edge cases like no mask, ALiBi, unpadded K/V, or misaligned addresses for large data transfers - // are put into the template specialization without GQA optimizations. -- bool use_gqa_opt = mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ bool use_gqa_opt = mask && max_bias == 0.0f && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; - for (const ggml_tensor * t : {Q, K, V, mask}) { - if (t == nullptr || ggml_is_quantized(t->type)) { - continue; -@@ -357,6 +360,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg - case 576: { - // For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels. - GGML_ASSERT(V->ne[0] == 512); -+ const int64_t kv_span = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; - float max_bias = 0.0f; - memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); - -@@ -375,7 +379,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg - break; - } - if (cc >= GGML_CUDA_CC_BLACKWELL) { -- if (Q->ne[1] <= 4 && K->ne[1] >= 65536) { -+ if (Q->ne[1] <= 4 && kv_span >= 65536) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); - break; - } -@@ -392,7 +396,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg - } - if (cc >= GGML_CUDA_CC_TURING) { - if (Q->ne[1] <= 4) { -- if (K->ne[1] <= 16384) { -+ if (kv_span <= 16384) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); - break; - } -@@ -537,6 +541,27 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { - } - } - -+// The 576/512 MMA specialization reuses the K tile for V. Shape alone does -+// not establish this alias: indexed FA also admits independent physical pools. -+static bool ggml_cuda_fattn_v_aliases_k(const ggml_tensor * K, const ggml_tensor * V) { -+ const bool same_view = V->view_src && -+ ((V->view_src == K && V->view_offs == 0) || -+ (K->view_src && V->view_src == K->view_src && V->view_offs == K->view_offs)); -+ const bool same_data = K->data && V->data && K->data == V->data; -+ if (K->data && V->data && !same_data) { -+ return false; -+ } -+ if ((!same_view && !same_data) || K->type != V->type || V->ne[0] > K->ne[0]) { -+ return false; -+ } -+ for (int i = 0; i < GGML_MAX_DIMS; ++i) { -+ if (K->nb[i] != V->nb[i] || (i != 0 && K->ne[i] != V->ne[i])) { -+ return false; -+ } -+ } -+ return true; -+} -+ - static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { - #ifndef FLASH_ATTN_AVAILABLE - GGML_UNUSED(device); GGML_UNUSED(dst); -@@ -557,7 +582,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const - - // The effective batch size for the kernel can be increased by gqa_ratio. - // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded, -- bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && (dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]) % FATTN_KQ_STRIDE == 0; - for (const ggml_tensor * t : {Q, K, V, mask}) { - if (t == nullptr || ggml_is_quantized(t->type)) { - continue; -@@ -629,9 +654,40 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const - return BEST_FATTN_KERNEL_NONE; - } - -+ if (const ggml_tensor * indices = dst->src[5]) { -+ const ggml_tensor * lengths = dst->src[6]; -+ // Indexed tile/MMA readers decode selected rows directly into shared -+ // tiles, supporting the same mixed KV types without pool conversion. -+ if (!lengths || indices->type != GGML_TYPE_I32 || lengths->type != GGML_TYPE_I32 || -+ !ggml_is_contiguous(indices) || !ggml_is_contiguous(lengths) || -+ indices->ne[0] <= 0 || indices->ne[0] > INT32_MAX || -+ indices->ne[0] % FATTN_KQ_STRIDE != 0 || -+ indices->ne[1] != 1 || indices->ne[2] != 1 || indices->ne[3] <= 0 || -+ lengths->ne[0] != 1 || lengths->ne[1] != 1 || lengths->ne[2] != 1 || -+ lengths->ne[3] != indices->ne[3] || Q->ne[3] % indices->ne[3] != 0 || -+ (mask && mask->ne[0] != indices->ne[0]) || K->ne[1] > INT32_MAX || -+ K->ne[3] != V->ne[3] || Q->ne[3] % K->ne[3] != 0) { -+ return BEST_FATTN_KERNEL_NONE; -+ } -+ if (Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && Q->ne[1] <= 2 && -+ K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && -+ ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr) { -+ return BEST_FATTN_KERNEL_VEC; -+ } -+ if (K->ne[0] == 576 && !ggml_cuda_fattn_v_aliases_k(K, V)) { -+ return BEST_FATTN_KERNEL_TILE; -+ } -+ } -+ - // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes: - // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. -- const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; -+ const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; -+ // Indexed readers do not convert the physical pool to F16 for missing vec types. -+ const bool vector_types = !dst->src[5] || (K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && -+ ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr); -+ const bool can_use_vector_kernel = vector_types && Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && -+ Q->ne[0] != 192 && n_kv % FATTN_KQ_STRIDE == 0; - - // If Turing tensor cores are available, use them: - if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { -@@ -749,7 +805,7 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d - } - - const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra = -- ggml_cuda_flash_attn_ext_get_f16_extra_data(dst, need_f16_K, need_f16_V); -+ ggml_cuda_flash_attn_ext_get_f16_extra_data(dst, need_f16_K && !dst->src[5], need_f16_V && !dst->src[5]); - - return f16_extra.end - (uintptr_t) dst->data; - } -diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu -index f860e8035..960a96e77 100644 ---- a/ggml/src/ggml-cuda/ggml-cuda.cu -+++ b/ggml/src/ggml-cuda/ggml-cuda.cu -@@ -2759,6 +2759,7 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx - for (int j = 0; j < GGML_MAX_SRC; ++j) { - if (cgraph->nodes[i]->src[j]) { - prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data; -+ prop.node_src_types[j] = cgraph->nodes[i]->src[j]->type; - memcpy(prop.node_src_ne[j], cgraph->nodes[i]->src[j]->ne, sizeof(prop.node_src_ne[j])); - memcpy(prop.node_src_nb[j], cgraph->nodes[i]->src[j]->nb, sizeof(prop.node_src_nb[j])); - } -diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp -index 54a6d166d..d3677ac92 100644 ---- a/ggml/src/ggml-et/ggml-et.cpp -+++ b/ggml/src/ggml-et/ggml-et.cpp -@@ -1268,6 +1268,9 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm - (op->src[1]->ne[1] % op->src[4]->ne[1] == 0); - break; - case GGML_OP_FLASH_ATTN_EXT: -+ if (op->src[5]) { -+ return false; -+ } - if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && - (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && - (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && -diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp -index 08c15ff78..bbda6f992 100644 ---- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp -+++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp -@@ -9500,7 +9500,7 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons - break; - - case GGML_OP_FLASH_ATTN_EXT: -- supp = ggml_hexagon_supported_flash_attn_ext(sess, op); -+ supp = !op->src[5] && ggml_hexagon_supported_flash_attn_ext(sess, op); - break; - - case GGML_OP_SET_ROWS: -diff --git a/ggml/src/ggml-metal/ggml-metal-attention-indexed.h b/ggml/src/ggml-metal/ggml-metal-attention-indexed.h -new file mode 100644 -index 000000000..04445aada ---- /dev/null -+++ b/ggml/src/ggml-metal/ggml-metal-attention-indexed.h -@@ -0,0 +1,90 @@ -+#pragma once -+ -+#include "ggml.h" -+#include "ggml-metal-impl.h" -+ -+// Request-local physical row lists use the existing attention gather kernels. -+// Keep their admission independent from the mask-scanning sparse hint limits. -+static inline bool ggml_metal_flash_attn_indexed_supported(const struct ggml_tensor * op) { -+ const struct ggml_tensor * indices = op->src[5]; -+ const struct ggml_tensor * lengths = op->src[6]; -+ if (!indices || !lengths || indices->type != GGML_TYPE_I32 || lengths->type != GGML_TYPE_I32 || -+ indices->nb[0] != sizeof(int32_t) || lengths->ne[0] != 1 || -+ op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != op->src[2]->type || -+ op->src[0]->ne[1] >= 65536 || op->src[0]->ne[3] >= 65536 || -+ indices->ne[0] <= 0 || indices->ne[0] > INT32_MAX || op->src[1]->ne[1] > INT32_MAX) { -+ return false; -+ } -+ for (int dim = 1; dim < 4; ++dim) { -+ if (indices->ne[dim] <= 0 || lengths->ne[dim] != indices->ne[dim] || -+ op->src[0]->ne[dim] % indices->ne[dim] != 0) { -+ return false; -+ } -+ } -+ const int64_t dk = op->src[1]->ne[0]; -+ const int64_t dv = op->src[2]->ne[0]; -+ const bool shape = ((dk == 32 || dk == 40 || dk == 48 || dk == 64 || dk == 72 || -+ dk == 80 || dk == 112) && dv == dk) || -+ (dk == 96 && (dv == 96 || dv == 64)) || (dk == 128 && (dv == 128 || dv == 96)) || -+ (dk == 192 && (dv == 192 || dv == 128)) || (dk == 256 && dv == 256) || -+ (dk == 320 && dv == 256) || (dk == 512 && dv == 512) || (dk == 576 && dv == 512); -+ if (!shape || (dk % 32 != 0 && (indices->ne[1] != 1 || indices->ne[2] != 1))) { -+ return false; -+ } -+ switch (op->src[1]->type) { -+ case GGML_TYPE_F32: -+ case GGML_TYPE_F16: -+ case GGML_TYPE_BF16: -+ case GGML_TYPE_Q4_0: -+ case GGML_TYPE_Q4_1: -+ case GGML_TYPE_Q5_0: -+ case GGML_TYPE_Q5_1: -+ case GGML_TYPE_Q8_0: -+ return true; -+ default: -+ return false; -+ } -+} -+ -+// Canonical request lists share one logical K/V order across the query tile. -+// Reuse the existing typed matrix kernel for prefill instead of scalarizing it. -+static inline bool ggml_metal_flash_attn_indexed_use_mma(const struct ggml_tensor * op) { -+ return op->src[5] && (op->src[0]->ne[1] >= 20 || op->src[1]->ne[0] % 32 != 0) && -+ op->src[5]->ne[1] == 1 && op->src[5]->ne[2] == 1; -+} -+ -+static inline void ggml_metal_flash_attn_indexed_args( -+ const struct ggml_tensor * op, ggml_metal_kargs_flash_attn_ext_vec * args) { -+ if (!op->src[5]) { -+ return; -+ } -+ args->n_kv_physical = (int32_t) op->src[1]->ne[1]; -+ args->n_kv_indices = (int32_t) op->src[5]->ne[0]; -+ args->ne51 = (int32_t) op->src[5]->ne[1]; -+ args->ne52 = (int32_t) op->src[5]->ne[2]; -+ args->ne53 = (int32_t) op->src[5]->ne[3]; -+ args->nb51 = op->src[5]->nb[1]; -+ args->nb52 = op->src[5]->nb[2]; -+ args->nb53 = op->src[5]->nb[3]; -+ args->nb61 = op->src[6]->nb[1]; -+ args->nb62 = op->src[6]->nb[2]; -+ args->nb63 = op->src[6]->nb[3]; -+} -+ -+static inline void ggml_metal_flash_attn_indexed_mma_args( -+ const struct ggml_tensor * op, ggml_metal_kargs_flash_attn_ext * args) { -+ if (!op->src[5]) { -+ return; -+ } -+ args->n_kv_physical = (int32_t) op->src[1]->ne[1]; -+ args->n_kv_indices = (int32_t) op->src[5]->ne[0]; -+ args->ne51 = (int32_t) op->src[5]->ne[1]; -+ args->ne52 = (int32_t) op->src[5]->ne[2]; -+ args->ne53 = (int32_t) op->src[5]->ne[3]; -+ args->nb51 = op->src[5]->nb[1]; -+ args->nb52 = op->src[5]->nb[2]; -+ args->nb53 = op->src[5]->nb[3]; -+ args->nb61 = op->src[6]->nb[1]; -+ args->nb62 = op->src[6]->nb[2]; -+ args->nb63 = op->src[6]->nb[3]; -+} -diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp -index 2c7972b0a..b0e66a08a 100644 ---- a/ggml/src/ggml-metal/ggml-metal-device.cpp -+++ b/ggml/src/ggml-metal/ggml-metal-device.cpp -@@ -1902,6 +1902,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( - int32_t ns20) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ const bool has_indices = op->src[5] != nullptr; -+ - char base[256]; - char name[256]; - -@@ -1919,7 +1921,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( - dk, - dv); - -- snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_ns10=%d_ns20=%d_nsg=%d", -+ snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_indexed=%d_ns10=%d_ns20=%d_nsg=%d", - base, - has_mask, - has_sinks, -@@ -1927,6 +1929,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( - has_scap, - has_kvpad, - bc_mask, -+ has_indices, - ns10, - ns20, - nsg); -@@ -1940,6 +1943,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( - ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT + 2); - ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT + 3); - ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT + 4); -+ ggml_metal_cv_set_bool(cv, has_indices, FC_FLASH_ATTN_EXT + 5); - - ggml_metal_cv_set_bool(cv, bc_mask, FC_FLASH_ATTN_EXT + 10); - -@@ -1993,6 +1997,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - int32_t ns20) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ const bool has_indices = op->src[5] != nullptr; -+ - char base[256]; - char name[256]; - -@@ -2013,7 +2019,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - dv, - qne_suffix); - -- snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", -+ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_indexed=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", - base, - has_mask, - has_sinks, -@@ -2021,6 +2027,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - has_scap, - has_kvpad, - has_sparse, -+ has_indices, - ns10, - ns20, - nsg, nwg); -@@ -2035,6 +2042,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v - ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_VEC + 3); - ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); - ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); -+ ggml_metal_cv_set_bool(cv, has_indices, FC_FLASH_ATTN_EXT_VEC + 6); - - ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); - ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); -diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index 5b23ddf7f..b1171f6ae 100644 ---- a/ggml/src/ggml-metal/ggml-metal-device.m -+++ b/ggml/src/ggml-metal/ggml-metal-device.m -@@ -5,6 +5,7 @@ - #import "ggml-backend-impl.h" - #import "ggml-metal-impl.h" - #import "ggml-metal-common.h" -+#import "ggml-metal-attention-indexed.h" - - #include - -@@ -1887,6 +1888,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te - case GGML_OP_ROLL: - return ggml_is_contiguous(op->src[0]); - case GGML_OP_FLASH_ATTN_EXT: -+ if (op->src[5]) { -+ return ggml_metal_flash_attn_indexed_supported(op) && has_simdgroup_mm && -+ (op->src[1]->type != GGML_TYPE_BF16 || has_bfloat); -+ } - // for new head sizes, add checks here - if (op->src[0]->ne[0] != 32 && - op->src[0]->ne[0] != 40 && -diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h -index d151a600d..a7fc56741 100644 ---- a/ggml/src/ggml-metal/ggml-metal-impl.h -+++ b/ggml/src/ggml-metal/ggml-metal-impl.h -@@ -445,6 +445,11 @@ typedef struct { - float m1; - int32_t n_head_log2; - float logit_softcap; -+ int32_t n_kv_physical; -+ int32_t n_kv_indices; -+ int32_t ne51, ne52, ne53; -+ uint64_t nb51, nb52, nb53; -+ uint64_t nb61, nb62, nb63; - } ggml_metal_kargs_flash_attn_ext; - - typedef struct { -@@ -481,6 +486,11 @@ typedef struct { - int32_t n_head_log2; - float logit_softcap; - int32_t n_kv_max_padded; -+ int32_t n_kv_physical; -+ int32_t n_kv_indices; -+ int32_t ne51, ne52, ne53; -+ uint64_t nb51, nb52, nb53; -+ uint64_t nb61, nb62, nb63; - } ggml_metal_kargs_flash_attn_ext_vec; - - typedef struct { -diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp -index 53c981618..c983946dd 100644 ---- a/ggml/src/ggml-metal/ggml-metal-ops.cpp -+++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp -@@ -9,6 +9,7 @@ - #include "ggml-metal-device.h" - #include "ggml-metal-fusion.h" - #include "ggml-metal-tuning.h" -+#include "ggml-metal-attention-indexed.h" - - #include - #include -@@ -3094,6 +3095,10 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) { - bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return !ggml_metal_flash_attn_indexed_use_mma(op); -+ } -+ - const int64_t ne00 = op->src[0]->ne[0]; // head size - const int64_t ne01 = op->src[0]->ne[1]; // batch size - -@@ -3106,6 +3111,10 @@ bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { - static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return false; -+ } -+ - // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial - // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 - // TODO: tune per device -@@ -3174,6 +3183,11 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool - static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ GGML_ASSERT(ggml_metal_flash_attn_indexed_supported(op)); -+ return (int) op->src[5]->ne[0]; -+ } -+ - int32_t n_kv_max = 0; - memcpy(&n_kv_max, ((const int32_t *) op->op_params) + 4, sizeof(n_kv_max)); - -@@ -3253,6 +3267,10 @@ static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) - size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return 0; -+ } -+ - GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); - GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); - GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); -@@ -3311,6 +3329,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { - size_t ggml_metal_op_flash_attn_ext_extra_blk(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return 0; -+ } -+ - GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); - //GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); - //GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); -@@ -3379,6 +3401,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { - size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return 0; -+ } -+ - // note: always reserve the temp buffer to avoid graph reallocations - //if (!ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { - // return 0; -@@ -3404,6 +3430,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { - size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - -+ if (op->src[5]) { -+ return 0; -+ } -+ - GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne); - - const int n_kv_max = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op); -@@ -3496,6 +3526,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - // sparse path: gather the finite mask entries into index lists and run the vec kernels over them - const int n_kv_max_sparse = ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op); -+ const bool use_indexed = op->src[5] != nullptr; -+ const bool use_indexed_mma = ggml_metal_flash_attn_indexed_use_mma(op); - const bool use_sparse = n_kv_max_sparse > 0; - const int n_kv_max_padded = use_sparse ? GGML_PAD(n_kv_max_sparse, OP_FLASH_ATTN_EXT_VEC_NCPSG) : 0; - -@@ -3676,6 +3708,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.m1 =*/ m1, - /*.n_head_log2 =*/ n_head_log2, - /*.logit_softcap =*/ logit_softcap, -+ /* indexed physical/list bounds and broadcast strides */ -+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - }; - - // shared memory layout: queries (16-bit), scores (float), probabilities (16-bit), row scale (float), rescale flag (int) -@@ -3699,7 +3733,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0); - - ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, ne02, ne03, 32, nsg, 1); -- } else if (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op)) { -+ } else if (use_indexed_mma || (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op))) { - // half8x8 kernel - const int nqptg = OP_FLASH_ATTN_EXT_NQPSG; // queries per threadgroup - const int ncpsg = OP_FLASH_ATTN_EXT_NCPSG; // cache values per simdgroup -@@ -3710,7 +3744,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - bool need_sync = false; - -- const bool has_kvpad = ne11 % ncpsg != 0; -+ const bool has_kvpad = !use_indexed && ne11 % ncpsg != 0; - - if (has_kvpad) { - assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); -@@ -3750,7 +3784,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - need_sync = true; - } - -- if (has_mask) { -+ if (has_mask && !use_indexed) { - assert(ggml_metal_op_flash_attn_ext_extra_blk(op) != 0); - - ggml_metal_kargs_flash_attn_ext_blk args0 = { -@@ -3783,7 +3817,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_metal_op_concurrency_reset(ctx); - } - -- const int is_q = !use_kv_f16 && ggml_is_quantized(op->src[1]->type) ? 1 : 0; -+ const int is_q = use_indexed || (!use_kv_f16 && ggml_is_quantized(op->src[1]->type)) ? 1 : 0; - - // shared memory layout (halfs unless noted): - // queries/attn/result: Q*(DK + 2*PAD2(DV,64) + 4*C) -@@ -3797,6 +3831,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - // simdgroups per threadgroup (a.k.a. warps) - int32_t nsg = ne00 >= 512 ? 8 : 4; -+ while (use_indexed && nsg > 1 && fa_smem(nsg) > props_dev->max_theadgroup_memory_size) { -+ nsg /= 2; -+ } - - const size_t smem = fa_smem(nsg); - -@@ -3810,7 +3847,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.nb01 =*/ nb01, - /*.nb02 =*/ nb02, - /*.nb03 =*/ nb03, -- /*.ne11 =*/ ne11, -+ /*.ne11 =*/ use_indexed ? n_kv_max_padded : ne11, - /*.ne_12_2 =*/ ne12, - /*.ne_12_3 =*/ ne13, - /*.ns10 =*/ ns10, -@@ -3836,8 +3873,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.m1 =*/ m1, - /*.n_head_log2 =*/ n_head_log2, - /*.logit_softcap =*/ logit_softcap, -+ /* indexed physical/list bounds and broadcast strides */ -+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - }; - -+ ggml_metal_flash_attn_indexed_mma_args(op, &args); -+ - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20); - - ggml_metal_encoder_set_pipeline(enc, pipeline); -@@ -3850,6 +3891,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_metal_encoder_set_buffer (enc, bid_pad, 6); - ggml_metal_encoder_set_buffer (enc, bid_blk, 7); - ggml_metal_encoder_set_buffer (enc, bid_dst, 8); -+ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[5]) : bid_src0, 9); -+ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[6]) : bid_src0, 10); - - GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size); - -@@ -3880,7 +3923,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - - const bool has_kvpad = !use_sparse && ne11 % ncpsg != 0; - -- if (use_sparse) { -+ if (use_sparse && !use_indexed) { - assert(ggml_metal_op_flash_attn_ext_extra_idx(op) != 0); - - GGML_ASSERT(ne30 == ne11); -@@ -4046,8 +4089,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - /*.n_head_log2 =*/ n_head_log2, - /*.logit_softcap =*/ logit_softcap, - /*.n_kv_max_padded =*/ n_kv_max_padded, -+ /* indexed physical/list bounds and broadcast strides */ -+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - }; - -+ ggml_metal_flash_attn_indexed_args(op, &args); -+ - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); - - GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); -@@ -4059,7 +4106,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { - ggml_metal_encoder_set_buffer (enc, bid_v, 3); - ggml_metal_encoder_set_buffer (enc, bid_src3, 4); - ggml_metal_encoder_set_buffer (enc, bid_src4, 5); -- ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : bid_src0, 8); -+ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[5]) : (use_sparse ? bid_idx : bid_src0), 8); -+ ggml_metal_encoder_set_buffer (enc, use_indexed ? ggml_metal_get_buffer_id(op->src[6]) : bid_src0, 9); - - const size_t smem = fa_vec_smem(nsg, nqptg); - -diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal -index 5e08bf85f..f92f945b5 100644 ---- a/ggml/src/ggml-metal/kernels/fa_common.metal -+++ b/ggml/src/ggml-metal/kernels/fa_common.metal -@@ -3,6 +3,7 @@ constant bool FC_flash_attn_ext_has_sinks [[function_constant(FC_FLASH_ATTN_EXT - constant bool FC_flash_attn_ext_has_bias [[function_constant(FC_FLASH_ATTN_EXT + 2)]]; - constant bool FC_flash_attn_ext_has_scap [[function_constant(FC_FLASH_ATTN_EXT + 3)]]; - constant bool FC_flash_attn_ext_has_kvpad [[function_constant(FC_FLASH_ATTN_EXT + 4)]]; -+constant bool FC_flash_attn_ext_has_indices [[function_constant(FC_FLASH_ATTN_EXT + 5)]]; - - constant bool FC_flash_attn_ext_bc_mask [[function_constant(FC_FLASH_ATTN_EXT + 10)]]; - -@@ -14,6 +15,18 @@ constant int32_t FC_flash_attn_ext_ns10 [[function_constant(FC_FLASH_ATTN_EXT + - constant int32_t FC_flash_attn_ext_ns20 [[function_constant(FC_FLASH_ATTN_EXT + 21)]]; - constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + 22)]]; - -+// The physical pool may be interleaved, shared, or recycled. The list remains -+// in logical token order so mask columns and causality retain their meaning. -+static inline int flash_attn_ext_indexed_physical( -+ constant ggml_metal_kargs_flash_attn_ext & args, -+ device const int * indices, int count, int logical) { -+ if (logical < 0 || logical >= count) { -+ return -1; -+ } -+ const int physical = indices[logical]; -+ return physical >= 0 && physical < args.n_kv_physical ? physical : -1; -+} -+ - // ref: https://arxiv.org/pdf/2307.08691.pdf - template< - typename q_t, // query types in shared memory -@@ -54,6 +67,8 @@ void kernel_flash_attn_ext_impl( - device const char * pad, - device const char * blk, - device char * dst, -+ device const char * indices, -+ device const char * lengths, - threadgroup half * shmem_f16, - uint3 tgpig, - ushort tiisg, -@@ -118,7 +133,7 @@ void kernel_flash_attn_ext_impl( - pm2[jj] = (device const half2 *) ((device const char *) mask + (iq1 + j)*args.nb31 + (iq2%args.ne32)*args.nb32 + (iq3%args.ne33)*args.nb33); - } - -- { -+ if (!FC_flash_attn_ext_has_indices) { - const int32_t nblk1 = ((args.ne01 + Q - 1)/Q); - const int32_t nblk0 = ((args.ne11 + C - 1)/C); - -@@ -182,11 +197,20 @@ void kernel_flash_attn_ext_impl( - slope = pow(base, exph); - } - -+ device const int * pidx = nullptr; -+ int n_kv = args.ne11; -+ if (FC_flash_attn_ext_has_indices) { -+ const int i3 = iq3%args.ne53; -+ pidx = (device const int *) (indices + i3*args.nb53); -+ const int count = *((device const int *) (lengths + i3*args.nb63)); -+ n_kv = clamp(count, 0, args.n_kv_indices); -+ } -+ - // loop over the KV cache - // each simdgroup handles blocks of Q rows and C columns - for (int ic0 = 0; ; ++ic0) { - int ic = ic0*C; -- if (ic >= args.ne11) { -+ if (ic >= n_kv) { - break; - } - -@@ -231,7 +255,22 @@ void kernel_flash_attn_ext_impl( - char blk_cur = 1; - - // read the mask into shared mem -- if (FC_flash_attn_ext_has_mask) { -+ if (FC_flash_attn_ext_has_indices) { -+ FOR_UNROLL (short jj = 0; jj < NQ; ++jj) { -+ const short j = jj*NSG + sgitg; -+ half2 values(-MAXHALF, -MAXHALF); -+ FOR_UNROLL (short col = 0; col < 2; ++col) { -+ const int logical = ic + 2*tiisg + col; -+ if ((iq1 + j) < args.ne01 && -+ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) >= 0) { -+ values[col] = FC_flash_attn_ext_has_mask ? -+ ((device const half *) pm2[jj])[2*tiisg + col] : 0.0h; -+ } -+ } -+ sm2[j*SH + tiisg] = values; -+ pm2[jj] += NW; -+ } -+ } else if (FC_flash_attn_ext_has_mask) { - blk_cur = blk[ic0]; - - if (blk_cur == 0) { -@@ -286,7 +325,31 @@ void kernel_flash_attn_ext_impl( - - // Q*K^T - // this is compile-time check, so it does not have runtime overhead -- if (is_same::value) { -+ if (is_same::value && FC_flash_attn_ext_has_indices) { -+ // Gather an 8x8 tile before the existing MMA. This also covers -+ // non-quantized heads not divisible by 16 without truncation. -+ const short col = tiisg%8; -+ const short row = tiisg/8; -+ for (short cc = sgitg; cc < C/8; cc += NSG) { -+ qk8x8_t mqk = make_filled_simdgroup_matrix((qk_t) 0.0f); -+ for (short block = 0; block < DK8; ++block) { -+ FOR_UNROLL (short part = 0; part < 2; ++part) { -+ const short r = row + 4*part; -+ const int physical = flash_attn_ext_indexed_physical(args, pidx, n_kv, ic + 8*cc + r); -+ sk[8*r + col] = physical < 0 ? k_t(0) : -+ ((device const k_t *) (k + physical*args.nb11))[8*block + col]; -+ } -+ simdgroup_barrier(mem_flags::mem_threadgroup); -+ k8x8_t mk; -+ q8x8_t mq; -+ simdgroup_load(mk, sk, 8, 0, true); -+ simdgroup_load(mq, sq + 8*block, DK); -+ simdgroup_multiply_accumulate(mqk, mq, mk, mqk); -+ simdgroup_barrier(mem_flags::mem_threadgroup); -+ } -+ simdgroup_store(mqk, ss + 8*cc, SH, 0, false); -+ } -+ } else if (is_same::value) { - // we can read directly from global memory - device const k_t * pk = (device const k_t *) (k + ic*args.nb11); - threadgroup const q_t * pq = sq; -@@ -354,13 +417,20 @@ void kernel_flash_attn_ext_impl( - qk8x8_t mqk = make_filled_simdgroup_matrix((qk_t) 0.0f); - - for (short ii = 0; ii < DK16; ii += 4) { -- device const kd4x4_t * pk4x4 = (device const kd4x4_t *) (k + ((ic + 8*cc + ty)*args.nb11)); -+ const int logical = ic + 8*cc + ty; -+ const int physical = FC_flash_attn_ext_has_indices ? -+ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) : logical; -+ device const kd4x4_t * pk4x4 = (device const kd4x4_t *) (k + max(physical, 0)*args.nb11); - - if (DK16%4 == 0) { - // the head is evenly divisible by 4*16 = 64, so no need for bound checks - { - k4x4_t tmp; -- deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); -+ if (physical >= 0) { -+ deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); -+ } else { -+ tmp = k4x4_t(0); -+ } - sk4x4[4*ty + tx] = tmp; - } - -@@ -381,7 +451,11 @@ void kernel_flash_attn_ext_impl( - } else { - if (ii + tx < DK16) { - k4x4_t tmp; -- deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); -+ if (physical >= 0) { -+ deq_k(pk4x4 + (ii + tx)/nl_k, (ii + tx)%nl_k, tmp); -+ } else { -+ tmp = k4x4_t(0); -+ } - sk4x4[4*ty + tx] = tmp; - } - -@@ -458,7 +532,30 @@ void kernel_flash_attn_ext_impl( - // O = O + (Q*K^T)*V - { - // we can read directly from global memory -- if (is_same::value) { -+ if (is_same::value && FC_flash_attn_ext_has_indices) { -+ const short col = tiisg%8; -+ const short row = tiisg/8; -+ for (short cc = 0; cc < C/8; ++cc) { -+ s8x8_t vs; -+ simdgroup_load(vs, ss + 8*cc, SH, 0, false); -+ for (short block = sgitg; block < DV/8; block += NSG) { -+ FOR_UNROLL (short part = 0; part < 2; ++part) { -+ const short r = row + 4*part; -+ const int physical = flash_attn_ext_indexed_physical(args, pidx, n_kv, ic + 8*cc + r); -+ sv[8*r + col] = physical < 0 ? v_t(0) : -+ ((device const v_t *) (v + physical*args.nb21))[8*block + col]; -+ } -+ simdgroup_barrier(mem_flags::mem_threadgroup); -+ v8x8_t mv; -+ o8x8_t lo; -+ simdgroup_load(mv, sv, 8); -+ simdgroup_load(lo, so + 8*block, PV); -+ simdgroup_multiply_accumulate(lo, vs, mv, lo); -+ simdgroup_store(lo, so + 8*block, PV); -+ simdgroup_barrier(mem_flags::mem_threadgroup); -+ } -+ } -+ } else if (is_same::value) { - static_assert(PV8 % NSG == 0, ""); - - constexpr short NO = PV8/NSG; -@@ -545,13 +642,20 @@ void kernel_flash_attn_ext_impl( - simdgroup_load(vs, ss + 8*cc, SH, 0, false); - - for (short ii = 4*sgitg; ii < DV16; ii += 4*NSG) { -- device const vd4x4_t * pv4x4 = (device const vd4x4_t *) (v + ((ic + 8*cc + ty)*args.nb21)); -+ const int logical = ic + 8*cc + ty; -+ const int physical = FC_flash_attn_ext_has_indices ? -+ flash_attn_ext_indexed_physical(args, pidx, n_kv, logical) : logical; -+ device const vd4x4_t * pv4x4 = (device const vd4x4_t *) (v + max(physical, 0)*args.nb21); - - if (DV16%4 == 0) { - // no need for bound checks - { - v4x4_t tmp; -- deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); -+ if (physical >= 0) { -+ deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); -+ } else { -+ tmp = v4x4_t(0); -+ } - sv4x4[4*ty + tx] = tmp; - } - -@@ -575,7 +679,11 @@ void kernel_flash_attn_ext_impl( - } else { - if (ii + tx < DV16) { - v4x4_t tmp; -- deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); -+ if (physical >= 0) { -+ deq_v(pv4x4 + (ii + tx)/nl_v, (ii + tx)%nl_v, tmp); -+ } else { -+ tmp = v4x4_t(0); -+ } - sv4x4[4*ty + tx] = tmp; - } - -@@ -692,16 +800,22 @@ kernel void kernel_flash_attn_ext( - device const char * pad, - device const char * blk, - device char * dst, -+ device const char * indices, -+ device const char * lengths, - threadgroup half * shmem_f16 [[threadgroup(0)]], - uint3 tgpig[[threadgroup_position_in_grid]], - ushort tiisg[[thread_index_in_simdgroup]], - ushort sgitg[[simdgroup_index_in_threadgroup]]) { - #define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C --#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg -+#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, indices, lengths, shmem_f16, tgpig, tiisg, sgitg - switch (FC_flash_attn_ext_nsg) { -- // note: disabled cases to reduce library load time -- //case 1: kernel_flash_attn_ext_impl(FWD_ARGS); break; -- //case 2: kernel_flash_attn_ext_impl(FWD_ARGS); break; -+ // Indexed gathers may need fewer simdgroups to fit their tile scratch. -+ case 1: -+ if (FC_flash_attn_ext_has_indices) { kernel_flash_attn_ext_impl(FWD_ARGS); } -+ break; -+ case 2: -+ if (FC_flash_attn_ext_has_indices) { kernel_flash_attn_ext_impl(FWD_ARGS); } -+ break; - case 4: kernel_flash_attn_ext_impl(FWD_ARGS); break; - case 8: kernel_flash_attn_ext_impl(FWD_ARGS); break; - } -diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal -index 46270ba4b..4ef22227c 100644 ---- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal -+++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal -@@ -13,6 +13,7 @@ constant int32_t FC_flash_attn_ext_vec_ns20 [[function_constant(FC_FLASH_ATTN_EX - constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 22)]]; - constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; - constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; -+constant bool FC_flash_attn_ext_vec_has_indices [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; - template< - typename q4_t, // query types in shared memory - typename k4_t, // key types in shared memory -@@ -43,6 +44,7 @@ kernel void kernel_flash_attn_ext_vec( - device const char * pad, - device char * dst, - device const char * idx, -+ device const char * lengths, - threadgroup half * shmem_f16 [[threadgroup(0)]], - uint3 tgpig[[threadgroup_position_in_grid]], - ushort tiisg[[thread_index_in_simdgroup]], -@@ -160,7 +162,15 @@ kernel void kernel_flash_attn_ext_vec( - // sparse indices: the list of finite mask entries per query row - // the sparse path requires Q == 1 (enforced by the host) - device const int * pidx = nullptr; -- if (FC_flash_attn_ext_vec_has_sparse) { -+ int n_kv = args.ne11; -+ if (FC_flash_attn_ext_vec_has_indices) { -+ const int i1 = iq1%args.ne51; -+ const int i2 = iq2%args.ne52; -+ const int i3 = iq3%args.ne53; -+ pidx = (device const int *) (idx + i1*args.nb51 + i2*args.nb52 + i3*args.nb53); -+ const int count = *((device const int *) (lengths + i1*args.nb61 + i2*args.nb62 + i3*args.nb63)); -+ n_kv = clamp(count, 0, args.n_kv_indices); -+ } else if (FC_flash_attn_ext_vec_has_sparse) { - pidx = (device const int *) idx + - ((int64_t)(iq3%args.ne33)*args.ne32 + (iq2%args.ne32))*args.ne31*args.n_kv_max_padded + (iq1%args.ne31)*args.n_kv_max_padded; - } -@@ -181,7 +191,7 @@ kernel void kernel_flash_attn_ext_vec( - // each simdgroup handles blocks of Q rows and C columns - for (int ic0 = iwg*NSG + sgitg; ; ic0 += NWG*NSG) { - int ic = ic0*C; -- if (ic >= args.ne11) { -+ if (ic >= n_kv) { - break; - } - -@@ -227,7 +237,14 @@ kernel void kernel_flash_attn_ext_vec( - FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { - const short i = ii*NW + tiisg; - -- spidx[i] = pidx[ic + i]; -+ int physical = -1; -+ if (!FC_flash_attn_ext_vec_has_indices || ic + i < n_kv) { -+ physical = pidx[ic + i]; -+ } -+ if (FC_flash_attn_ext_vec_has_indices && (physical < 0 || physical >= args.n_kv_physical)) { -+ physical = -1; -+ } -+ spidx[i] = physical; - } - simdgroup_barrier(mem_flags::mem_threadgroup); - } -@@ -237,7 +254,7 @@ kernel void kernel_flash_attn_ext_vec( - FOR_UNROLL (short qq = 0; qq < Q; ++qq) { - const int i11 = spidx[tiisg]; - if ((iq1*Q + qq) < args.ne01 && i11 >= 0) { -- sm[qq*C + tiisg] = pm[qq][i11]; -+ sm[qq*C + tiisg] = pm[qq][FC_flash_attn_ext_vec_has_indices ? ic + tiisg : i11]; - } else { - sm[qq*C + tiisg] = -MAXHALF; - } -@@ -253,7 +270,9 @@ kernel void kernel_flash_attn_ext_vec( - } - } else { - FOR_UNROLL (short qq = 0; qq < Q; ++qq) { -- if ((iq1*Q + qq) >= args.ne01) { -+ if (FC_flash_attn_ext_vec_has_indices) { -+ sm[qq*C + tiisg] = (iq1*Q + qq) < args.ne01 && spidx[tiisg] >= 0 ? 0.0h : -MAXHALF; -+ } else if ((iq1*Q + qq) >= args.ne01) { - sm[qq*C + tiisg] = -MAXHALF; - } - } -diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp -index 17ceacc7a..a0f87bebe 100644 ---- a/ggml/src/ggml-opencl/ggml-opencl.cpp -+++ b/ggml/src/ggml-opencl/ggml-opencl.cpp -@@ -9402,6 +9402,9 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te - case GGML_OP_MEAN: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_FLASH_ATTN_EXT: { -+ if (op->src[5]) { -+ return false; -+ } - #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { - return true; -diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp -index 22b2f45e2..89d727ab3 100644 ---- a/ggml/src/ggml-openvino/ggml-openvino.cpp -+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp -@@ -1761,6 +1761,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { - - static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(ggml_backend_dev_t dev, const ggml_tensor * op) { - GGML_ASSERT(dev->reg != nullptr); -+ if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { -+ return {false, "request-indexed attention is not supported"}; -+ } - - ggml_backend_openvino_device_context * dev_ctx = (ggml_backend_openvino_device_context *) dev->context; - if (dev_ctx->ov_name != ggml_openvino_get_device_name()) { -diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp -index 6759af0ed..e0d4d3342 100644 ---- a/ggml/src/ggml-sycl/ggml-sycl.cpp -+++ b/ggml/src/ggml-sycl/ggml-sycl.cpp -@@ -7178,7 +7178,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons - case GGML_OP_SOLVE_TRI: - return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; - case GGML_OP_FLASH_ATTN_EXT: -- return ggml_sycl_flash_attn_ext_supported(device, op); -+ return !op->src[5] && ggml_sycl_flash_attn_ext_supported(device, op); - default: - return false; - } -diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp -index 436bfe3bb..065a27b2a 100644 ---- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp -+++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp -@@ -15569,6 +15569,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm - } - case GGML_OP_FLASH_ATTN_EXT: - { -+ if (op->src[5]) { -+ return false; -+ } - bool coopmat2 = device->coopmat2; - uint32_t HSK = op->src[1]->ne[0]; - uint32_t HSV = op->src[2]->ne[0]; -diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp -index 15e6c784b..6400077b9 100644 ---- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp -+++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp -@@ -4580,7 +4580,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const - { - // conservative support checks for whether the more resource-intensive shader paths - // can be used, to avoid cases where flash_attn is assigned to the CPU later on -- supports_op = src0->type == GGML_TYPE_F32 && -+ supports_op = !op->src[5] && src0->type == GGML_TYPE_F32 && - (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || - src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && - (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || -diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c -index 01dc8d05c..d970209bf 100644 ---- a/ggml/src/ggml.c -+++ b/ggml/src/ggml.c -@@ -5516,20 +5516,40 @@ struct ggml_tensor * ggml_arange( - - // ggml_flash_attn_ext - --struct ggml_tensor * ggml_flash_attn_ext( -+static struct ggml_tensor * ggml_flash_attn_ext_impl( - struct ggml_context * ctx, - struct ggml_tensor * q, - struct ggml_tensor * k, - struct ggml_tensor * v, - struct ggml_tensor * mask, -+ struct ggml_tensor * indices, -+ struct ggml_tensor * lengths, - float scale, - float max_bias, - float logit_softcap) { - GGML_ASSERT(ggml_can_mul_mat(k, q)); - // TODO: check if vT can be multiplied by (k*qT) - -- GGML_ASSERT(q->ne[3] == k->ne[3]); -- GGML_ASSERT(q->ne[3] == v->ne[3]); -+ GGML_ASSERT((indices != NULL) == (lengths != NULL)); -+ GGML_ASSERT(q->ne[3] == k->ne[3] || (indices && k->ne[3] == 1)); -+ GGML_ASSERT(q->ne[3] == v->ne[3] || (indices && v->ne[3] == 1)); -+ -+ if (indices) { -+ GGML_ASSERT(indices->type == GGML_TYPE_I32 && lengths->type == GGML_TYPE_I32); -+ GGML_ASSERT(indices->ne[0] > 0 && lengths->ne[0] == 1); -+ GGML_ASSERT(k->ne[1] == v->ne[1]); -+ GGML_ASSERT(q->nb[0] == ggml_type_size(q->type)); -+ GGML_ASSERT(k->nb[0] == ggml_type_size(k->type)); -+ GGML_ASSERT(v->nb[0] == ggml_type_size(v->type)); -+ GGML_ASSERT(ggml_is_contiguous(indices) && ggml_is_contiguous(lengths)); -+ for (int d = 1; d < GGML_MAX_DIMS; ++d) { -+ GGML_ASSERT(indices->ne[d] > 0); -+ GGML_ASSERT(q->ne[d] % indices->ne[d] == 0); -+ GGML_ASSERT(lengths->ne[d] == indices->ne[d]); -+ } -+ GGML_ASSERT(mask == NULL || mask->ne[0] == indices->ne[0]); -+ GGML_ASSERT(mask == NULL || mask->ne[1] >= q->ne[1]); -+ } - - if (mask) { - GGML_ASSERT(mask->type == GGML_TYPE_F16); -@@ -5556,10 +5576,28 @@ struct ggml_tensor * ggml_flash_attn_ext( - result->src[1] = k; - result->src[2] = v; - result->src[3] = mask; -+ result->src[5] = indices; -+ result->src[6] = lengths; - - return result; - } - -+struct ggml_tensor * ggml_flash_attn_ext( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, struct ggml_tensor * k, struct ggml_tensor * v, -+ struct ggml_tensor * mask, float scale, float max_bias, float logit_softcap) { -+ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, NULL, NULL, scale, max_bias, logit_softcap); -+} -+ -+struct ggml_tensor * ggml_flash_attn_ext_indexed( -+ struct ggml_context * ctx, -+ struct ggml_tensor * q, struct ggml_tensor * k, struct ggml_tensor * v, -+ struct ggml_tensor * mask, struct ggml_tensor * indices, struct ggml_tensor * lengths, -+ float scale, float max_bias, float logit_softcap) { -+ GGML_ASSERT(indices && lengths); -+ return ggml_flash_attn_ext_impl(ctx, q, k, v, mask, indices, lengths, scale, max_bias, logit_softcap); -+} -+ - - void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, -diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index d7d61a2b7..3a5d04693 100644 ---- a/src/CMakeLists.txt -+++ b/src/CMakeLists.txt -@@ -19,10 +19,12 @@ set(LLAMA_CORE_SOURCES - llama-cparams.cpp - llama-grammar.cpp - llama-graph.cpp -+ llama-graph-kv-read.cpp - llama-hparams.cpp - llama-impl.cpp - llama-io.cpp - llama-kv-cache.cpp -+ llama-kv-read.cpp - llama-kv-cache-iswa.cpp - llama-kv-cache-dsa.cpp - llama-kv-cache-dsa-iswa.cpp -diff --git a/src/llama-graph-kv-read.cpp b/src/llama-graph-kv-read.cpp -new file mode 100644 -index 000000000..ca21c90c0 ---- /dev/null -+++ b/src/llama-graph-kv-read.cpp -@@ -0,0 +1,134 @@ -+#include "llama-graph.h" -+ -+#include "llama-cparams.h" -+#include "llama-kv-cache.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+ -+bool llm_graph_context::supports_indexed_attn(const ggml_tensor * node, -+ const ggml_tensor * storage) const { -+ while (storage->view_src) { -+ storage = storage->view_src; -+ } -+ if (storage->buffer) { -+ const auto type = ggml_backend_buffer_get_type(storage->buffer); -+ const auto device = ggml_backend_buft_get_device(type); -+ if (device) { -+ return ggml_backend_dev_supports_op(device, node); -+ } -+ // Generic CPU and mapped host buffers have no device owner. Resolve -+ // their capability through the scheduler's CPU backend, without -+ // admitting unsupported GPU-owned storage onto a CPU copy path. -+ if (!ggml_backend_buft_is_host(type) || !sched) { -+ return false; -+ } -+ for (int i = 0; i < ggml_backend_sched_get_n_backends(sched); ++i) { -+ const auto backend = ggml_backend_sched_get_backend(sched, i); -+ const auto backend_device = ggml_backend_get_device(backend); -+ if (backend_device && ggml_backend_dev_type(backend_device) == GGML_BACKEND_DEVICE_TYPE_CPU && -+ ggml_backend_supports_op(backend, node)) { -+ return true; -+ } -+ } -+ return false; -+ } -+ // Unallocated planning tensors have no buffer owner yet. Use the normal -+ // scheduler's preferred compute backend for the same capability query. -+ return sched && ggml_backend_sched_get_n_backends(sched) > 0 && -+ ggml_backend_supports_op(ggml_backend_sched_get_backend(sched, 0), node); -+} -+ -+static llama_kv_read_plan make_read_plan(const llm_graph_input_attn_kv &, -+ const llama_ubatch &) { -+ // Compact request indexing changes MMA query grouping and KV reduction -+ // partitions. It has not met the full-model baseline arithmetic contract, -+ // including with a fresh uncached context. Keep the ordinary graph -+ // until an indexed layout preserves that contract. The public indexed -+ // operator remains independently available and tested. -+ return {}; -+} -+ -+void llm_graph_input_attn_kv::build_read_inputs(ggml_context * ctx, const llama_ubatch & ubatch) { -+ read_plan = make_read_plan(*this, ubatch); -+ if (!read_plan) { -+ return; -+ } -+ self_read_indices = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, -+ read_plan.logical_extent, 1, 1, read_plan.request_count); -+ self_read_lengths = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, -+ 1, 1, 1, read_plan.request_count); -+ self_read_mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, -+ read_plan.logical_extent, read_plan.queries_per_request, 1, read_plan.request_count); -+ ggml_set_input(self_read_indices); -+ ggml_set_input(self_read_lengths); -+ ggml_set_input(self_read_mask); -+ ggml_set_name(self_read_indices, "attn_inp_read_indices"); -+ ggml_set_name(self_read_lengths, "attn_inp_read_lengths"); -+ ggml_set_name(self_read_mask, "attn_inp_read_mask"); -+} -+ -+bool llm_graph_input_attn_kv::can_reuse_read_inputs(const llama_ubatch & ubatch) { -+ auto next = make_read_plan(*this, ubatch); -+ if (static_cast(next) != static_cast(read_plan)) { -+ return false; -+ } -+ if (next.logical_extent != read_plan.logical_extent || -+ next.queries_per_request != read_plan.queries_per_request || -+ next.request_count != read_plan.request_count || -+ next.physical_extent != read_plan.physical_extent) { -+ return false; -+ } -+ read_plan = std::move(next); -+ return true; -+} -+ -+void llm_graph_input_attn_kv::set_read_inputs(const llama_ubatch & ubatch) { -+ if (!read_plan) { -+ return; -+ } -+ if (self_read_indices->buffer) { -+ ggml_backend_tensor_set(self_read_indices, read_plan.indices.data(), 0, -+ read_plan.indices.size() * sizeof(int32_t)); -+ } -+ if (self_read_lengths->buffer) { -+ ggml_backend_tensor_set(self_read_lengths, read_plan.lengths.data(), 0, -+ read_plan.lengths.size() * sizeof(int32_t)); -+ } -+ if (!self_read_mask->buffer) { -+ return; -+ } -+ -+ const uint32_t extent = read_plan.logical_extent; -+ const uint32_t queries = read_plan.queries_per_request; -+ std::vector mask(ggml_nelements(self_read_mask)); -+ const ggml_fp16_t drop = ggml_fp32_to_fp16(-INFINITY); -+ const ggml_fp16_t keep = ggml_fp32_to_fp16(0.0f); -+ std::fill(mask.begin(), mask.end(), drop); -+ for (uint32_t request = 0; request < read_plan.request_count; ++request) { -+ const auto * begin = read_plan.positions.data() + static_cast(request) * extent; -+ const auto * end = begin + read_plan.lengths[request]; -+ for (uint32_t query = 0; query < queries; ++query) { -+ const llama_pos position = ubatch.pos[request * queries + query]; -+ auto * row = mask.data() + (static_cast(request) * queries + query) * extent; -+ if (hparams.f_max_alibi_bias <= 0) { -+ const auto * visible = std::upper_bound(begin, end, position); -+ std::fill(row, row + (visible - begin), keep); -+ continue; -+ } -+ for (int32_t slot = 0; slot < read_plan.lengths[request]; ++slot) { -+ const llama_pos key_position = read_plan.positions[request * extent + slot]; -+ if (key_position > position) { -+ break; -+ } -+ const float bias = hparams.f_max_alibi_bias > 0 ? -+ -static_cast(position - key_position) : 0.0f; -+ row[slot] = ggml_fp32_to_fp16(bias); -+ } -+ } -+ } -+ ggml_backend_tensor_set(self_read_mask, mask.data(), 0, mask.size() * sizeof(ggml_fp16_t)); -+} -diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index ec6e4d075..a91e2737c 100644 ---- a/src/llama-graph.cpp -+++ b/src/llama-graph.cpp -@@ -591,6 +591,8 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { - mctx->set_input_kq_mask(self_kq_mask, ubatch, cparams.causal_attn); - } - -+ set_read_inputs(*ubatch); -+ - if (self_k_rot && self_k_rot->buffer) { - mctx->set_input_k_rot(self_k_rot); - } -@@ -601,19 +603,23 @@ void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { - } - - bool llm_graph_input_attn_kv::can_reuse(const llm_graph_params & params) { -- const auto * mctx = static_cast(params.mctx); -+ return can_reuse_attn(static_cast(params.mctx), -+ params.ubatch, params.cparams); -+} - -- this->mctx = mctx; -+bool llm_graph_input_attn_kv::can_reuse_attn(const llama_kv_cache_context * context, -+ const llama_ubatch & ubatch, const llama_cparams & params) { -+ mctx = context; - -- bool res = true; -+ bool res = can_reuse_read_inputs(ubatch); - - if (self_k_idxs && self_k_idxs->buffer) { -- res &= self_k_idxs->ne[0] == params.ubatch.n_tokens; -+ res &= self_k_idxs->ne[0] == ubatch.n_tokens; - } - //res &= self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there - - if (self_kq_mask && self_kq_mask->buffer) { -- res &= can_reuse_kq_mask(self_kq_mask, mctx, params.ubatch, params.cparams); -+ res &= can_reuse_kq_mask(self_kq_mask, mctx, ubatch, params); - } - - return res; -@@ -1263,23 +1269,8 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { - } - - void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { -- const auto * attn_ctx = mctx->get_attn(); -- -- // These tensors may not be allocated for staged slices that contain only -- // recurrent layers. -- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { -- attn_ctx->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); -- attn_ctx->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); -- attn_ctx->set_input_kq_mask(inp_attn->self_kq_mask, ubatch, cparams.causal_attn); -- } -- -- if (inp_attn->self_k_rot) { -- attn_ctx->set_input_k_rot(inp_attn->self_k_rot); -- } -- -- if (inp_attn->self_v_rot) { -- attn_ctx->set_input_v_rot(inp_attn->self_v_rot); -- } -+ inp_attn->mctx = mctx->get_attn(); -+ inp_attn->set_input(ubatch); - - const int64_t n_rs = mctx->get_recr()->get_n_rs(); - -@@ -1299,16 +1290,7 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { - - this->mctx = mctx; - -- bool res = true; -- -- if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { -- res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; -- } -- //res &= inp_attn->self_v_idxs->ne[0] == params.ubatch.n_tokens; // TODO: need to move this to the unified cache and check there -- -- if (inp_attn->self_kq_mask && inp_attn->self_kq_mask->buffer) { -- res &= can_reuse_kq_mask(inp_attn->self_kq_mask, mctx->get_attn(), params.ubatch, params.cparams); -- } -+ bool res = inp_attn->can_reuse_attn(mctx->get_attn(), params.ubatch, params.cparams); - - if (inp_rs->s_copy && inp_rs->s_copy->buffer) { - res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); -@@ -1967,6 +1949,9 @@ void llm_graph_context::request_inputs(llm_graph_input_attn_kv * input) const { - request_input(input->self_k_idxs, "attention.key_indices"); - request_input(input->self_v_idxs, "attention.value_indices"); - request_input(input->self_kq_mask, "attention.mask"); -+ request_input(input->self_read_indices, "attention.read_indices"); -+ request_input(input->self_read_lengths, "attention.read_lengths"); -+ request_input(input->self_read_mask, "attention.read_mask"); - request_input(input->self_k_rot, "attention.key_rotation"); - request_input(input->self_v_rot, "attention.value_rotation"); - } -@@ -3384,11 +3369,17 @@ ggml_tensor * llm_graph_context::build_attn_mha( - ggml_tensor * v_mla, - int64_t n_kv_max, - float kq_scale, -- int il) const { -+ int il, -+ ggml_tensor * read_indices, -+ ggml_tensor * read_lengths, -+ ggml_tensor * dense_mask) const { -+ ggml_tensor * original_q = q; -+ ggml_tensor * original_k = k; -+ ggml_tensor * original_v = v; - const bool v_trans = v->nb[1] > v->nb[2]; - - // split the batch into streams if needed -- const auto n_stream = k->ne[3]; -+ const auto n_stream = read_indices ? read_indices->ne[3] : k->ne[3]; - - // the stream dim steps over one stream's worth of dim-2 (tokens): (ne[2]/n_stream) rows of stride nb[2]. - // q->nb[3]/n_stream only equals that for a contiguous q; nope-only MLA (glm5-next) passes a permuted -@@ -3410,16 +3401,26 @@ ggml_tensor * llm_graph_context::build_attn_mha( - } - - // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) -- if (k->type == GGML_TYPE_F32) { -+ if (!read_indices && k->type == GGML_TYPE_F32) { - k = ggml_cast(ctx0, k, GGML_TYPE_F16); - } - -- if (v->type == GGML_TYPE_F32) { -+ if (!read_indices && v->type == GGML_TYPE_F32) { - v = ggml_cast(ctx0, v, GGML_TYPE_F16); - } - -- cur = ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, kq_scale, hparams.f_max_alibi_bias, -- hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); -+ const float softcap = hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f; -+ cur = read_indices ? ggml_flash_attn_ext_indexed(ctx0, q, k, v, fa_mask, -+ read_indices, read_lengths, kq_scale, hparams.f_max_alibi_bias, softcap) : -+ ggml_flash_attn_ext(ctx0, q, k, v, fa_mask, -+ kq_scale, hparams.f_max_alibi_bias, softcap); -+ if (read_indices && !supports_indexed_attn(cur, original_k)) { -+ // Keep unsupported devices and K/V types on their existing native -+ // attention path, rather than copying the shared pool to the CPU. -+ GGML_ASSERT(dense_mask); -+ return build_attn_mha(original_q, original_k, original_v, kq_b, dense_mask, -+ sinks, v_mla, n_kv_max, kq_scale, il); -+ } - res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); - - ggml_flash_attn_ext_add_sinks(cur, sinks); -@@ -3626,6 +3627,8 @@ static std::unique_ptr build_attn_inp_kv_impl( - inp->self_kq_mask_cnv = inp->self_kq_mask; - } - -+ inp->build_read_inputs(ctx0, ubatch); -+ - inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); - inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); - -@@ -3707,7 +3710,11 @@ ggml_tensor * llm_graph_context::build_attn( - - ggml_tensor * kq_mask = inp->get_kq_mask(); - -- ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); -+ // Bias-producing builders retain their existing dense mask and semantics. -+ const bool indexed = inp->self_read_indices != nullptr && kq_b == nullptr && v_mla == nullptr; -+ ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, -+ indexed ? inp->self_read_mask : kq_mask, sinks, v_mla, 0, kq_scale, il, -+ indexed ? inp->self_read_indices : nullptr, indexed ? inp->self_read_lengths : nullptr, kq_mask); - cb(cur, "kqv_out", il); - - if (inp->self_v_rot) { -diff --git a/src/llama-graph.h b/src/llama-graph.h -index a4ffee4e5..f32b6ef58 100644 ---- a/src/llama-graph.h -+++ b/src/llama-graph.h -@@ -4,6 +4,7 @@ - #include "llama-batch.h" - #include "llama-hparams.h" - #include "llama-adapter.h" -+#include "llama-kv-read.h" - - #include "skippy/block_boundaries.h" - #include "skippy/graph_identity.h" -@@ -430,6 +431,12 @@ public: - void set_input(const llama_ubatch * ubatch) override; - - bool can_reuse(const llm_graph_params & params) override; -+ bool can_reuse_attn(const llama_kv_cache_context * context, const llama_ubatch & ubatch, -+ const llama_cparams & params); -+ -+ void build_read_inputs(ggml_context * ctx, const llama_ubatch & ubatch); -+ void set_read_inputs(const llama_ubatch & ubatch); -+ bool can_reuse_read_inputs(const llama_ubatch & ubatch); - - ggml_tensor * get_k_idxs() const { return self_k_idxs; } - ggml_tensor * get_v_idxs() const { return self_v_idxs; } -@@ -442,6 +449,13 @@ public: - ggml_tensor * self_kq_mask = nullptr; // F32/F16 [n_kv, n_batch/n_stream, 1, n_stream] - ggml_tensor * self_kq_mask_cnv = nullptr; // [n_kv, n_batch/n_stream, 1, n_stream] - -+ // Optional logical reads into the existing physical K/V storage. The dense -+ // mask remains available for attention nodes with additional bias semantics. -+ ggml_tensor * self_read_indices = nullptr; -+ ggml_tensor * self_read_lengths = nullptr; -+ ggml_tensor * self_read_mask = nullptr; -+ llama_kv_read_plan read_plan; -+ - // note: assumes v_rot^2 == I - ggml_tensor * self_k_rot = nullptr; - ggml_tensor * self_v_rot = nullptr; -@@ -1433,7 +1447,12 @@ struct llm_graph_context { - ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] - int64_t n_kv_max, - float kq_scale, -- int il) const; -+ int il, -+ ggml_tensor * read_indices = nullptr, -+ ggml_tensor * read_lengths = nullptr, -+ ggml_tensor * dense_mask = nullptr) const; -+ -+ bool supports_indexed_attn(const ggml_tensor * node, const ggml_tensor * storage) const; - - llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; - -diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index 80edf6865..8a2e09270 100644 ---- a/src/llama-kv-cache.h -+++ b/src/llama-kv-cache.h -@@ -15,6 +15,7 @@ struct llama_model; - struct llama_context; - struct skippy_kv_page_desc; - struct skippy_cachegen_record_v1; -+struct llama_kv_read_plan; - - // - // llama_kv_cache -@@ -466,6 +467,7 @@ public: - - uint32_t get_n_kv() const; - uint32_t get_n_kv_pos_contiguous() const; -+ llama_kv_read_plan get_read_plan(const llama_ubatch & ubatch) const; - - ggml_type type_k() const; - ggml_type type_v() const; -diff --git a/src/llama-kv-read.cpp b/src/llama-kv-read.cpp -new file mode 100644 -index 000000000..934d3b733 ---- /dev/null -+++ b/src/llama-kv-read.cpp -@@ -0,0 +1,148 @@ -+#include "llama-kv-read.h" -+ -+#include "llama-kv-cache.h" -+ -+#include -+#include -+#include -+ -+namespace { -+ -+struct request_queries { -+ llama_seq_id sequence; -+ uint32_t count = 0; -+ llama_pos max_position = -1; -+}; -+ -+bool scalar_text_positions(const llama_ubatch & ubatch) { -+ if (ubatch.n_pos == 0) { -+ return false; -+ } -+ // Ordinary text can carry multiple rotary-position planes. The batch -+ // allocator expands these to [p, p, p, 0, ...]; spatial inputs retain -+ // independent coordinates and need the existing spatial mask instead. -+ for (uint32_t axis = 1; axis < ubatch.n_pos; ++axis) { -+ for (uint32_t token = 0; token < ubatch.n_tokens; ++token) { -+ const llama_pos expected = axis < 3 ? ubatch.pos[token] : 0; -+ if (ubatch.pos[axis * ubatch.n_tokens + token] != expected) { -+ return false; -+ } -+ } -+ } -+ return true; -+} -+ -+bool query_runs(const llama_ubatch & ubatch, std::vector & requests) { -+ std::set sequences; -+ std::set positions; -+ for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { -+ if (ubatch.n_seq_id[i] != 1 || !ubatch.seq_id[i] || ubatch.pos[i] < 0) { -+ return false; -+ } -+ const llama_seq_id sequence = ubatch.seq_id[i][0]; -+ if (sequence < 0 || sequence >= LLAMA_MAX_SEQ) { -+ return false; -+ } -+ if (requests.empty() || requests.back().sequence != sequence) { -+ // A request must own one contiguous query run, including decode -+ // split_simple batches whose b_equal_seqs flag is false. -+ if (!sequences.insert(sequence).second) { -+ return false; -+ } -+ requests.push_back({sequence}); -+ positions.clear(); -+ } -+ if (!positions.insert(ubatch.pos[i]).second) { -+ return false; -+ } -+ auto & request = requests.back(); -+ ++request.count; -+ request.max_position = std::max(request.max_position, ubatch.pos[i]); -+ } -+ const uint32_t count = requests.front().count; -+ return std::all_of(requests.begin(), requests.end(), [count](const request_queries & request) { -+ return request.count == count; -+ }); -+} -+ -+bool visible_count(const llama_kv_cache & cache, const request_queries & request, -+ uint32_t physical_extent, bool spatial_positions, int32_t & count) { -+ const auto & cells = cache.get_cells(request.sequence); -+ llama_pos previous = -1; -+ count = 0; -+ for (const auto & entry : cells.seq_pos_get(request.sequence)) { -+ if (entry.first > request.max_position) { -+ break; -+ } -+ if (entry.first < 0 || entry.first == previous || entry.second >= physical_extent || -+ count == std::numeric_limits::max()) { -+ return false; -+ } -+ if (spatial_positions) { -+ const auto & spatial = cells.ext_get(entry.second); -+ if (spatial.x != entry.first || spatial.y != entry.first) { -+ return false; -+ } -+ } -+ previous = entry.first; -+ ++count; -+ } -+ return true; -+} -+ -+} // namespace -+ -+llama_kv_read_plan llama_kv_cache_context::get_read_plan(const llama_ubatch & ubatch) const { -+ if (!kv || kv->get_n_stream() != 1 || kv->get_n_swa() != 0 || -+ ubatch.n_tokens == 0 || ubatch.decision_order || -+ !ubatch.pos || !ubatch.n_seq_id || !ubatch.seq_id) { -+ return {}; -+ } -+ if (!scalar_text_positions(ubatch)) { -+ return {}; -+ } -+ const uint32_t physical_extent = get_n_kv(); -+ if (physical_extent == 0 || physical_extent > static_cast(std::numeric_limits::max())) { -+ return {}; -+ } -+ -+ std::vector requests; -+ if (!query_runs(ubatch, requests)) { -+ return {}; -+ } -+ llama_kv_read_plan plan; -+ plan.physical_extent = physical_extent; -+ plan.lengths.resize(requests.size()); -+ uint32_t max_length = 0; -+ for (size_t i = 0; i < requests.size(); ++i) { -+ if (!visible_count(*kv, requests[i], physical_extent, ubatch.n_pos >= 3, plan.lengths[i])) { -+ return {}; -+ } -+ max_length = std::max(max_length, static_cast(plan.lengths[i])); -+ } -+ constexpr uint32_t alignment = 256; -+ if (max_length > static_cast(std::numeric_limits::max()) - (alignment - 1)) { -+ return {}; -+ } -+ plan.logical_extent = std::max(alignment, ((max_length + alignment - 1) / alignment) * alignment); -+ if (requests.size() > std::numeric_limits::max() / plan.logical_extent) { -+ return {}; -+ } -+ const size_t elements = requests.size() * plan.logical_extent; -+ plan.indices.assign(elements, -1); -+ plan.positions.assign(elements, -1); -+ for (size_t i = 0; i < requests.size(); ++i) { -+ size_t destination = i * plan.logical_extent; -+ for (const auto & entry : kv->get_cells(requests[i].sequence).seq_pos_get(requests[i].sequence)) { -+ if (entry.first > requests[i].max_position) { -+ break; -+ } -+ plan.indices[destination] = static_cast(entry.second); -+ plan.positions[destination] = entry.first; -+ ++destination; -+ } -+ } -+ plan.queries_per_request = requests.front().count; -+ plan.request_count = static_cast(requests.size()); -+ return plan; -+} -diff --git a/src/llama-kv-read.h b/src/llama-kv-read.h -new file mode 100644 -index 000000000..ca21eae3a ---- /dev/null -+++ b/src/llama-kv-read.h -@@ -0,0 +1,20 @@ -+#pragma once -+ -+#include "llama.h" -+ -+#include -+#include -+ -+// Request-major logical token positions and their shared physical attention -+// cells. Padding is -1; lengths, not physical pool occupancy, bound each read. -+struct llama_kv_read_plan { -+ uint32_t queries_per_request = 0; -+ uint32_t request_count = 0; -+ uint32_t physical_extent = 0; -+ uint32_t logical_extent = 0; -+ std::vector indices; -+ std::vector positions; -+ std::vector lengths; -+ -+ explicit operator bool() const { return request_count != 0; } -+}; -diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index def0ea7a6..0e279f1bc 100644 ---- a/tests/CMakeLists.txt -+++ b/tests/CMakeLists.txt -@@ -345,6 +345,8 @@ endif() - - llama_build(test-backend-ops.cpp LINK ggml) - -+llama_build_and_test(test-flash-attn-indexed.cpp LINK ggml ARGS --backend CPU) -+ - llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) - llama_build_and_test(test-model-load-cancel.cpp LABEL "model") - llama_build_and_test(test-autorelease.cpp LABEL "model") -diff --git a/tests/test-flash-attn-indexed.cpp b/tests/test-flash-attn-indexed.cpp -new file mode 100644 -index 000000000..813953ac1 ---- /dev/null -+++ b/tests/test-flash-attn-indexed.cpp -@@ -0,0 +1,378 @@ -+#include "ggml.h" -+#include "ggml-alloc.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+namespace { -+constexpr int64_t kv_heads = 2; -+constexpr int64_t requests = 4; -+// Match test_flash_attn_ext::max_nmse_err in test-backend-ops.cpp. -+constexpr double max_nmse = 5e-4; -+ -+struct attention_case { -+ int64_t queries; -+ int64_t logical_rows; -+ bool mask; -+ bool sinks; -+ bool query_local = false; -+ bool strided_query = false; -+ ggml_type type_k = GGML_TYPE_F16; -+ ggml_type type_v = GGML_TYPE_F16; -+ int64_t dk = 256; -+ int64_t dv = 256; -+ float max_bias = 1.5f; -+ int64_t heads = 8; -+}; -+ -+void require(bool condition, const char * message) { -+ if (!condition) { -+ throw std::runtime_error(message); -+ } -+} -+ -+struct inputs { -+ const attention_case spec; -+ const int64_t physical_rows; -+ const int64_t mask_queries; -+ const int64_t index_queries; -+ std::vector q; -+ const size_t row_k; -+ const size_t row_v; -+ std::vector k, v, logical_k, logical_v; -+ std::vector mask; -+ std::vector indices, lengths; -+ std::vector sinks; -+ -+ explicit inputs(attention_case value) : spec(value), physical_rows(2*value.logical_rows + 257), -+ mask_queries((value.queries + 63)/64*64), index_queries(value.query_local ? value.queries : 1), -+ q(value.dk*value.queries*value.heads*requests), -+ row_k(ggml_row_size(value.type_k, value.dk)), row_v(ggml_row_size(value.type_v, value.dv)), -+ k(row_k*physical_rows*kv_heads), v(row_v*physical_rows*kv_heads), -+ logical_k(row_k*value.logical_rows*kv_heads*requests), -+ logical_v(row_v*value.logical_rows*kv_heads*requests), -+ mask(value.logical_rows*mask_queries*requests), -+ indices(value.logical_rows*index_queries*requests), lengths(index_queries*requests), sinks(value.heads) { -+ std::mt19937 random(34791); -+ std::uniform_real_distribution sample(-0.75f, 0.75f); -+ for (float & item : q) { -+ item = sample(random); -+ } -+ std::vector values(std::max(value.dk, value.dv)*physical_rows*kv_heads); -+ for (float & item : values) { -+ item = sample(random); -+ } -+ ggml_quantize_chunk(value.type_k, values.data(), k.data(), 0, physical_rows*kv_heads, value.dk, nullptr); -+ for (float & item : values) { -+ item = sample(random); -+ } -+ ggml_quantize_chunk(value.type_v, values.data(), v.data(), 0, physical_rows*kv_heads, value.dv, nullptr); -+ for (float & item : sinks) { -+ item = sample(random); -+ } -+ } -+ -+ void refresh(int phase) { -+ const int64_t width = spec.logical_rows; -+ std::fill(indices.begin(), indices.end(), -1); -+ std::fill(logical_k.begin(), logical_k.end(), 0); -+ std::fill(logical_v.begin(), logical_v.end(), 0); -+ const std::array counts = phase == 0 ? -+ std::array{0, 31, 65, int32_t(width - 7)} : -+ std::array{65, int32_t(width - 9), 0, 31}; -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t query = 0; query < index_queries; ++query) { -+ const int32_t count = std::max(0, counts[request] - int32_t(query % 3)); -+ lengths[request*index_queries + query] = count; -+ for (int32_t slot = 0; slot < count; ++slot) { -+ // Shared first rows plus interleaved, nonmonotonic physical rows. -+ const int32_t physical = int32_t((slot*37 + (slot < 5 ? 0 : request*53) + phase*101) % physical_rows); -+ indices[(request*index_queries + query)*width + slot] = physical; -+ } -+ } -+ for (int64_t slot = 0; slot < width; ++slot) { -+ const int32_t physical = indices[request*index_queries*width + slot]; -+ if (physical < 0) { -+ continue; -+ } -+ for (int64_t head = 0; head < kv_heads; ++head) { -+ const size_t src = head*physical_rows + physical; -+ const size_t dst = (request*kv_heads + head)*width + slot; -+ // Preserve the exact encoded block bytes, not re-quantized floats. -+ std::copy_n(k.data() + src*row_k, row_k, logical_k.data() + dst*row_k); -+ std::copy_n(v.data() + src*row_v, row_v, logical_v.data() + dst*row_v); -+ } -+ } -+ for (int64_t query = 0; query < mask_queries; ++query) { -+ const int64_t iq = spec.query_local ? std::min(query, spec.queries - 1) : 0; -+ const int32_t count = lengths[request*index_queries + iq]; -+ for (int64_t slot = 0; slot < width; ++slot) { -+ float bias = -std::numeric_limits::infinity(); -+ if (query < spec.queries && slot < count) { -+ bias = spec.mask ? -0.025f*float(slot % 7) : 0.0f; -+ if (spec.mask && slot % 11 == 3) { -+ bias = -std::numeric_limits::infinity(); -+ } -+ } -+ mask[(request*mask_queries + query)*width + slot] = ggml_fp32_to_fp16(bias); -+ } -+ } -+ } -+ } -+}; -+ -+struct graph_fixture { -+ ggml_context * ctx = nullptr; -+ ggml_backend_buffer_t buffer = nullptr; -+ ggml_tensor * q = nullptr; -+ ggml_tensor * k = nullptr; -+ ggml_tensor * v = nullptr; -+ ggml_tensor * mask = nullptr; -+ ggml_tensor * indices = nullptr; -+ ggml_tensor * lengths = nullptr; -+ ggml_tensor * sinks = nullptr; -+ ggml_tensor * output = nullptr; -+ ggml_cgraph * graph = nullptr; -+ const bool indexed; -+ -+ graph_fixture(ggml_backend_t backend, const inputs & data, bool use_indices) : indexed(use_indices) { -+ ggml_init_params params{32*ggml_tensor_overhead() + ggml_graph_overhead_custom(32, false), nullptr, true}; -+ ctx = ggml_init(params); -+ require(ctx != nullptr, "allocate graph context"); -+ if (data.spec.strided_query) { -+ auto storage = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, 2*data.spec.queries, data.spec.heads, requests); -+ q = ggml_view_4d(ctx, storage, data.spec.dk, data.spec.queries, data.spec.heads, requests, -+ 2*storage->nb[1], storage->nb[2], storage->nb[3], 0); -+ } else { -+ q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, data.spec.dk, data.spec.queries, data.spec.heads, requests); -+ } -+ const int64_t rows = indexed ? data.physical_rows : data.spec.logical_rows; -+ const int64_t streams = indexed ? 1 : requests; -+ k = ggml_new_tensor_4d(ctx, data.spec.type_k, data.spec.dk, rows, kv_heads, streams); -+ v = ggml_new_tensor_4d(ctx, data.spec.type_v, data.spec.dv, rows, kv_heads, streams); -+ // Dense reference always masks the padding excluded by indexed lengths. -+ if (!indexed || data.spec.mask) { -+ mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, data.spec.logical_rows, data.mask_queries, 1, requests); -+ } -+ if (indexed) { -+ indices = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, data.spec.logical_rows, data.index_queries, 1, requests); -+ lengths = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, 1, data.index_queries, 1, requests); -+ output = ggml_flash_attn_ext_indexed(ctx, q, k, v, mask, indices, lengths, -+ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, 0.0f); -+ } else { -+ output = ggml_flash_attn_ext(ctx, q, k, v, mask, -+ 1.0f/std::sqrt(float(data.spec.dk)), data.spec.mask ? data.spec.max_bias : 0.0f, 0.0f); -+ } -+ if (data.spec.sinks) { -+ sinks = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, data.spec.heads); -+ ggml_flash_attn_ext_add_sinks(output, sinks); -+ } -+ ggml_prec_set_acc(output, GGML_PREC_F32); -+ require(ggml_backend_supports_op(backend, output), "selected backend does not support indexed test shape"); -+ graph = ggml_new_graph_custom(ctx, 32, false); -+ ggml_build_forward_expand(graph, output); -+ buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); -+ require(buffer != nullptr, "allocate backend graph tensors"); -+ } -+ -+ ~graph_fixture() { -+ ggml_backend_buffer_free(buffer); -+ ggml_free(ctx); -+ } -+ graph_fixture(const graph_fixture &) = delete; -+ graph_fixture & operator=(const graph_fixture &) = delete; -+ -+ std::vector run(ggml_backend_t backend, const inputs & data) { -+ for (int64_t request = 0; request < requests; ++request) { -+ for (int64_t head = 0; head < data.spec.heads; ++head) { -+ for (int64_t query = 0; query < data.spec.queries; ++query) { -+ const size_t offset = request*q->nb[3] + head*q->nb[2] + query*q->nb[1]; -+ const size_t source = ((request*data.spec.heads + head)*data.spec.queries + query)*data.spec.dk; -+ ggml_backend_tensor_set(q, data.q.data() + source, offset, data.spec.dk*sizeof(float)); -+ } -+ } -+ } -+ ggml_backend_tensor_set(k, indexed ? data.k.data() : data.logical_k.data(), 0, ggml_nbytes(k)); -+ ggml_backend_tensor_set(v, indexed ? data.v.data() : data.logical_v.data(), 0, ggml_nbytes(v)); -+ if (mask) { -+ ggml_backend_tensor_set(mask, data.mask.data(), 0, ggml_nbytes(mask)); -+ } -+ if (indices) { -+ ggml_backend_tensor_set(indices, data.indices.data(), 0, ggml_nbytes(indices)); -+ ggml_backend_tensor_set(lengths, data.lengths.data(), 0, ggml_nbytes(lengths)); -+ } -+ if (sinks) { -+ ggml_backend_tensor_set(sinks, data.sinks.data(), 0, ggml_nbytes(sinks)); -+ } -+ require(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS, "compute attention graph"); -+ std::vector result(ggml_nelements(output)); -+ ggml_backend_tensor_get(output, result.data(), 0, ggml_nbytes(output)); -+ return result; -+ } -+}; -+ -+void compare(const std::vector & expected, const std::vector & actual, -+ const inputs & data, const char * backend, int phase) { -+ double maximum_nmse = 0.0; -+ float max_absolute = 0.0f; -+ const size_t request_elements = data.spec.dv*data.spec.heads*data.spec.queries; -+ for (int64_t request = 0; request < requests; ++request) { -+ double error = 0.0, energy = 0.0; -+ for (size_t i = request*request_elements; i < (request + 1)*request_elements; ++i) { -+ require(std::isfinite(expected[i]) && std::isfinite(actual[i]), "non-finite attention output"); -+ const double delta = double(expected[i]) - actual[i]; -+ error += delta*delta; -+ energy += double(expected[i])*expected[i]; -+ max_absolute = std::max(max_absolute, float(std::abs(delta))); -+ } -+ if (energy == 0.0) { -+ require(error == 0.0, "empty request must produce exact zero output"); -+ } else { -+ maximum_nmse = std::max(maximum_nmse, error/energy); -+ require(error/energy <= max_nmse, "indexed attention exceeds existing FA NMSE tolerance"); -+ } -+ } -+ std::printf("PASS backend=%s K=%s V=%s dk=%lld dv=%lld heads=%lld bias=%.2f q=%lld logical=%lld mask=%d sinks=%d query_local=%d strided_q=%d phase=%d max_request_nmse=%.9g max_abs=%.9g\n", -+ backend, ggml_type_name(data.spec.type_k), ggml_type_name(data.spec.type_v), -+ (long long) data.spec.dk, (long long) data.spec.dv, (long long) data.spec.heads, -+ data.spec.mask ? data.spec.max_bias : 0.0f, (long long) data.spec.queries, (long long) data.spec.logical_rows, -+ data.spec.mask, data.spec.sinks, data.spec.query_local, data.spec.strided_query, phase, maximum_nmse, max_absolute); -+} -+ -+void set_threads(ggml_backend_t backend) { -+ const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)); -+ const auto setter = reinterpret_cast( -+ ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads")); -+ if (setter) { -+ setter(backend, 4); -+ } -+} -+ -+// Accept an exact device (e.g. MTL0/CUDA0) or its registry (Metal/CUDA). -+ggml_backend_t open_backend(const char * name) { -+ if (auto exact = ggml_backend_init_by_name(name, nullptr)) { -+ return exact; -+ } -+ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { -+ auto device = ggml_backend_dev_get(i); -+ const auto registry = ggml_backend_dev_backend_reg(device); -+ if (std::strcmp(ggml_backend_reg_name(registry), name) == 0) { -+ return ggml_backend_dev_init(device, nullptr); -+ } -+ } -+ return nullptr; -+} -+ -+void run_case(ggml_backend_t cpu, ggml_backend_t target, attention_case spec) { -+ inputs data(spec); -+ graph_fixture reference(cpu, data, false); -+ graph_fixture indexed(cpu, data, true); -+ std::unique_ptr device; -+ if (target != cpu) { -+ if (ggml_backend_supports_op(target, indexed.output)) { -+ device = std::make_unique(target, data, true); -+ } else { -+ const bool dense_supported = ggml_backend_supports_op(target, reference.output); -+ require(!spec.mask || spec.query_local || !dense_supported, -+ "selected backend must support the canonical masked request-local shape"); -+ std::printf("SKIP optional backend=%s K=%s V=%s q=%lld mask=%d query_local=%d dense_admission=%d: indexed shape explicitly unsupported; CPU verification remains required\n", -+ ggml_backend_name(target), ggml_type_name(spec.type_k), ggml_type_name(spec.type_v), -+ (long long) spec.queries, spec.mask, spec.query_local, dense_supported); -+ } -+ } -+ for (int phase = 0; phase < 2; ++phase) { -+ data.refresh(phase); -+ const auto expected = reference.run(cpu, data); -+ compare(expected, indexed.run(cpu, data), data, ggml_backend_name(cpu), phase); -+ if (device) { -+ compare(expected, device->run(target, data), data, ggml_backend_name(target), phase); -+ } -+ } -+} -+} // namespace -+ -+int main(int argc, char ** argv) { -+ try { -+ require(argc == 1 || (argc == 3 && std::strcmp(argv[1], "--backend") == 0), -+ "usage: test-flash-attn-indexed [--backend DEVICE_NAME]"); -+ ggml_backend_load_all(); -+ using backend_ptr = std::unique_ptr; -+ backend_ptr cpu(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr), ggml_backend_free); -+ require(cpu != nullptr, "CPU reference backend unavailable"); -+ set_threads(cpu.get()); -+ backend_ptr selected(nullptr, ggml_backend_free); -+ if (argc == 3) { -+ selected.reset(open_backend(argv[2])); -+ require(selected != nullptr, "requested backend unavailable"); -+ } else { -+ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)); -+ if (!selected) { -+ selected.reset(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU, nullptr)); -+ } -+ } -+ const bool selected_cpu = selected && -+ ggml_backend_dev_type(ggml_backend_get_device(selected.get())) == GGML_BACKEND_DEVICE_TYPE_CPU; -+ auto target = selected && !selected_cpu ? selected.get() : cpu.get(); -+ std::printf("indexed FA: CPU reference and target=%s; per-request NMSE limit=%.9g\n", ggml_backend_name(target), max_nmse); -+ for (int64_t queries : {1, 4, 31, 32, 64}) { -+ run_case(cpu.get(), target, {queries, 256, true, true}); -+ } -+ run_case(cpu.get(), target, {1, 4352, true, true}); -+ run_case(cpu.get(), target, {4, 256, false, false}); -+ run_case(cpu.get(), target, {31, 256, true, false, true}); -+ run_case(cpu.get(), target, {32, 256, true, true, false, true}); -+ const std::array types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, -+ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}; -+ for (auto type_k : types) { -+ for (auto type_v : types) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, type_k, type_v}); -+ } -+ } -+ } -+ const std::array, 13> head_shapes = {{{32, 32}, {64, 64}, {96, 96}, -+ {96, 64}, {128, 128}, {128, 96}, {192, 192}, {192, 128}, {256, 256}, -+ {320, 256}, {512, 512}, {576, 512}, {128, 64}}}; -+ for (const auto & dimensions : head_shapes) { -+ for (auto type : types) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimensions[0], dimensions[1]}); -+ } -+ } -+ } -+ // CUDA's larger-head kernels require zero ALiBi and admitted GQA tile ratios. -+ const std::array, 5> wide_shapes = {{{192, 128, 16}, -+ {320, 256, 64}, {512, 512, 8}, {576, 512, 8}, {576, 512, 4}}}; -+ for (const auto & dimensions : wide_shapes) { -+ for (auto type : types) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimensions[0], dimensions[1], 0.0f, dimensions[2]}); -+ } -+ } -+ } -+ for (int64_t dimension : {40, 48, 72, 80, 112}) { -+ for (auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { -+ for (int64_t queries : {1, 32}) { -+ run_case(cpu.get(), target, {queries, 256, true, true, false, false, -+ type, type, dimension, dimension}); -+ } -+ } -+ } -+ return 0; -+ } catch (const std::exception & error) { -+ std::fprintf(stderr, "indexed FA test failed: %s\n", error.what()); -+ return 1; -+ } -+} --- -2.56.0 - diff --git a/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch b/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch index 9fb10f9a8a..478cabc824 100644 --- a/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch +++ b/skippy/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch @@ -5,13 +5,14 @@ Subject: [PATCH 13/15] fix(skippy): take the argmax path for temperature-0 chains that can only pick the top logit --- - src/CMakeLists.txt | 3 +- - src/skippy/chat_sampling.cpp | 43 +++++++++++ - src/skippy/runtime_types.h | 4 + - src/skippy/sampling.cpp | 2 + - src/skippy/sampling_argmax.cpp | 136 +++++++++++++++++++++++++++++++++ - src/skippy/sampling_argmax.h | 42 ++++++++++ - 6 files changed, 229 insertions(+), 1 deletion(-) + src/CMakeLists.txt | 3 +- + src/skippy/chat_sampling.cpp | 43 ++++++++ + src/skippy/runtime_types.h | 4 + + src/skippy/sampling.cpp | 2 + + src/skippy/sampling_argmax.cpp | 136 ++++++++++++++++++++++++++ + src/skippy/sampling_argmax.h | 42 ++++++++ + src/skippy/tests/sampling_history.cpp | 110 ++++++++++++++++++++- + 7 files changed, 338 insertions(+), 2 deletions(-) create mode 100644 src/skippy/sampling_argmax.cpp create mode 100644 src/skippy/sampling_argmax.h @@ -19,7 +20,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c7a99d16c..cd2b536f6 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -53,6 +53,7 @@ add_library(llama +@@ -50,6 +50,7 @@ add_library(llama ${LLAMA_CORE_SOURCES} skippy/activation.cpp skippy/activation_layout.cpp @@ -31,8 +32,8 @@ index c7a99d16c..cd2b536f6 100644 target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) target_link_libraries(skippy-sampling-history PRIVATE llama) function(add_skippy_sampling_history_tests family fixture state) -- foreach(mode grammar penalty resident) -+ foreach(mode grammar penalty resident argmax) +- foreach(mode grammar penalty) ++ foreach(mode grammar penalty argmax) add_test(NAME skippy_sampling_history_${family}_${mode} COMMAND skippy-sampling-history "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) @@ -116,7 +117,7 @@ index f44e874d9..46e907aa0 100644 #include "../llama-context.h" #include "../llama-model.h" -@@ -172,6 +173,9 @@ struct skippy_session { +@@ -165,6 +166,9 @@ struct skippy_session { bool sampling_backend_verifying = false; uint64_t sampling_reuse_hit_count = 0; uint64_t sampling_rebuild_count = 0; @@ -336,6 +337,154 @@ index 000000000..d06000f11 + const float * logits, + int32_t n_vocab, + const skippy_argmax_plan & plan); +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index 9e134586f..4100856f3 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -1,5 +1,7 @@ + #include "skippy.h" + #include "../runtime_types.h" ++#include "../sampling_internal.h" ++#include "../sampling_argmax.h" + #include "../runtime_support.h" + #include "llama-model.h" + #include "../../../common/sampling.h" +@@ -287,6 +289,108 @@ void penalty_restore(skippy_model * model, bool full) { + release(restored); + } + ++// Temperature 0 with the defaults and sampler order the serving layer sends. ++skippy_sampling_config temperature_zero_config() { ++ skippy_sampling_config config{}; ++ config.version = 1; ++ config.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ config.temperature = 0.0f; ++ config.top_k = 40; ++ config.top_p = 0.95f; ++ config.min_p = 0.05f; ++ config.typical_p = 1.0f; ++ config.top_nsigma = -1.0f; ++ config.dynatemp_exponent = 1.0f; ++ config.repeat_penalty = 1.0f; ++ config.penalty_last_n = 64; ++ config.dry_base = 1.75f; ++ config.dry_allowed_length = 2; ++ config.dry_penalty_last_n = 64; ++ config.xtc_threshold = 0.1f; ++ config.mirostat_entropy = 5.0f; ++ config.mirostat_learning_rate = 0.1f; ++ config.reasoning_budget_tokens = -1; ++ config.sampler_count = 9; ++ for (uint32_t i = 0; i < config.sampler_count; ++i) { ++ config.samplers[i] = i + 1; ++ } ++ return config; ++} ++ ++// The token a freshly built chain selects from the row the last decode sampled. ++llama_token full_chain_token(skippy_session * session) { ++ auto * reference = common_sampler_clone(session->sampler); ++ CHECK(reference != nullptr); ++ common_sampler_reset(reference); ++ for (const llama_token token : session->token_history) { ++ common_sampler_accept(reference, token, true); ++ } ++ const auto token = common_sampler_sample(reference, session->ctx, -1); ++ CHECK(common_sampler_last(session->sampler) == session->token_history.back()); ++ CHECK(session->sampling_accepted_token_count == session->token_history.size()); ++ common_sampler_free(reference); ++ return token; ++} ++ ++// Count the decodes that took the argmax path and check each against the full chain. ++uint64_t argmax_decodes(skippy_model * model, const skippy_sampling_config & sampling, ++ std::vector * predicted) { ++ auto * session = create(model); ++ prefill(session, {1, 2, 3, 4, 5, 6, 7, 8}); ++ const uint64_t before = session->sampling_argmax_count; ++ llama_token previous = 9; ++ for (int step = 0; step < 6; ++step) { ++ previous = decode(session, sampling, previous); ++ CHECK(previous == full_chain_token(session)); ++ predicted->push_back(previous); ++ } ++ const uint64_t taken = session->sampling_argmax_count - before; ++ release(session); ++ return taken; ++} ++ ++void argmax_path(skippy_model * model) { ++ // Repeated biases apply in order to the original logit, without pre-summing. ++ skippy_argmax_plan plan; ++ skippy_prepare_argmax_plan(&plan, {{0, -1e20f}, {1, 0.0f}, {0, 1.0f}, {-1, 4.0f}}, 2); ++ const float logits[] = {1e20f, 0.5f}; ++ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); ++ skippy_prepare_argmax_plan(&plan, {}, 2); ++ CHECK(skippy_select_unique_argmax(logits, 2, plan) == 0); ++ ++ // Each request can only select the top biased logit, so it must not run the full chain. ++ auto ignore_eos = temperature_zero_config(); ++ ignore_eos.flags |= SKIPPY_SAMPLING_FLAG_IGNORE_EOS; ++ ignore_eos.ignore_eos = 1; ++ auto logit_bias = temperature_zero_config(); ++ logit_bias.logit_bias_count = 2; ++ logit_bias.logit_bias[0] = {7, -3.0f}; ++ logit_bias.logit_bias[1] = {9, 2.5f}; ++ auto inert_penalties = temperature_zero_config(); ++ inert_penalties.presence_penalty = 0.5f; ++ inert_penalties.frequency_penalty = 0.5f; ++ inert_penalties.penalty_last_n = 0; ++ for (const auto & sampling : {ignore_eos, logit_bias, inert_penalties}) { ++ std::vector predicted; ++ const uint64_t taken = argmax_decodes(model, sampling, &predicted); ++ if (taken != predicted.size()) { ++ std::fprintf(stderr, "argmax path taken for %llu of %zu temperature-0 decodes\n", ++ static_cast(taken), predicted.size()); ++ } ++ CHECK(taken == predicted.size()); ++ } ++ ++ // Equal biased maxima keep the full chain's tie order. ++ auto tie = temperature_zero_config(); ++ tie.logit_bias_count = 2; ++ tie.logit_bias[0] = {3, 1e30f}; ++ tie.logit_bias[1] = {5, 1e30f}; ++ std::vector predicted; ++ CHECK(argmax_decodes(model, tie, &predicted) == 0); ++ for (const llama_token token : predicted) { ++ CHECK(token == 3 || token == 5); ++ } ++} + + int32_t stage_layers(skippy_session * session) { + return session->stage_model->model->hparams.n_layer(); +@@ -441,6 +545,7 @@ void adapter_contracts(skippy_model * model) { + error = nullptr; + + config = sampling_config(); ++ config.temperature = 0.8f; + config.ignore_eos = 1; + config.logit_bias_count = 3; + const auto * vocab = llama_model_get_vocab(model->model); +@@ -476,7 +581,8 @@ int main(int argc, char ** argv) { + CHECK(argc == 4); + const bool grammar = std::strcmp(argv[2], "grammar") == 0; + const bool state = std::strcmp(argv[2], "state") == 0; +- CHECK(grammar || state || std::strcmp(argv[2], "penalty") == 0); ++ const bool argmax = std::strcmp(argv[2], "argmax") == 0; ++ CHECK(grammar || state || argmax || std::strcmp(argv[2], "penalty") == 0); + CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); + require_recurrent = std::strcmp(argv[3], "recurrent") == 0; + auto config = skippy_runtime_config_default(); +@@ -491,6 +597,8 @@ int main(int argc, char ** argv) { + // partial side payload is intentionally empty there. + CHECK(require_recurrent); + state_round_trip(model); ++ } else if (argmax) { ++ argmax_path(model); + } else { + for (const bool full : {false, true}) { + if (grammar) { -- 2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch b/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch index 73a2778aa1..d2ca5b97ab 100644 --- a/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch +++ b/skippy/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch @@ -23,7 +23,7 @@ backend-sampling output limit is restored. 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index c930d9c3b..856c98f97 100644 +index bc4da9a07..b570682ef 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -123,6 +123,10 @@ struct skippy_runtime_config { @@ -56,10 +56,10 @@ index c9a0a226b..3257d7f2c 100644 } } diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 4082fa198..5bfd47c93 100644 +index 7305cc529..db5a69e38 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp -@@ -734,7 +734,13 @@ enum skippy_status skippy_finish_model_open( +@@ -733,7 +733,13 @@ enum skippy_status skippy_finish_model_open( } if (llm_arch_is_recurrent(model->arch) || llm_arch_is_hybrid(model->arch)) { params.n_seq_max = std::max(params.n_seq_max, std::max(2, stage_model->lane_count * 2)); @@ -90,10 +90,10 @@ index 6a1352271..b688fce73 100644 session->sampling_config_valid = false; session->chat_sampling_metadata.clear(); diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 0653347a7..40110a816 100644 +index 36c972d92..4741f55cb 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -387,6 +387,7 @@ enum skippy_status skippy_session_reset( +@@ -390,6 +390,7 @@ enum skippy_status skippy_session_reset( skippy_env_enabled("SKIPPY_DETACH_SAMPLER_ON_RESET"); if (detach_sampler_on_reset || !skippy_reset_reusable_sampling(session)) { skippy_clear_chat_sampling(session); diff --git a/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch b/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch index 9208e0642f..9deca54db5 100644 --- a/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch +++ b/skippy/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch @@ -76,10 +76,10 @@ index df831c43e..3448095a1 100644 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/state.h b/include/skippy/state.h -index 0fe373d78..6d9028a18 100644 +index 1cfaaa5c6..e8d0874a1 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h -@@ -177,6 +177,21 @@ LLAMA_API enum skippy_status skippy_retire_verify_checkpoint( +@@ -173,6 +173,21 @@ LLAMA_API enum skippy_status skippy_retire_verify_checkpoint( uint64_t token_count, struct skippy_error ** out_error); @@ -105,7 +105,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cd2b536f6..4f4fc1cd1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -62,6 +62,7 @@ add_library(llama +@@ -59,6 +59,7 @@ add_library(llama skippy/model_source.cpp skippy/session.cpp skippy/verification.cpp @@ -137,7 +137,7 @@ index cd2b536f6..4f4fc1cd1 100644 + add_skippy_verify_rollback_test(qwen4exp qwen4exp-moe.gguf) + # lfm2's fixture slides its attention window, so it checkpoints every window. + add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) - add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) + add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) target_include_directories(skippy-sampling-history PRIVATE .) target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) diff --git a/src/skippy-verify-checkpoint.h b/src/skippy-verify-checkpoint.h @@ -497,7 +497,7 @@ diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h index 46e907aa0..ec9fb94b1 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -130,6 +130,11 @@ struct skippy_verify_checkpoint { +@@ -121,6 +121,11 @@ struct skippy_verify_checkpoint { bool valid = false; int32_t token_start = 0; size_t token_count = 0; @@ -509,7 +509,7 @@ index 46e907aa0..ec9fb94b1 100644 std::vector state; std::vector token_ids; bool has_activation_input = false; -@@ -201,4 +206,16 @@ struct skippy_session { +@@ -194,4 +199,16 @@ struct skippy_session { std::vector pending_activation_exports; bool reset_required = false; std::vector verify_checkpoints; @@ -572,20 +572,76 @@ index 4741f55cb..9d0ba6ee5 100644 SKIPPY_RUNTIME_EVENT_KIND_KV_PRESSURE_CLEARED, static_cast(session->seq_id), diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index b2f394444..57b9eea4e 100644 +index 15c48419d..45a53c4ba 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp -@@ -726,8 +726,11 @@ enum skippy_status skippy_trim_session( - } +@@ -74,7 +74,7 @@ static void skippy_update_session_state_after_import( + session->signal_history.resize(static_cast(session->n_past)); + } + skippy_mtp_clear_session_state(session); +- session->verify_checkpoints.clear(); ++ skippy_clear_verify_windows(session); + } + + static enum skippy_status skippy_imported_session_position( +@@ -646,7 +646,7 @@ enum skippy_status skippy_import_kv_page( } - session->n_past = static_cast(token_count); -- if (session->token_history.size() > token_count) { -+ const bool history_truncated = session->token_history.size() > token_count; -+ if (history_truncated) { - session->token_history.resize(static_cast(token_count)); + session->n_past = std::max(session->n_past, static_cast(std::min(desc->token_start + desc->token_count, std::numeric_limits::max()))); + skippy_mtp_clear_session_state(session); +- session->verify_checkpoints.clear(); ++ skippy_clear_verify_windows(session); + session->ctx->synchronize(); + return skippy_success(out_error); + } +@@ -742,7 +742,7 @@ enum skippy_status skippy_import_cachegen_kv_page_v1(struct skippy_session * + static_cast(std::min(desc->token_start + desc->token_count, + std::numeric_limits::max()))); + skippy_mtp_clear_session_state(session); +- session->verify_checkpoints.clear(); ++ skippy_clear_verify_windows(session); + session->ctx->synchronize(); + return skippy_success(out_error); + } +@@ -759,17 +759,28 @@ enum skippy_status skippy_retire_verify_checkpoint( + if (!skippy_memory_needs_verify_checkpoint(session->ctx->get_memory())) { + return skippy_success(out_error); + } +- // No checkpoint is taken when the span rolls back in place, so there is +- // nothing to retire. +- if (skippy_verify_window_can_roll_back_in_place(session, static_cast(token_count))) { ++ skippy_verify_checkpoint & inplace = session->inplace_verify_window; ++ if (inplace.valid && static_cast(inplace.token_start) == token_start && ++ inplace.token_count == token_count) { ++ inplace.valid = false; ++ ++session->verify_windows_in_place; + return skippy_success(out_error); + } +- if (!skippy_retire_verify_checkpoint_exact( +- session->verify_checkpoints, token_start, token_count)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "verify-window checkpoint was not found"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; ++ skippy_verify_checkpoint retired; ++ if (skippy_retire_verify_checkpoint_exact( ++ session->verify_checkpoints, token_start, token_count, &retired)) { ++ if (session->verify_checkpoint_pool.size() < 2) { ++ session->verify_checkpoint_pool.push_back(std::move(retired)); ++ } ++ return skippy_success(out_error); + } +- return skippy_success(out_error); ++ // A window that could roll back in place may have taken no checkpoint ++ // at all, so there is nothing to retire. ++ if (skippy_verify_window_can_roll_back_in_place(session, static_cast(token_count))) { ++ return skippy_success(out_error); + } -+ if (history_truncated || session->sampling_accepted_token_count > token_count) { - skippy_clear_chat_sampling(session); ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "verify-window checkpoint was not found"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; + } + + enum skippy_status skippy_trim_session( +@@ -799,6 +810,25 @@ enum skippy_status skippy_trim_session( + skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); + return SKIPPY_STATUS_RUNTIME_ERROR; } + // A window held in place rewinds through seq_rm below, to any row after + // its first. Its first row is the committed token the window started diff --git a/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch b/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch index 85a6c27c40..691aa355cd 100644 --- a/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch +++ b/skippy/llama_cpp/patches/model_support/0003-llama-port-diffusiongemma-support.patch @@ -13,7 +13,7 @@ Subject: [PATCH] llama: port DiffusionGemma support .../diffusion-gemma-server.cpp | 189 ++++ .../diffusion-gemma-visual-server.cpp | 388 ++++++++ examples/diffusion/diffusion-cli.cpp | 548 +++++++++-- - examples/diffusion/diffusion.cpp | 291 ++++++ + examples/diffusion/diffusion.cpp | 289 ++++++ examples/diffusion/diffusion.h | 38 + ggml/src/ggml-cuda/diffusion-sampling.cu | 178 ++++ ggml/src/ggml-cuda/diffusion-sampling.cuh | 19 + @@ -37,7 +37,6 @@ Subject: [PATCH] llama: port DiffusionGemma support create mode 100644 ggml/src/ggml-cuda/diffusion-sampling.cuh create mode 100644 src/models/diffusion-gemma.cpp create mode 100644 src/models/gemma4-common.h - create mode 100644 src/skippy/tests/diffusion_host_fallback.cpp diff --git a/common/arg.cpp b/common/arg.cpp index 69be4a61e..66cdb9919 100644 @@ -1686,7 +1685,7 @@ index c64611356..7f036913a 100644 llama_free(ctx); diff --git a/examples/diffusion/diffusion.cpp b/examples/diffusion/diffusion.cpp -index 0ff57d953..f752c18b6 100644 +index 0ff57d953..cf5c0e149 100644 --- a/examples/diffusion/diffusion.cpp +++ b/examples/diffusion/diffusion.cpp @@ -8,7 +8,9 @@ @@ -1760,7 +1759,7 @@ index 0ff57d953..f752c18b6 100644 llama_token_data_array cur_p = { candidates.data(), -@@ -404,3 +432,266 @@ void diffusion_generate(llama_context * ctx, +@@ -404,3 +432,264 @@ void diffusion_generate(llama_context * ctx, n_generated = params.max_length; } @@ -1830,6 +1829,7 @@ index 0ff57d953..f752c18b6 100644 + // canvas, reading the cached prefix - instead of re-decoding [prompt|canvas] every step. + // The canvas logits row base is re-resolved from output_ids after each decode below: a capped + // n_outputs_max compacts the flagged canvas rows to 0, while an uncapped pass keeps them at n_input. ++ int32_t logit_off = params.kv_cache ? 0 : n_input; + if (params.kv_cache) { + llama_diffusion_set_sc(model, nullptr, 0.0f, 1.0f, false); + // Chunked causal PREFILL: feed the prompt in ubatch-sized chunks, each writing its K/V to the store and @@ -1905,8 +1905,18 @@ index 0ff57d953..f752c18b6 100644 + + // Stage-1: when on, skip the 268 MB logits D2H + host reductions and sample on the GPU from sc_dev. + const bool gpu_reduce = dev_sc && device_sample_ok; -+ const float * logits = nullptr; // first canvas row, resolved before host use -+ if (gpu_reduce) { ++ const bool want_logits = !gpu_reduce; ++ const float * logits = nullptr; // canvas rows packed: [C or max_length, n_vocab] ++ if (want_logits) { ++ logits = llama_get_logits(ctx); ++ const float * first_canvas = llama_get_logits_ith(ctx, params.kv_cache ? 0 : n_input); ++ if (first_canvas == nullptr) { ++ LOG_ERR("%s: canvas logits row missing at step %d\n", __func__, step_idx); ++ decode_failed = true; ++ break; ++ } ++ logit_off = (int32_t) (first_canvas - logits) / n_vocab; ++ } else { + llama_synchronize(ctx); // sc_dev write must complete before we read it + } + @@ -1919,7 +1929,7 @@ index 0ff57d953..f752c18b6 100644 + // per position: argmax, entropy of softmax(raw/t), and a multinomial sample; stash raw row for SC + auto worker = [&](int32_t p0, int32_t p1) { + for (int32_t pos = p0; pos < p1; pos++) { -+ const float * row = logits + (size_t) pos * n_vocab; ++ const float * row = logits + (size_t) (logit_off + pos) * n_vocab; + float m = -INFINITY; int32_t amax = 0; + for (int32_t v = 0; v < n_vocab; v++) { + const float z = row[v] * temp_inv; @@ -1949,13 +1959,6 @@ index 0ff57d953..f752c18b6 100644 + } + }; + auto run_host_worker = [&]() { -+ // Resolve output_ids on every host entry, including the first device-sampling fallback. -+ // n_outputs_max can compact canvas rows to zero instead of their batch-token offset. -+ logits = llama_get_logits_ith(ctx, params.kv_cache ? 0 : n_input); -+ if (logits == nullptr) { -+ LOG_ERR("%s: canvas logits row missing at step %d\n", __func__, step_idx); -+ return false; -+ } + std::vector pool; + const int32_t chunk = (C + (int32_t) nth - 1) / (int32_t) nth; + for (unsigned ti = 0; ti < nth; ti++) { @@ -1964,7 +1967,6 @@ index 0ff57d953..f752c18b6 100644 + if (p0 < p1) { pool.emplace_back(worker, p0, p1); } + } + for (auto & th : pool) { th.join(); } -+ return true; + }; + + if (gpu_reduce) { @@ -1978,16 +1980,11 @@ index 0ff57d953..f752c18b6 100644 + LOG_WRN("%s: on-device sampling unsupported on this backend; using host sampling\n", __func__); + device_sample_ok = false; + } -+ if (!run_host_worker()) { -+ decode_failed = true; -+ break; -+ } ++ if (!logits) { logits = llama_get_logits(ctx); } ++ run_host_worker(); + } + } else { -+ if (!run_host_worker()) { -+ decode_failed = true; -+ break; -+ } ++ run_host_worker(); + } + + // accept the lowest-entropy positions within the MI bound (sum of strictly-earlier entropies <= bound) @@ -2371,31 +2368,6 @@ index 8e39fdf48..3380a0eae 100644 LLAMA_API int32_t llama_model_n_ctx_train (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd_inp (const struct llama_model * model); -diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index a4fbfac19..eeb0553e6 100644 ---- a/src/CMakeLists.txt -+++ b/src/CMakeLists.txt -@@ -223,6 +223,20 @@ if (LLAMA_STAGE_BUILD_TESTS) - target_compile_features(skippy-model-fixture-generator PRIVATE cxx_std_17) - target_include_directories(skippy-model-fixture-generator PRIVATE .) - target_link_libraries(skippy-model-fixture-generator PRIVATE llama-common) -+ -+ set(DIFFUSION_FALLBACK_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/diffusion-fallback-models") -+ file(MAKE_DIRECTORY "${DIFFUSION_FALLBACK_FIXTURE_DIR}") -+ add_test(NAME skippy_generate_diffusion_fallback COMMAND skippy-model-fixture-generator -+ --arch "^diffusion-gemma$" --seed 42 --out "${DIFFUSION_FALLBACK_FIXTURE_DIR}") -+ set_tests_properties(skippy_generate_diffusion_fallback PROPERTIES FIXTURES_SETUP diffusion-fallback-model) -+ add_executable(skippy-diffusion-host-fallback -+ skippy/tests/diffusion_host_fallback.cpp ../examples/diffusion/diffusion.cpp) -+ target_include_directories(skippy-diffusion-host-fallback PRIVATE . ../examples/diffusion) -+ target_compile_features(skippy-diffusion-host-fallback PRIVATE cxx_std_17) -+ target_link_libraries(skippy-diffusion-host-fallback PRIVATE llama-common) -+ add_test(NAME skippy_diffusion_host_fallback COMMAND skippy-diffusion-host-fallback -+ "${DIFFUSION_FALLBACK_FIXTURE_DIR}/diffusion-gemma-moe.gguf") -+ set_tests_properties(skippy_diffusion_host_fallback PROPERTIES FIXTURES_REQUIRED diffusion-fallback-model) - set(MTP_WIDTH_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/mtp-width-models") - file(MAKE_DIRECTORY "${MTP_WIDTH_FIXTURE_DIR}") - add_test(NAME skippy_generate_mtp_width COMMAND skippy-model-fixture-generator diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index e659ba84a..a3e3d0cbb 100644 --- a/src/llama-arch.cpp @@ -3604,123 +3576,6 @@ index 8f6c3160d..00538e6b0 100644 struct llama_model_gemma4_assistant : public llama_model_base { llama_model_gemma4_assistant(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; -diff --git a/src/skippy/tests/diffusion_host_fallback.cpp b/src/skippy/tests/diffusion_host_fallback.cpp -new file mode 100644 -index 000000000..3d714fb1a ---- /dev/null -+++ b/src/skippy/tests/diffusion_host_fallback.cpp -@@ -0,0 +1,111 @@ -+#include "diffusion.h" -+#include "ggml-backend.h" -+ -+#include -+#include -+#include -+#include -+ -+namespace { -+constexpr int prompt_size = 4; -+constexpr int canvas_size = 16; -+ -+struct observation { -+ llama_context * ctx; -+ bool device; -+ bool valid = true; -+ int steps = 0; -+}; -+ -+bool observe_step(int32_t step, int32_t total, const llama_token * tokens, int32_t count, void * user) { -+ auto & seen = *static_cast(user); -+ const int vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(seen.ctx))); -+ const float * canvas = llama_get_logits_ith(seen.ctx, prompt_size); -+ // Enforce the regression's layout: only the canvas is output, packed from row zero. -+ seen.valid &= count == prompt_size + canvas_size && canvas == llama_get_logits(seen.ctx); -+ if (!canvas) { -+ seen.valid = false; -+ return false; -+ } -+ const float inv_temp = 1.0f / (0.4f + (0.8f - 0.4f) * float(total - step) / float(total)); -+ for (int pos = 0; pos < canvas_size; ++pos) { -+ const float * row = llama_get_logits_ith(seen.ctx, prompt_size + pos); -+ seen.valid &= row == canvas + size_t(pos) * vocab; -+ if (!row) { -+ seen.valid = false; -+ return false; -+ } -+ float maximum = -INFINITY; -+ int argmax = 0; -+ for (int v = 0; v < vocab; ++v) { -+ const float value = row[v] * inv_temp; -+ if (value > maximum) { -+ maximum = value; -+ argmax = v; -+ } -+ } -+ seen.valid &= tokens[prompt_size + pos] == argmax; -+ } -+ if (seen.device) { -+ // A CPU-resident model must take the unsupported-device fallback, even in a CUDA build. -+ std::vector draws(canvas_size, 0.5f), entropy(canvas_size); -+ std::vector argmax(canvas_size), sampled(canvas_size); -+ seen.valid &= !llama_diffusion_device_sample(llama_get_model(seen.ctx), draws.data(), argmax.data(), -+ entropy.data(), sampled.data(), canvas_size, inv_temp); -+ } -+ ++seen.steps; -+ return seen.valid; -+} -+ -+bool run(llama_model * model, bool device) { -+ auto context_params = llama_context_default_params(); -+ context_params.n_ctx = 128; -+ context_params.n_batch = 32; -+ context_params.n_ubatch = 32; -+ context_params.n_outputs_max = canvas_size; -+ context_params.n_threads = 2; -+ context_params.n_threads_batch = 2; -+ llama_context * ctx = llama_init_from_model(model, context_params); -+ if (!ctx) { -+ return false; -+ } -+ observation seen { ctx, device }; -+ const std::vector prompt { 1, 2, 3, 4 }; -+ std::vector output(prompt_size + canvas_size, -1); -+ diffusion_eb_params params; -+ params.max_length = int(output.size()); -+ params.max_denoising_steps = 2; -+ params.confidence_threshold = -1.0f; -+ params.seed = 42; -+ params.gpu_sampling = device; -+ params.gpu_sample_reduce = device; -+ params.step_callback = observe_step; -+ params.step_callback_user_data = &seen; -+ int32_t generated = 0; -+ diffusion_generate_entropy_bound(ctx, prompt.data(), output.data(), prompt_size, params, generated); -+ const bool ok = seen.valid && seen.steps == 2 && generated == int(output.size()) && -+ std::equal(prompt.begin(), prompt.end(), output.begin()); -+ llama_free(ctx); -+ return ok; -+} -+} // namespace -+ -+int main(int argc, char ** argv) { -+ if (argc != 2) { -+ return 1; -+ } -+ llama_backend_init(); -+ ggml_backend_load_all(); -+ auto params = llama_model_default_params(); -+ params.n_gpu_layers = 0; -+ llama_model * model = llama_model_load_from_file(argv[1], params); -+ const bool ok = model && run(model, false) && run(model, true); -+ if (model) { -+ llama_model_free(model); -+ } -+ llama_backend_free(); -+ if (!ok) { -+ std::fprintf(stderr, "compacted diffusion host/device-fallback logits mismatch\n"); -+ } -+ return ok ? 0 : 1; -+} diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index d12706299..d7d1a9024 100644 --- a/tests/test-llama-archs.cpp @@ -3776,5 +3631,5 @@ index d12706299..d7d1a9024 100644 if (moe && !moe_implemented(arch)) { continue; -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch index ad035181e7..7daca3241a 100644 --- a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch @@ -121,7 +121,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4f4fc1cd1..d3c86694f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -98,6 +98,7 @@ add_library(llama +@@ -94,6 +94,7 @@ add_library(llama skippy/speculative_decoding.cpp skippy/tokenization.cpp skippy/events.cpp @@ -391,5 +391,5 @@ index 000000000..d0c51d87a + } +} -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch b/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch index d1c00f91b5..0d2e75d437 100644 --- a/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch +++ b/skippy/llama_cpp/patches/model_support/0005-skippy-query-diffusion-canvas-length.patch @@ -68,5 +68,5 @@ index d0c51d87a..9cbe792ae 100644 struct skippy_model * model, const llama_token * prompt_tokens, -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch index c294b2a3dc..aafbc5288d 100644 --- a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch +++ b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch @@ -267,7 +267,7 @@ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d3c86694f..db01bc2f5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -99,6 +99,8 @@ add_library(llama +@@ -95,6 +95,8 @@ add_library(llama skippy/tokenization.cpp skippy/events.cpp skippy/system_one.cpp @@ -276,7 +276,7 @@ index d3c86694f..db01bc2f5 100644 unicode.h ${LLAMA_MODELS_SOURCES} ) -@@ -127,7 +129,7 @@ set_source_files_properties(${LLAMA_MODELS_SOURCES} +@@ -123,7 +125,7 @@ set_source_files_properties(${LLAMA_MODELS_SOURCES} configure_file(llama-version.h.in ${CMAKE_CURRENT_BINARY_DIR}/llama-version.h @ONLY) @@ -2807,5 +2807,5 @@ index 000000000..8a713d563 +// run one forward pass; returns 0 on success, non-zero on failure +LLAMA_API int laya_encode(laya_context * ctx, const laya_batch & batch, laya_result & result); -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch b/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch index 0b407568d6..0d5661f1f6 100644 --- a/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch +++ b/skippy/llama_cpp/patches/model_support/0007-fix-muse-glimmer-parse-implicit-reasoning-continuati.patch @@ -42,5 +42,5 @@ index 98dfc4b65..f19c533b9 100644 // generation prompt, so the output starts at " to=". tst.test(" to=special_function<|message|>" + call_markup) -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch b/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch index 4b9f52d1e0..779d43af41 100644 --- a/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch +++ b/skippy/llama_cpp/patches/model_support/0008-models-add-qwen3-moe-native-mtp.patch @@ -478,5 +478,5 @@ index d7d1a9024..89b5135a4 100644 glm_dsa_indexshare_fixture::DEFAULT, 256, 8, false, 2 + dense_mtp_depth, 256); -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index 5b1845464b..02759682c4 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -1,4 +1,4 @@ -From d96bec3062e9d6b566576d2e0a11ccc00b24abf6 Mon Sep 17 00:00:00 2001 +From 43dc48235a7b30a1dba4d59ad3cb90928df2aa00 Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Thu, 22 Oct 2026 17:15:05 +1100 Subject: [PATCH] skippy: add Whisper speech recognition @@ -220,7 +220,7 @@ index 000000000..99d4a1094 + +#endif // SKIPPY_ASR_H diff --git a/include/skippy/common.h b/include/skippy/common.h -index 54c87b6f2..80710eb3b 100644 +index 54c87b6f2..4214d0b89 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -228,7 +228,7 @@ index 54c87b6f2..80710eb3b 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 -#define SKIPPY_ABI_VERSION_PATCH 73 -+#define SKIPPY_ABI_VERSION_PATCH 75 ++#define SKIPPY_ABI_VERSION_PATCH 74 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) @@ -242,7 +242,7 @@ index 54c87b6f2..80710eb3b 100644 enum skippy_status { SKIPPY_STATUS_OK = 0, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index eab1c3a46..ea0cdd178 100644 +index f43b87266..deb634e8a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -101,6 +101,7 @@ add_library(llama @@ -264,7 +264,7 @@ index eab1c3a46..ea0cdd178 100644 configure_file(llama-version.h.in ${CMAKE_CURRENT_BINARY_DIR}/llama-version.h @ONLY) target_include_directories(llama PRIVATE . ../common ../tools/laya ${CMAKE_CURRENT_BINARY_DIR}) -@@ -170,6 +175,38 @@ if (LLAMA_LLGUIDANCE) +@@ -173,6 +178,38 @@ if (LLAMA_LLGUIDANCE) endif() diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 0cf24fb8cb..92ed594e49 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -1,4 +1,4 @@ -From 76c1598c4144f104a0b8946f6533619fd9ad6b33 Mon Sep 17 00:00:00 2001 +From 5dbf1902a59cc99e2e2f37fff9c1c5ee3a4098ca Mon Sep 17 00:00:00 2001 From: Virgile-pct Date: Wed, 21 Oct 2026 23:42:33 +0200 Subject: [PATCH] skippy: record per-token logprobs while sampling @@ -43,15 +43,15 @@ index 4e33847d9..9497734b7 100644 #include "skippy/system_one.h" #include "skippy/laya.h" diff --git a/include/skippy/common.h b/include/skippy/common.h -index 80710eb3b..93232a2b8 100644 +index 4214d0b89..dae7be31c 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 75 -+#define SKIPPY_ABI_VERSION_PATCH 78 +-#define SKIPPY_ABI_VERSION_PATCH 74 ++#define SKIPPY_ABI_VERSION_PATCH 77 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) @@ -144,7 +144,7 @@ index 1b42f32c0..c1a755c4c 100644 #ifdef __cplusplus diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index ea0cdd178..beded64e4 100644 +index deb634e8a..a75262731 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -87,6 +87,7 @@ add_library(llama @@ -256,19 +256,19 @@ index 000000000..43260dfc2 + return skippy_success(out_error); +} diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp -index 1b82ba6ba..42769ba7c 100644 +index 42769ba7c..577b4be2e 100644 --- a/src/skippy/resident_prefix.cpp +++ b/src/skippy/resident_prefix.cpp -@@ -182,6 +182,7 @@ skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, - } +@@ -183,6 +183,7 @@ skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, session->n_past = static_cast(count); session->token_history = std::move(history); -+ session->signal_history.clear(); + session->signal_history.clear(); ++ session->token_logprobs.clear(); skippy_mtp_clear_session_state(session); session->verify_checkpoints.clear(); return skippy_success(error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index ec9fb94b1..cd8a82f7a 100644 +index b8e4251aa..255334489 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -153,6 +153,8 @@ struct skippy_session { diff --git a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch index c7d1053be7..894d1b02b9 100644 --- a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch +++ b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch @@ -39,7 +39,7 @@ index beded64e4..0e619d785 100644 # lfm2's fixture slides its attention window, so it checkpoints every window. add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) + add_skippy_verify_rollback_test(glm5-next glm5-next-moe.gguf) - add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp skippy/tests/resident_checkpoint_gpu.cpp) + add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) target_include_directories(skippy-sampling-history PRIVATE .) target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp @@ -406,5 +406,5 @@ index 89b5135a4..682a1b061 100644 saver.save(path); require_fixture_written(path); -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch index 3a63909f16..5f4ebfb536 100644 --- a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch @@ -775,5 +775,5 @@ index 000000000..6ccd39221 + }); +} -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/todo.md b/todo.md index a84c11a761..159a31c33f 100644 --- a/todo.md +++ b/todo.md @@ -64,6 +64,75 @@ The model-backed refusal case also passes on both backends: a one-byte L3 budget cannot retain a checkpoint, but eviction frees native attention cells and cold recomputation produces identical fixed-input predictions. +The combined Jared vector-decode candidate additionally passes the bounded +native **process** restart on local Metal: separate supervised seed/restore +children, a committed L3 hit, complete attention/recurrent SHA-256 equality and +four identical fixed-input predictions. Long-prefix, HTTP-server restart and +concurrent c4 cases remain separately scoped below. + +## Combined-source AgentX sweep + +- [x] Integrate Jared's indexed F16/BF16 vector-decode route and regenerate its + owning mail patch; retain compiled-kernel softcap eligibility and expand Q2, + mixed-type and post-capture graph-replay operator tests. +- [x] Package the combined Metal runtime and pass the local model-backed + foundation, including the native process-restart gate. +- [ ] Qualify the changed CUDA route with actual kernel evidence, the expanded + operator cases, independent FP64 and strict cache/L3 model gates. +- [ ] Prepare one CUDA producer per isolated lab and one Metal producer, reusing + verified artifacts across models and compatible workers. +- [ ] Finish the reusable full AgentX runner: four pinned models, c1/c2/c4, + complete recorded work, ABBAAB, standard vanilla and observed product-auto + Skippy capacity. Do not substitute the correctness foundation for this runner. +- [ ] Run and audit all eight model/backend sweeps (144 engine cells), preserving + raw work, resolved settings, source/runtime/tool identities and failures. +- [ ] Record the new campaign and linked runs in existing MLflow experiment + **6 `agentx-skippy-vs-llama`**, preserving historical campaigns. +- [ ] Rewrite the AgentX PR descriptions around the final implementation, + benchmark contract and source-pinned results. Reconcile #2657's remaining + correctness requirements before declaring it fully superseded. + +## PR #2746 regression repair gates + +These gates supplement the fixed four-model campaign. Product selection must +depend on loaded capabilities, tensor geometry and backend support; model names +and family allowlists must not choose a serving or kernel path. + +The repair withholds automatic indexed graph selection until the unchanged +full-model arithmetic contract passes. Direct indexed-operator support is +separate. Ordinary attention retains its physical-pool cost; do not carry the +historical idle-pool scaling claim into the fallback candidate's results. + +- [ ] Preserve the common upstream CUDA hardware/GQA dispatch policy for indexed + attention. Verify actual MMA selection for eligible wide-GQA decode and an + eligible vector control, plus unchanged operator numerical and graph-replay + gates. Kernel availability alone is not a performance qualification. +- [ ] Prove that resident recurrent checkpoints retain cooperative suffix-prefill + and cache-wave scheduling with disk disabled. Decode must make progress before + a competing long prefill completes. Exercise cancellation and resource cleanup + without changing exact checkpoint boundaries. +- [ ] Compare the longest valid resident and committed L3 prefixes using + metadata. Cover a short resident prefix with a longer L3 checkpoint, resident + ties, refused or failed L3 fill, and preservation of the resident fallback. +- [ ] Exercise large native-owner cold offload during active decode with L3 + admission pressure. Byte-budget safety alone does not establish bounded + request latency while snapshots are materialized. +- [ ] Run genuine uncached base/head model controls and retain the original + strict physical-layout full-model numerical failure until the same contract + passes. Operator FP64 references and output-count hashes do not close it. +- [ ] Extend cache save/restore/fork and cold-export correctness coverage to + supported quantized and mixed K/V pairs, retaining byte/state, fixed-input + logit and selected-token assertions. Finite-logit dispatch tests are separate. +- [ ] Add pinned small-model probes for independent capability coverage: a + different head width/GQA and sliding-window/softcap attention. Verify actual + metadata and intended baseline fallback when indexing is unsupported; do not + count such a fallback as indexed-attention coverage. These models supplement + the existing four; they do not replace or alter their pinned qualification. +- [ ] Restart affected M3 and allowed-Spark AgentX groups after the relevant + corrected-source gates pass. Keep original source943 results/failures and + source188 admission recovery separate, publish audited complete groups into + existing MLflow experiment6, and update public PR2746 with exact attribution. + ## Retain PR #2657's correctness requirements Cache-owned immutable checkpoints replace the old execution-lane pinning and diff --git a/tools/xtask/src/automation/agentx/final_sweep_tests.rs b/tools/xtask/src/automation/agentx/final_sweep_tests.rs index 061df3a19a..bb0e9c29d7 100644 --- a/tools/xtask/src/automation/agentx/final_sweep_tests.rs +++ b/tools/xtask/src/automation/agentx/final_sweep_tests.rs @@ -112,6 +112,11 @@ fn prepared_environment_rejects_executable_and_external_pth_entries() { path: dir.path().into(), sha256: String::new(), }; + std::fs::write( + dir.path().join("pyvenv.cfg"), + "include-system-site-packages = false\n", + ) + .unwrap(); std::fs::create_dir(dir.path().join("modules")).unwrap(); std::fs::write(&path, "# local modules\nmodules\n").unwrap(); assert!(tree.observe().is_ok()); @@ -125,6 +130,182 @@ fn prepared_environment_rejects_executable_and_external_pth_entries() { } } +#[test] +fn prepared_environment_rejects_system_site_packages_and_ambiguous_config() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("pyvenv.cfg"); + let tree = Tree { + path: dir.path().into(), + sha256: String::new(), + }; + for content in [ + "home = /installed/python\nversion = 3.12.0\ninclude-system-site-packages = false\n", + "include-system-site-packages = false\n", + "# isolated environment\r\n INCLUDE-SYSTEM-SITE-PACKAGES\t=\tFaLsE \r\n", + ] { + std::fs::write(&path, content).unwrap(); + assert!(tree.observe().is_ok(), "{content:?}"); + } + for content in [ + "home = /installed/python\nversion = 3.12.0\n", + "", + "include-system-site-packages = true\n", + " InClUdE-SyStEm-SiTe-PaCkAgEs\t=\tTrUe \r\n", + "include-system-site-packages = yes\n", + "include-system-site-packages = 1\n", + "include-system-site-packages =\n", + "include-system-site-packages = false # comment\n", + "include-system-site-packages = false\ninclude-system-site-packages = true\n", + "include-system-site-packages = true\ninclude-system-site-packages = false\n", + "include-system-site-packages = false\nINCLUDE-SYSTEM-SITE-PACKAGES = false\n", + "include-system-site-packages true\n", + "= false\n", + ] { + std::fs::write(&path, content).unwrap(); + assert!(tree.observe().is_err(), "{content:?}"); + } + std::fs::write(&path, [0xff]).unwrap(); + assert!(tree.observe().is_err()); +} + +fn prepared_tools_fixture(root: &std::path::Path) -> Tools { + let mut tools = tools(); + for (name, file) in [ + ("skippy", &mut tools.skippy), + ("llama", &mut tools.llama), + ("client", &mut tools.client), + ("lock", &mut tools.client_lock), + ] { + file.path = root.join(name); + std::fs::write(&file.path, b"pinned fixture").unwrap(); + } + for (name, tree) in [ + ("runtime", &mut tools.runtime), + ("standard", &mut tools.standard_runtime), + ("environment", &mut tools.client_environment), + ("tokenizer", &mut tools.tokenizer), + ] { + tree.path = root.join(name); + std::fs::create_dir(&tree.path).unwrap(); + std::fs::write(tree.path.join("module"), b"pinned fixture").unwrap(); + } + tools +} + +#[test] +fn prepared_tools_require_isolated_root_config_for_pinning_and_verification() { + let dir = tempfile::tempdir().unwrap(); + let mut tools = prepared_tools_fixture(dir.path()); + // Runtime and tokenizer trees remain generic; only the client requires a venv. + assert!(tools.runtime.observe().is_ok()); + assert!(tools.tokenizer.observe().is_ok()); + for error in [ + tools.pin().unwrap_err(), + tools.verify(dir.path()).unwrap_err(), + ] { + assert!(error.to_string().contains("isolated root pyvenv.cfg")); + } + let config = tools.client_environment.path.join("pyvenv.cfg"); + std::fs::write(&config, "include-system-site-packages = false\n").unwrap(); + tools.pin().unwrap(); + tools.client_environment.verify().unwrap(); + std::fs::remove_file(&config).unwrap(); + tools.client_environment.sha256 = tools.client_environment.observe().unwrap(); + for error in [ + tools.pin().unwrap_err(), + tools.verify(dir.path()).unwrap_err(), + ] { + assert!(error.to_string().contains("isolated root pyvenv.cfg")); + } +} + +#[test] +fn prepared_tools_reject_bin_config_overriding_an_isolated_root_config() { + let dir = tempfile::tempdir().unwrap(); + let mut tools = prepared_tools_fixture(dir.path()); + let environment = tools.client_environment.path.clone(); + std::fs::write( + environment.join("pyvenv.cfg"), + "include-system-site-packages = false\n", + ) + .unwrap(); + std::fs::create_dir(environment.join("bin")).unwrap(); + let override_config = environment.join("bin/pyvenv.cfg"); + std::fs::write(&override_config, "include-system-site-packages = false\n").unwrap(); + tools.pin().unwrap(); + for content in ["include-system-site-packages = true\n", "home = /python\n"] { + std::fs::write(&override_config, content).unwrap(); + // Even an accurately pinned tree cannot admit the executable-directory override. + tools.client_environment.sha256 = crate::product::digest::tree_sha256(&environment) + .map_err(|error| error.error) + .unwrap(); + assert!( + tools + .pin() + .unwrap_err() + .to_string() + .contains("site-packages") + ); + assert!( + tools + .verify(dir.path()) + .unwrap_err() + .to_string() + .contains("site-packages") + ); + } +} + +#[test] +fn prepared_tools_check_executable_config_using_filesystem_case_resolution() { + let dir = tempfile::tempdir().unwrap(); + let mut tools = prepared_tools_fixture(dir.path()); + let environment = tools.client_environment.path.clone(); + std::fs::write( + environment.join("pyvenv.cfg"), + "include-system-site-packages = false\n", + ) + .unwrap(); + std::fs::create_dir(environment.join("bin")).unwrap(); + std::fs::write( + environment.join("bin/PYVENV.CFG"), + "include-system-site-packages = true\n", + ) + .unwrap(); + match std::fs::metadata(environment.join("bin/pyvenv.cfg")) { + Ok(_) => {} + // A case-sensitive filesystem cannot resolve this spelling as Python would. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return, + Err(error) => panic!("probe config case resolution: {error}"), + } + for error in [ + tools.pin().unwrap_err(), + tools.verify(dir.path()).unwrap_err(), + ] { + assert!(error.to_string().contains("site-packages")); + } +} + +#[test] +fn prepared_tools_reject_nonregular_executable_config() { + let dir = tempfile::tempdir().unwrap(); + let mut tools = prepared_tools_fixture(dir.path()); + let environment = tools.client_environment.path.clone(); + std::fs::write( + environment.join("pyvenv.cfg"), + "include-system-site-packages = false\n", + ) + .unwrap(); + std::fs::create_dir(environment.join("Scripts")).unwrap(); + let config = environment.join("Scripts/pyvenv.cfg"); + std::fs::create_dir(&config).unwrap(); + assert!(tools.pin().is_err()); + assert!(tools.verify(dir.path()).is_err()); + std::fs::remove_dir(&config).unwrap(); + std::fs::write(&config, "include-system-site-packages = false\n").unwrap(); + tools.pin().unwrap(); +} + #[cfg(unix)] #[test] fn ordinary_venv_alias_is_pinned_without_permitting_external_editable_packages() { diff --git a/tools/xtask/src/automation/agentx/prepared_tools.rs b/tools/xtask/src/automation/agentx/prepared_tools.rs index 22738fc026..894ebc0bb8 100644 --- a/tools/xtask/src/automation/agentx/prepared_tools.rs +++ b/tools/xtask/src/automation/agentx/prepared_tools.rs @@ -98,6 +98,9 @@ impl Tree { { return Err("prepared trees require regular files or regular-file links".into()); } + if entry.file_name() == "pyvenv.cfg" { + verify_python_venv_config(&entry.path())?; + } if entry .path() .extension() @@ -129,6 +132,35 @@ impl Tree { } } +fn verify_python_venv_config(path: &Path) -> DynResult<()> { + let bytes = crate::automation::receipt_files::bounded(&path.canonicalize()?, 1024 * 1024)?; + let mut seen_site_packages = false; + for line in std::str::from_utf8(&bytes)?.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + let (key, value) = line + .split_once('=') + .ok_or("prepared pyvenv.cfg requires key=value entries")?; + let key = key.trim(); + if key.is_empty() { + return Err("prepared pyvenv.cfg requires nonempty keys".into()); + } + if key.eq_ignore_ascii_case("include-system-site-packages") { + // System paths can execute unpinned .pth/sitecustomize hooks before + // the client imports. Reject ambiguous or non-boolean declarations. + if seen_site_packages || !value.trim().eq_ignore_ascii_case("false") { + return Err("prepared environment must disable system site-packages".into()); + } + seen_site_packages = true; + } + } + if !seen_site_packages { + return Err("prepared pyvenv.cfg must explicitly disable system site-packages".into()); + } + Ok(()) +} + fn verify_python_path_file(path: &Path, root: &Path) -> DynResult<()> { let bytes = crate::automation::receipt_files::bounded(&path.canonicalize()?, 1024 * 1024)?; for line in std::str::from_utf8(&bytes)?.lines().map(str::trim) { @@ -174,7 +206,33 @@ pub(super) struct Tools { pub cell_seconds: u64, } impl Tools { + fn verify_client_environment(&self) -> DynResult<()> { + absolute(&self.client_environment.path)?; + verify_python_venv_config(&self.client_environment.path.join("pyvenv.cfg")).map_err( + |error| -> crate::command::DynError { + format!("prepared client environment requires an isolated root pyvenv.cfg: {error}") + .into() + }, + )?; + // Python checks the executable directory first. Probe the actual path, + // including case-insensitive filesystem resolution, rather than relying + // only on directory-entry spelling during the generic tree walk. + for directory in ["bin", "Scripts"] { + let config = self + .client_environment + .path + .join(directory) + .join("pyvenv.cfg"); + match std::fs::symlink_metadata(&config) { + Ok(_) => verify_python_venv_config(&config)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + Ok(()) + } pub(super) fn pin(&mut self) -> DynResult<()> { + self.verify_client_environment()?; for file in [ &mut self.skippy, &mut self.llama, @@ -194,6 +252,7 @@ impl Tools { Ok(()) } pub(super) fn verify(&self, root: &Path) -> DynResult<()> { + self.verify_client_environment()?; for source in [ &self.product_source_commit, &self.native_source_commit, diff --git a/tools/xtask/src/automation/kv_validation/evidence.rs b/tools/xtask/src/automation/kv_validation/evidence.rs index 03185d1fca..ea44e2572b 100644 --- a/tools/xtask/src/automation/kv_validation/evidence.rs +++ b/tools/xtask/src/automation/kv_validation/evidence.rs @@ -2,6 +2,35 @@ use super::contract::Backend; use crate::command::DynResult; use std::collections::{BTreeMap, BTreeSet}; +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct RestartReceipt { + status: String, + source: String, + seed_process_id: u32, + restore_process_id: u32, + state_integrity: String, + fixed_input_predictions: Vec, +} + +pub(super) fn process_restart(bytes: &[u8]) -> DynResult<()> { + let receipt: RestartReceipt = serde_json::from_slice(bytes)?; + if receipt.status != "passed" + || receipt.source != "l3" + || receipt.seed_process_id == 0 + || receipt.restore_process_id == 0 + || receipt.seed_process_id == receipt.restore_process_id + || receipt.state_integrity != "sha256_exact" + || receipt.fixed_input_predictions.len() != 4 + { + return Err( + "L3 restart lacks separate successful processes and exact state/content evidence" + .into(), + ); + } + Ok(()) +} + #[derive(serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub(super) struct CacheEvidence { diff --git a/tools/xtask/src/automation/kv_validation/execution.rs b/tools/xtask/src/automation/kv_validation/execution.rs index 6218994068..c9896423b7 100644 --- a/tools/xtask/src/automation/kv_validation/execution.rs +++ b/tools/xtask/src/automation/kv_validation/execution.rs @@ -123,7 +123,7 @@ pub(super) fn finalize( let passed = result.is_ok() && finish.is_ok() && archived.is_ok() && Instant::now() < deadline; publish( &output.join("result.json"), - &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"scope":"KVdtype_dispatch_generic_c1_cache_plus_recurrent_runtime_L3_restart_not_long_c4_process_restart_or_performance"}), + &json!({"schema_version":1,"status":if passed {"passed"} else {"failed"},"model_key":input.model_key,"request":input,"failure":result.as_ref().err().map(ToString::to_string),"interrupt_failure":finish.as_ref().err().map(ToString::to_string),"archive_failure":archived.as_ref().err().map(ToString::to_string),"result_location":"post_archive_sidecar_not_in_evidence_archive","scope":"KVdtype_dispatch_generic_c1_cache_plus_recurrent_L3_process_restart_not_long_c4_HTTP_restart_or_performance"}), )?; finish?; result?; @@ -328,5 +328,46 @@ fn recurrent( )?; evidence::rust_test(&text, &test)?; } + process_restart(prepared, &env, output, deadline, cancel)?; Ok(()) } + +fn process_restart( + prepared: &Prepared, + env: &[(&str, OsString)], + output: &Path, + deadline: Instant, + cancel: &Cancellation, +) -> DynResult<()> { + let root = output.join("l3-process-restart"); + std::fs::create_dir(&root)?; + let test = + "frontend::local_generation::tests::durable_prefix::native_cold_prefix_process_stage"; + for phase in ["seed", "restore"] { + let mut phase_env = env.to_vec(); + phase_env.extend([ + ("SKIPPY_L3_TEST_ROOT", root.clone().into_os_string()), + ("SKIPPY_L3_TEST_PHASE", phase.into()), + ]); + let text = child( + &prepared.producer.serving_tests.path, + vec![ + "--exact".into(), + test.into(), + "--ignored".into(), + "--nocapture".into(), + "--test-threads=1".into(), + ], + (output, output), + &format!("l3-process-{phase}"), + remaining(deadline)?, + cancel, + &phase_env, + )?; + evidence::rust_test(&text, test)?; + } + evidence::process_restart(&crate::automation::receipt_files::bounded( + &root.join("restart-receipt.json"), + 4096, + )?) +} diff --git a/tools/xtask/src/automation/kv_validation/tests.rs b/tools/xtask/src/automation/kv_validation/tests.rs index 0ec2f0e653..310a5ecd55 100644 --- a/tools/xtask/src/automation/kv_validation/tests.rs +++ b/tools/xtask/src/automation/kv_validation/tests.rs @@ -4,6 +4,36 @@ use super::{ }; use std::path::PathBuf; +#[path = "tests/cache_client.rs"] +mod cache_client; + +#[test] +fn l3_restart_requires_distinct_processes_exact_state_and_typed_predictions() { + let valid = serde_json::json!({"status":"passed","source":"l3","seed_process_id":1, + "restore_process_id":2,"state_integrity":"sha256_exact","fixed_input_predictions":[1,2,3,4]}); + let check = |value| evidence::process_restart(&serde_json::to_vec(&value).unwrap()); + check(valid.clone()).unwrap(); + for (field, value) in [ + ("seed_process_id", serde_json::json!(0)), + ("restore_process_id", serde_json::json!(1)), + ("source", serde_json::json!("radix")), + ("status", serde_json::json!("failed")), + ("state_integrity", serde_json::json!("token_counts_only")), + ("fixed_input_predictions", serde_json::json!([1, 2, 3])), + ( + "fixed_input_predictions", + serde_json::json!(["1", "2", "3", "4"]), + ), + ] { + let mut invalid = valid.clone(); + invalid[field] = value; + assert!(check(invalid).is_err(), "accepted invalid {field}"); + } + let mut invalid = valid; + invalid["arbitrary_headers"] = serde_json::json!({}); + assert!(check(invalid).is_err()); +} + #[cfg(unix)] #[test] fn evidence_archive_receipt_binds_contents_and_excludes_runtime_symlinks() { From 80a919df06356da2b4b42f910a7677a5b465c484 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 9 Nov 2026 16:50:19 +1100 Subject: [PATCH 31/81] perf(skippy): match llama.cpp decode on Metal and resume multi-turn chats (#2866) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Skippy now decodes as fast as vanilla llama.cpp on Metal, multi-turn chats on hybrid recurrent models (Qwen3.5) resume from the cache instead of re-prefilling their history, and every step of both is visible in Skippy's own OpenTelemetry traces. Stacked on #2746. ## What changes for users On an M4 MacBook Pro with Qwen3.5-4B Q4_K_M at four concurrent requests (llama-benchy, `PREFIX_CACHING=1`): | | before | after | |---|---|---| | `tg128 (c4)` | 185-189 t/s | **198-200 t/s** | | `ctx_tg @ d4096 (c4)` | 169-171 t/s | **179-180 t/s** | | `tg128 @ d4096 (c4)` | 170-172 t/s | **177-179 t/s** | | follow-up turn groups | 19.2 / 19.6 s | **5.7 / 5.2 s** | | prompt tokens prefilled per follow-up group | 18,385 | **2,026** | Per 4-token decode step (medians, five alternated runs with cool-downs): | | graph nodes | GPU | step | host | |---|---|---|---|---| | Skippy before | 2073 | 21.74 ms | 22.61 ms | 0.81 ms | | Skippy after | 1927 | 20.33 ms | 21.17 ms | 0.77 ms | | llama-server | 1943 | 20.38 ms | 21.89 ms | 1.20 ms | Greedy answers are byte-identical before and after, both from a resumed prefix and from a fresh server. - **Decode:** two recurrent-state copies are gone, so the GPU does the same work per step as vanilla. Sessions that never verify drafts no longer keep rollback snapshots: 48 fewer `CPY` per Qwen3.5-4B decode graph. Every recurrent layer now gathers its states once instead of twice: 48 fewer `GET_ROWS`. - **Prompt reuse:** prefill checkpoints every valid boundary of the prompt: the end of the system prompt, the end of the history before the assistant turn, and the 128-token grid point. A follow-up turn resumes at the furthest one it shares (4,088 of 4,608 tokens in benchy's multi-turn mode). With a long first message, it resumes at the system prompt (3,804 of 3,823). - **Batching:** batch defaults to 2048 with ubatch 512, as llama-server does. A batch's requests sample concurrently. - **Tracing:** `--telemetry-level debug` with `SKIPPY_TELEMETRY_OTLP_FILE=trace.otlp.jsonl` (or OTLP/gRPC) gives one trace per process, viewable in any OpenTelemetry viewer: - HTTP request, OpenAI phase, scheduler, native call and native runtime spans. - Every Metal command buffer's encode, queue and execute time, with the GPU's idle gaps between them. - Each buffer's nodes and input bytes by op class. - Each graph size's op counts. - Why each prefix-cache lookup missed and where each checkpoint was taken. - CPU, memory, GPU and KV tier (L1, L2, L3) metrics. See `skippy/docs/TELEMETRY_EVENTS.md` and `skippy/docs/SERVING_SETTINGS.md`. ## Architecture - Patch `0004`: the state-kind `build_rs` overload defaults `get_state_rows` to `nullptr`, as upstream's overloads do. It defaulted to `ggml_get_rows`, upstream's old default from before the single gather. - Ordinary non-drafting sessions explicitly disable recurrent rollback snapshots. Enabled speculative plans reserve their required input window before the target opens, preserving larger caller-supplied depths and the existing checkpoint/replay fallback. This uses the parent's `recurrent_rollback_tokens` field rather than restoring the earlier `VerifyRollback` interface. - New core patches: - `0017`: native trace spans and GPU command timing, with the per-graph op counts. - `0018`: concurrent sampling. - Model-support patches `0001`, `0004`, `0006`, `0008`, `0009` and `0010` are regenerated for the new core patches. - The queue replays cold from the pinned upstream. ## Protocol The combined queue uses Skippy native ABI **0.1.81**, based on the parent branch's 0.1.79 ABI and superseding this branch's earlier 0.1.80 runtime. This PR adds native tracing and GPU command timing declarations. The existing `uint32_t skippy_runtime_config::recurrent_rollback_tokens` field now treats zero in a non-null configuration as explicitly disabling snapshots; positive values request retention up to the native limit of 64. The native configuration factory and a null C configuration retain an explicit depth of two for legacy callers. Rust's default is zero, and enabled speculative plans size retention before model open. Windows outside retained depth continue through checkpoint/replay on the selected compute backend. - The Rust FFI requires an exact ABI match, so hosts need the runtime built from this queue. - `split-certified.json` carries the new ABI and patch-queue digest. - `skippy-api.md` is regenerated. - No wire or gossip protocol changes. The M4 performance measurements above belong to the original performance commit. The completed short CUDA comparisons at `a6ee11d2a` are separately attributed in the PR comments. The rollback-restoration head `8fe849e35` is being rebenchmarked on the two hybrid CUDA models; no new result or current-head Metal/full-AgentX qualification is claimed yet. ## Validation The rollback-restoration head `8fe849e35` passes affected-package and reachable Mesh compile/Clippy, 16 focused caller-policy tests, 12 FFI tests, 398 runtime tests (10 ignored), four regenerated split-certificate tests, binding regeneration, formatting and console checks. Focused native CPU checks cover zero/two-depth full-vocabulary continuation at the unchanged `1e-6` bound, resident/component/fresh-context cache imports, and serial/pipelined verification fallback. Cold patch replay, C11/C++17 headers and API-document generation/check also pass. The real-model CUDA preflight and hybrid short reruns are pending; broad CI remains separate. Original performance-commit validation: - `cargo fmt --all --check`, `just no-console-print`, and `cargo clippy --all-targets -- -D warnings` on every touched crate and `mesh-llm`. - `just test-all`, `cargo test -p skippy-ffi --lib`, and `just skippy-native-tests metal`. - Patch queue: cold replay from the pinned upstream, with public headers compiling as C11 and C++17. - Traces (otel-desktop-viewer): - Graph op counts match llama-server except 16 view-only `RESHAPE`s. - Decode GPU per step matches llama-server. - Greedy outputs byte-identical with and without the change, both resumed from cache (3,804 tokens reused) and on a fresh server. ## Native ABI inventory after the merge ABI 0.1.79 → 0.1.81; the rollback contract changes from the earlier merged ABI 0.1.80. Older native runtimes are intentionally unsupported; Rust FFI bindings and consumers use the same queue. Existing function signatures and public struct layouts remain unchanged. No declarations are deprecated or removed. | Status | Declaration | Public header | Implementation / mirror | Purpose | |---|---|---|---|---| | Added | `enum skippy_status skippy_set_native_span_callback(skippy_native_span_callback callback, void *user_data)` | `include/skippy/tracing.h` | `src/skippy/tracing.cpp`; `skippy-ffi/src/bindings/skippy.rs` | Report completed native spans | | Added | `enum skippy_status skippy_set_gpu_command_timing_callback(skippy_gpu_command_timing_callback callback, void *user_data)` | `include/skippy/tracing.h` | Same | Report GPU command timings | | Added | `void skippy_set_trace_tag(uint64_t tag)` | `include/skippy/tracing.h` | Same | Correlate native work with its caller | | Added | `skippy_native_span_v1`, `skippy_gpu_command_timing_v1`, callback typedefs and version constants | `include/skippy/tracing.h` | Same | Complete new record declarations below | | Added | `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)` | `include/skippy/common.h` | `src/skippy/abi.cpp`; same Rust mirror | Advertise tracing availability | | Changed semantics; unchanged field/layout | `uint32_t skippy_runtime_config::recurrent_rollback_tokens` | `include/skippy/runtime.h` | `src/skippy/model_loading.cpp`; `skippy-runtime/src/config.rs`; serving/API/Mesh plan callers | Explicit zero disables snapshots; positive retention is sized from active verification inputs. Existing `SKIPPY_RS_SEQ` override accepts zero. | | Changed initialization; unchanged signature | `struct skippy_runtime_config skippy_runtime_config_default(void)` | `include/skippy/runtime.h` | `src/skippy/model_loading.cpp` | Explicitly returns rollback depth two, preserving legacy factory/null behavior under the new zero semantics. | | Changed version constants | `SKIPPY_ABI_VERSION_PATCH: 80 → 81` | `include/skippy/common.h` | `skippy-ffi/src/lib.rs`; generated bindings and certificate | Require matching native and Rust zero-depth contracts. | The new records, callback signatures, and constants are: ```c #define SKIPPY_TRACING_H #define SKIPPY_NATIVE_SPAN_V1_ABI_VERSION 1 #define SKIPPY_NATIVE_SPAN_ID_BIT (UINT64_C(1) << 63) struct skippy_native_span_v1 { uint32_t abi_version; uint32_t struct_size; uint64_t id; uint64_t parent; const char * name; const char * detail; int64_t start_unix_ns; int64_t end_unix_ns; const char * value_name; int64_t value; }; typedef void (*skippy_native_span_callback)( const struct skippy_native_span_v1 * span, void * user_data); #define SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION 1 struct skippy_gpu_command_timing_v1 { uint32_t abi_version; uint32_t struct_size; uint64_t tag; const char * backend_name; uint32_t context_id; uint32_t compute_index; uint32_t command_index; uint32_t command_count; uint32_t node_count; int32_t status; int64_t encode_start_unix_ns; int64_t encode_end_unix_ns; int64_t execute_start_unix_ns; int64_t execute_end_unix_ns; const char * op_class; int32_t layer; uint32_t split_by_class; uint32_t attention_kv_cells; uint32_t attention_queries; uint32_t attention_row_list_nodes; uint32_t attention_flash_nodes; uint32_t attention_nodes; uint32_t matmul_nodes; uint32_t recurrent_nodes; uint32_t kv_write_nodes; uint32_t other_nodes; uint64_t attention_bytes; uint64_t matmul_bytes; uint64_t recurrent_bytes; uint64_t kv_write_bytes; uint64_t other_bytes; uint32_t recurrent_states; uint32_t recurrent_states_carried; }; typedef void (*skippy_gpu_command_timing_callback)( const struct skippy_gpu_command_timing_v1 * timing, void * user_data); ``` Validation of this merge: cold native patch replay, generated bindings and API documentation, standalone C11/C++17 headers, Rust formatting/check/Clippy, and the previously failing Just layout contracts. CPU native probes and the fresh GitHub lanes are tracked separately from the original Metal benchmark evidence. --------- Co-authored-by: James Dumay Co-authored-by: James Dumay --- .../manage-ci/references/current-inventory.md | 2 - .github/actions/select-ci-runners/action.yml | 2 +- .gitignore | 3 + Cargo.lock | 2 +- ci/runner-images.json | 13 - mesh/crates/mesh-llm-commands/Cargo.toml | 1 + .../src/gpus/tune/apply_write_tests.rs | 2 +- .../src/gpus/tune/planning.rs | 4 +- .../tune/recommendation_defaults_tests.rs | 4 +- .../src/gpus/tune_resolver/tests.rs | 24 + .../src/inference/skippy/dflash_draft.rs | 276 ++---- .../src/runtime/local_split/loading.rs | 11 +- .../src/runtime/local_split/test_support.rs | 4 + .../crates/mesh-llm-skippy-adapter/Cargo.toml | 1 - .../src/config/dflash_catalog.rs | 117 ++- .../mesh-llm-skippy-adapter/src/config/mod.rs | 15 +- .../src/config/recurrent_rollback_tests.rs | 41 + .../src/config/speculative_tests.rs | 14 +- .../src/config/translation.rs | 11 +- mesh/website/src/docs/pages/skippy-api.md | 53 +- scripts/run-llama-benchy-openai.sh | 4 + skippy/crates/llama-spec-bench/src/main.rs | 7 +- skippy/crates/skippy-api/README.md | 8 + .../skippy-api/src/serving/lifecycle.rs | 38 +- .../skippy-api/src/split-certified.json | 2 +- skippy/crates/skippy-cache/src/l3.rs | 2 + skippy/crates/skippy-cache/src/l3/pressure.rs | 72 ++ skippy/crates/skippy-cache/src/lib.rs | 2 +- skippy/crates/skippy-cache/src/manager.rs | 39 + .../crates/skippy-config/src/local_serving.rs | 18 +- skippy/crates/skippy-ffi/README.md | 2 +- .../skippy-ffi/bindgen/wrapper/skippy_abi.h | 1 + skippy/crates/skippy-ffi/src/abi.rs | 94 ++ .../crates/skippy-ffi/src/bindings/skippy.rs | 114 ++- skippy/crates/skippy-ffi/src/dynamic.rs | 26 + skippy/crates/skippy-ffi/src/lib.rs | 33 +- .../crates/skippy-runtime/src/activation.rs | 41 +- .../src/activation/iteration_execution.rs | 4 +- .../skippy-runtime/src/capability_probe.rs | 17 +- .../crates/skippy-runtime/src/checkpoint.rs | 5 +- skippy/crates/skippy-runtime/src/config.rs | 15 +- skippy/crates/skippy-runtime/src/devices.rs | 41 +- .../crates/skippy-runtime/src/gguf_writer.rs | 15 +- skippy/crates/skippy-runtime/src/kv_pages.rs | 57 +- skippy/crates/skippy-runtime/src/laya.rs | 15 +- skippy/crates/skippy-runtime/src/lib.rs | 4 +- skippy/crates/skippy-runtime/src/media.rs | 98 +- skippy/crates/skippy-runtime/src/native.rs | 94 +- .../skippy-runtime/src/native_timing.rs | 140 +++ .../skippy-runtime/src/native_tracing.rs | 202 +++++ .../src/native_tracing/gpu_commands.rs | 504 +++++++++++ .../src/native_tracing/spans.rs | 189 ++++ skippy/crates/skippy-runtime/src/ngram.rs | 17 +- .../skippy-runtime/src/resident_prefix.rs | 17 +- skippy/crates/skippy-runtime/src/session.rs | 95 +- .../skippy-runtime/src/speech_recognition.rs | 15 +- .../skippy-runtime/src/stage_planning.rs | 24 +- .../src/binary_transport/binary_messaging.rs | 6 +- .../src/binary_transport/options.rs | 60 ++ skippy/crates/skippy-serving/src/embedded.rs | 27 +- .../src/frontend/backend/phase_spans.rs | 84 ++ .../skippy-serving/src/frontend/generation.rs | 1 + .../frontend/generation/http_request_span.rs | 160 ++++ .../src/frontend/generation/server.rs | 45 +- .../src/frontend/iteration_scheduler.rs | 325 +++---- .../iteration_scheduler/command_waits.rs | 121 +++ .../iteration_scheduler/direct_batch.rs | 6 + .../direct_batch/selection_tests.rs | 182 ++++ .../iteration_scheduler/direct_execution.rs | 117 ++- .../direct_execution/ordered_reply_tests.rs | 97 ++ .../iteration_scheduler/step_telemetry.rs | 261 ++++++ .../src/frontend/iteration_scheduler/tests.rs | 111 --- .../local_generation/linear_decode.rs | 1 + .../src/frontend/local_generation/tests.rs | 4 + .../tests/cooperative_prefill.rs | 2 + .../local_generation/tests/durable_prefix.rs | 1 + .../token_generation/exact_state_recording.rs | 124 ++- .../token_generation/kv_restore.rs | 38 + .../src/frontend/speculative.rs | 1 + .../speculative/recurrent_rollback.rs | 148 +++ .../src/frontend/system_one/causal.rs | 49 +- .../src/frontend/system_one/laya.rs | 4 +- .../src/frontend/token_counting.rs | 4 +- .../src/kv_integration/config.rs | 6 +- .../exact_state/resident_preference.rs | 10 +- .../src/kv_integration/l2_serving.rs | 7 + .../skippy-serving/src/kv_integration/mod.rs | 7 +- .../src/kv_integration/records.rs | 140 +++ .../src/kv_integration/resident_prefix.rs | 3 +- .../resident_prefix/recording.rs | 88 +- .../resident_prefix/selection.rs | 48 + .../src/kv_integration/tier_metrics.rs | 242 +++++ .../skippy-serving/src/runtime_state.rs | 31 +- skippy/crates/skippy-serving/src/telemetry.rs | 711 ++++++++------- .../src/telemetry/active_span.rs | 239 +++++ .../src/telemetry/gpu_commands.rs | 471 ++++++++++ .../telemetry/gpu_commands/attention_path.rs | 157 ++++ .../src/telemetry/gpu_commands/idle_gaps.rs | 175 ++++ .../src/telemetry/log_events.rs | 192 ++++ .../src/telemetry/log_events/catalogue.rs | 238 +++++ .../src/telemetry/log_events/otlp_logs.rs | 228 +++++ .../src/telemetry/native_calls.rs | 101 +++ .../src/telemetry/native_spans.rs | 146 +++ .../src/telemetry/otlp_encoding.rs | 143 +++ .../skippy-serving/src/telemetry/otlp_file.rs | 359 ++++++++ .../src/telemetry/resource_attrs.rs | 163 ++++ .../src/telemetry/resource_metrics.rs | 768 ++++++++++++++++ .../resource_metrics/gpu_op_classes.rs | 268 ++++++ .../telemetry/resource_metrics/kv_tiers.rs | 850 ++++++++++++++++++ .../resource_metrics/otlp_metrics.rs | 238 +++++ .../src/telemetry/resource_usage.rs | 310 +++++++ .../src/telemetry/span_components.rs | 122 +++ .../src/telemetry/stderr_sink.rs | 157 ++++ .../src/telemetry/trace_context.rs | 547 +++++++++++ skippy/docs/PROMPT_CACHE.md | 31 + skippy/docs/SERVING_SETTINGS.md | 165 ++++ skippy/docs/TELEMETRY_EVENTS.md | 111 +++ skippy/evals/agentx/README.md | 6 + skippy/evals/agentx/tools.example.json | 1 + ...kippy-add-whisper-speech-recognition.patch | 221 +---- ...rd-per-token-logprobs-while-sampling.patch | 50 +- ...skippy-add-clef-joint-decision-reads.patch | 2 +- skippy/scripts/build-llama.sh | 1 + .../src/automation/agentx/final_sweep.rs | 2 +- .../automation/agentx/final_sweep_tests.rs | 35 +- .../xtask/src/automation/agentx/lifecycle.rs | 34 + .../src/automation/agentx/prepared_tools.rs | 17 + .../src/automation/agentx/standard_runtime.rs | 33 +- tools/xtask/src/no_console_print/scope.rs | 2 +- .../ci_operations/runner_identity/check.json | 2 +- .../encoding_approval.rs | 2 +- .../full_replay.rs | 2 + 132 files changed, 11003 insertions(+), 1529 deletions(-) create mode 100644 mesh/crates/mesh-llm-skippy-adapter/src/config/recurrent_rollback_tests.rs create mode 100644 skippy/crates/skippy-cache/src/l3/pressure.rs create mode 100644 skippy/crates/skippy-runtime/src/native_timing.rs create mode 100644 skippy/crates/skippy-runtime/src/native_tracing.rs create mode 100644 skippy/crates/skippy-runtime/src/native_tracing/gpu_commands.rs create mode 100644 skippy/crates/skippy-runtime/src/native_tracing/spans.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/backend/phase_spans.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/selection_tests.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution/ordered_reply_tests.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/speculative/recurrent_rollback.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/active_span.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/gpu_commands.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/gpu_commands/attention_path.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/gpu_commands/idle_gaps.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/log_events.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/log_events/catalogue.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/log_events/otlp_logs.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/native_calls.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/native_spans.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/otlp_file.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_metrics/gpu_op_classes.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_metrics/kv_tiers.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/resource_usage.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/span_components.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/trace_context.rs create mode 100644 skippy/docs/TELEMETRY_EVENTS.md diff --git a/.agents/skills/manage-ci/references/current-inventory.md b/.agents/skills/manage-ci/references/current-inventory.md index 1e5f911e65..3cc270638b 100644 --- a/.agents/skills/manage-ci/references/current-inventory.md +++ b/.agents/skills/manage-ci/references/current-inventory.md @@ -150,7 +150,6 @@ workflow owners, direct PR routing and still-unverified census in agreement. | `release.yml` | dispatch on the default branch | Canonical version synchronization, release-only signing, assets, publication, post-publish release-notes regrouping, and a preflighted downstream `mesh-packaging` dispatch | | `resume-crates-release.yml` (`Release · Resume crates.io`) | dispatch on the default branch | Exact-tag, exact-SHA recovery for a partially published stable crates.io chain; grants `packages: read` to pull its pinned GHCR runner image; workflow-commit controller validates locked historical metadata and the source's literal roster through Rust, then publishes from the immutable release source | | `website-pages.yml` | main website paths, dispatch | Public website deployment | -| `dflash-pairings-publish.yml` (`Publish DFlash pairing index`) | push to `main` touching `mesh/crates/mesh-llm-skippy-adapter/data/dflash-pairings/**`, dispatch on `main` | Publishes the checked-in DFlash pairing index to Hugging Face `meshllm/dflash-pairings` with `HF_TOKEN`: uploads `index/.json` only when absent (never overwritten or deleted; an existing copy must hash to its name), refreshes the human-facing root `index.json` and `README.md`, then re-downloads and hashes the published file. Releases pin the index by `DFLASH_PAIRING_INDEX_SHA256`. GitHub-hosted with the pinned `public cpu` image for the `hf` CLI; one non-cancelling concurrency group per commit, so no pending publication is replaced; only the run whose pairings still match `main` refreshes the root copies | | `pr_cleanup.yml` | PR close, dispatch | Positively matched cleanup only | | `pr_auto_assign.yml` | PR lifecycle | Metadata only | | `cache-warm-sccache.yml` (`Cache · Trusted sccache seed`) | successful Main Quality, dispatch | Sole bounded Linux compiler-seed publisher on GitHub-hosted infrastructure | @@ -757,7 +756,6 @@ Reusable slices/workflows with a `container:` job, and what backs it: | `ci-ui-artifact-slice.yml` | `ui_stamp` | `public cpu`, release-tag callers only; protected automation checkout consumes the immutable raw distribution | | `ci-web-slice.yml` | `ui_quality`, `ui_e2e`, `mesh/website` | `public ui`, `public browser`, existing `public web`, respectively | | `website-pages.yml` | `build` | `public web` | -| `dflash-pairings-publish.yml` | `publish` | `public cpu`, sha256:f499b79b... -- unconditional, no bare-metal row | | `nightly-stability-run.yml` | `stability` | `public cpu`, the image `prepare-automation` verifies (also bakes the node/pnpm the CLI-smoke step needs) | | `nightly-kv-coverage.yml` | `ownership-state-machines` | `public cpu`, sha256:8d93de6b... | | `release.yml` (CUDA/ROCm/Vulkan compiler rows) | per-backend `public` digests | Native compiler/toolkit images remain backend-specific; amd64 CUDA preserves its intentional ARC self-hosted placement | diff --git a/.github/actions/select-ci-runners/action.yml b/.github/actions/select-ci-runners/action.yml index 8202cfa992..913c6a89e2 100644 --- a/.github/actions/select-ci-runners/action.yml +++ b/.github/actions/select-ci-runners/action.yml @@ -138,7 +138,7 @@ runs: # This checked-in deadline makes the accepted repository-wide cache # risk self-expiring. Extending it requires a reviewed source change. - depot_pr_exception_expires="2027-09-14" + depot_pr_exception_expires="2026-09-14" current_utc_date="$(date -u +%F)" depot_pr_exception_active=false if [[ "$INPUT_DEPOT_PR_ENABLED" == "true" && diff --git a/.gitignore b/.gitignore index aabfbb1b4b..13a3b008d5 100644 --- a/.gitignore +++ b/.gitignore @@ -73,7 +73,10 @@ mesh/sdk/swift/Generated/MeshLLMFFI.xcframework/ # Generated UI dependencies left at their pre-split location. /crates/mesh-llm-ui/node_modules/ +# Local seL4 Microkit experiments (see #2866 review) +microkit-work/ # C++ tooling scratch; skippy/skippy_api/.clang-tidy is checked in. /.lsmcp/ compile_commands.json skippy/skippy_api/.cache/ +>>>>>>> moby/2746-merged diff --git a/Cargo.lock b/Cargo.lock index 4dbdec3fb0..bc398818eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4784,6 +4784,7 @@ dependencies = [ "serde_yaml_ng", "serial_test 4.0.1", "skippy-commands", + "skippy-config", "skippy-coordinator", "skippy-hardware-profile", "skippy-hf-hub", @@ -5220,7 +5221,6 @@ dependencies = [ "mesh-llm-config", "mesh-llm-events", "serde_json", - "sha2 0.11.0", "skippy-api", "skippy-config", "skippy-hf-hub", diff --git a/ci/runner-images.json b/ci/runner-images.json index ad823ce7f9..8ab416dc60 100644 --- a/ci/runner-images.json +++ b/ci/runner-images.json @@ -476,19 +476,6 @@ } ] }, - "dflash-pairings-publish": { - "image_id": "public-cpu", - "scope": "ordinary", - "bindings": [ - { - "workflow": "dflash-pairings-publish.yml", - "job": "publish", - "matrix_selector": null, - "image_expression": "{image}", - "epoch_field": null - } - ] - }, "scripted-binary-smoke": { "image_id": "public-cpu", "scope": "ordinary", diff --git a/mesh/crates/mesh-llm-commands/Cargo.toml b/mesh/crates/mesh-llm-commands/Cargo.toml index 678843620c..bb2fd39878 100644 --- a/mesh/crates/mesh-llm-commands/Cargo.toml +++ b/mesh/crates/mesh-llm-commands/Cargo.toml @@ -29,6 +29,7 @@ mesh-llm-build-info.workspace = true mesh-llm-analytics = { path = "../mesh-llm-analytics", version = "0.78.0" } mesh-llm-cli = { path = "../mesh-llm-cli", version = "0.78.0" } skippy-hardware-profile = { path = "../../../skippy/crates/skippy-hardware-profile", version = "0.78.0" } +skippy-config = { path = "../../../skippy/crates/skippy-config", version = "0.78.0" } mesh-llm-config = { path = "../mesh-llm-config", version = "0.78.0" } mesh-llm-events = { path = "../mesh-llm-events", version = "0.78.0" } skippy-native-runtime = { path = "../../../skippy/crates/skippy-native-runtime", version = "0.78.0" } diff --git a/mesh/crates/mesh-llm-commands/src/gpus/tune/apply_write_tests.rs b/mesh/crates/mesh-llm-commands/src/gpus/tune/apply_write_tests.rs index da3f333f3e..bd60aa51ba 100644 --- a/mesh/crates/mesh-llm-commands/src/gpus/tune/apply_write_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/gpus/tune/apply_write_tests.rs @@ -269,7 +269,7 @@ fn gpu_tune_replace_existing_writes_nested_recommendations_over_legacy_manual_fi assert_eq!(model_fit.cache_type_k.as_deref(), Some("q8_0")); assert_eq!(model_fit.cache_type_v.as_deref(), Some("q8_0")); assert_eq!(model_fit.ctx_size, Some(65_536)); - assert_eq!(model_fit.batch, Some(512)); + assert_eq!(model_fit.batch, Some(2048)); assert_eq!(model_fit.ubatch, Some(512)); } diff --git a/mesh/crates/mesh-llm-commands/src/gpus/tune/planning.rs b/mesh/crates/mesh-llm-commands/src/gpus/tune/planning.rs index 5ceb9acd2a..82d44d7146 100644 --- a/mesh/crates/mesh-llm-commands/src/gpus/tune/planning.rs +++ b/mesh/crates/mesh-llm-commands/src/gpus/tune/planning.rs @@ -1,7 +1,7 @@ use super::*; -const BUILTIN_BATCH: u32 = 512; -const BUILTIN_UBATCH: u32 = 512; +const BUILTIN_BATCH: u32 = skippy_config::local_serving::BATCH; +const BUILTIN_UBATCH: u32 = skippy_config::local_serving::UBATCH; const BUILTIN_SAFETY_MARGIN_GB: f64 = 2.0; const LARGE_MODEL_MIN_BYTES: u64 = 50 * 1024 * 1024 * 1024; const MIN_AUTO_CONTEXT_LENGTH: u32 = 512; diff --git a/mesh/crates/mesh-llm-commands/src/gpus/tune/recommendation_defaults_tests.rs b/mesh/crates/mesh-llm-commands/src/gpus/tune/recommendation_defaults_tests.rs index d0e1087b27..41867668e1 100644 --- a/mesh/crates/mesh-llm-commands/src/gpus/tune/recommendation_defaults_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/gpus/tune/recommendation_defaults_tests.rs @@ -20,7 +20,7 @@ fn gpu_tune_recommends_stable_defaults() { assert_applied_kv(&plan, TuneField::CacheTypeV, TuneKvCacheType::Q8_0); assert_applied_flash_attention(&plan, TuneFlashAttentionValue::Enabled); assert_applied_context(&plan, 131_072); - assert_applied_batch(&plan, 512); + assert_applied_batch(&plan, 2048); assert_applied_ubatch(&plan, 512); assert_applied_gpu_layers(&plan, TuneGpuLayersValue::All); assert_applied_fit_target(&plan, 22 * 1024); @@ -51,7 +51,7 @@ fn gpu_tune_does_not_shadow_throughput_profile_ubatch() { survey: &survey_with_gpu(24 * gib(), 64 * gib()), }); - assert_applied_batch(&plan, 512); + assert_applied_batch(&plan, 2048); assert_preserved(&plan, TuneField::Ubatch, "throughput tuning profile"); } diff --git a/mesh/crates/mesh-llm-commands/src/gpus/tune_resolver/tests.rs b/mesh/crates/mesh-llm-commands/src/gpus/tune_resolver/tests.rs index fed6ba1441..a75cbf717a 100644 --- a/mesh/crates/mesh-llm-commands/src/gpus/tune_resolver/tests.rs +++ b/mesh/crates/mesh-llm-commands/src/gpus/tune_resolver/tests.rs @@ -60,6 +60,30 @@ fn mesh_config_with_models(models: &[String]) -> MeshConfig { #[test] fn gpu_tune_local_resolver_handles_paths_cache_refs_configured_misses_and_duplicates() { + let cache = tempdir().unwrap(); + let child = "gpus::tune_resolver::tests::local_resolver_private_cache_child"; + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", child, "--ignored", "--nocapture"]) + .current_dir(cache.path()) + .env("HF_HUB_CACHE", cache.path()) + .env("MESH_TUNE_RESOLVER_TEST_CACHE", cache.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{child} failed:\n{stdout}{stderr}"); + assert!( + stdout.contains("test result: ok. 1 passed"), + "{child} did not run:\n{stdout}{stderr}" + ); +} + +#[test] +#[ignore = "executed by the resolver test in a child with a private cache"] +fn local_resolver_private_cache_child() { + let cache = std::env::var_os("MESH_TUNE_RESOLVER_TEST_CACHE") + .expect("run this fixture through the parent resolver test"); + assert_eq!(huggingface_hub_cache_dir(), PathBuf::from(cache)); let temp = tempdir().unwrap(); let local_path = write_local_gguf_file(&temp, "sample.gguf"); let (_cache_guard, repo_id, cached_path) = diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/dflash_draft.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/dflash_draft.rs index f8e933b29b..3a4f117b15 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/dflash_draft.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/dflash_draft.rs @@ -8,70 +8,55 @@ use anyhow::{Context, Result}; use super::resolver::{ DFlashDraft, DFlashPairingIndexPin, DefaultDFlash, check_split_dflash_draft, dflash_draft_cache_path, dflash_pairing_index_installed, install_dflash_pairing_index, + load_dflash_pairing_index, }; /// Brings in the DFlash pairing index this release pins, without waiting. /// -/// The pin is the index's SHA-256. A cached `index/.json` is read from -/// the Hugging Face cache (no network, so it works offline) and, if its bytes -/// hash to the pin, replaces the bootstrap table. A missing one downloads from -/// `main` in the background; this load chooses from the bootstrap table and -/// the next load from the index. An index that is unreadable or fails its hash -/// is never used: loads keep choosing from the bootstrap table. +/// A cached index is read from the Hugging Face cache (no network, so it +/// works offline) and replaces the bootstrap table. A missing one downloads in +/// the background; this load chooses from the bootstrap table and the next +/// load from the index. Nothing happens until the index is published and +/// pinned. pub(crate) fn refresh_dflash_pairing_index() { if dflash_pairing_index_installed() { return; } - let pin = DFlashPairingIndexPin::shipped(); - refresh_cached_dflash_pairing_index(pin, pin.cached_paths(), fetch_dflash_pairing_index(pin)); -} - -/// What [`refresh_cached_dflash_pairing_index`] did. -#[derive(Debug)] -enum IndexRefresh { - /// A cached copy was installed. - Installed, - /// No cached copy was usable. The index is being fetched in the - /// background if there is a runtime and no fetch of it is running; the - /// task resolves to whether the fetched index was installed. - Fetching(Option>), + if let Some(pin) = DFlashPairingIndexPin::shipped() { + refresh_cached_dflash_pairing_index( + &pin.cache_path(), + &format!("{}/{}@{}", pin.repo, pin.file, pin.revision), + fetch_dflash_pairing_index(pin), + ); + } } -/// Installs the first usable index among the `cached` copies, or, when none -/// is usable, fetches it in the background. +/// Installs the index cached at `path`, or fetches it in the background. fn refresh_cached_dflash_pairing_index( - pin: DFlashPairingIndexPin, - cached: Vec, + path: &Path, + key: &str, fetch: impl Future> + Send + 'static, -) -> IndexRefresh { - for path in cached { - let Err(error) = install_cached_dflash_pairing_index(pin, &path) else { - return IndexRefresh::Installed; +) { + if path.is_file() { + let Err(error) = install_cached_dflash_pairing_index(path) else { + return; }; - // A partial, corrupt or wrong download: remove it so a fresh one - // replaces it. + // A partial or corrupt download: remove it so a fresh one replaces it. tracing::warn!( index = %path.display(), - "DFlash pairing index unusable: {error:#}" + "DFlash pairing index unusable, choosing from the bootstrap table: {error:#}" ); - discard_cached_artifact(&path); + discard_cached_artifact(path); } - tracing::info!("no usable DFlash pairing index cached; choosing from the bootstrap table"); - IndexRefresh::Fetching(fetch_in_background( - &pairing_index_fetch_key(pin), - async move { - let path = fetch.await?; - if let Err(error) = install_cached_dflash_pairing_index(pin, &path) { - discard_cached_artifact(&path); - return Err(error); - } - Ok(path) - }, - )) + draft_cached_or_fetch(path, key, async move { + let path = fetch.await?; + install_cached_dflash_pairing_index(&path)?; + Ok(path) + }); } -fn install_cached_dflash_pairing_index(pin: DFlashPairingIndexPin, path: &Path) -> Result<()> { - let index = pin.load(path)?; +fn install_cached_dflash_pairing_index(path: &Path) -> Result<()> { + let index = load_dflash_pairing_index(path)?; tracing::info!( index = %path.display(), pairings = index.pairings.len(), @@ -81,27 +66,17 @@ fn install_cached_dflash_pairing_index(pin: DFlashPairingIndexPin, path: &Path) Ok(()) } -fn pairing_index_fetch_key(pin: DFlashPairingIndexPin) -> String { - format!( - "{}/{}@{}", - pin.repo, - pin.file(), - DFlashPairingIndexPin::REVISION - ) -} - async fn fetch_dflash_pairing_index(pin: DFlashPairingIndexPin) -> Result { - let file = pin.file(); Ok( crate::models::catalog::download_hf_repo_file_with_progress_label( pin.repo, - Some(DFlashPairingIndexPin::REVISION), - &file, - &format!("DFlash pairing index {}/{file}", pin.repo), + Some(pin.revision), + pin.file, + &format!("DFlash pairing index {}@{}", pin.repo, pin.revision), false, ) .await - .with_context(|| format!("download {}", pairing_index_fetch_key(pin)))? + .with_context(|| format!("download {}/{}@{}", pin.repo, pin.file, pin.revision))? .path, ) } @@ -344,54 +319,37 @@ fn draft_cached_or_fetch( if path.is_file() { return true; } - fetch_in_background(key, fetch); - false -} - -/// The keys of the background fetches still running. -fn in_flight_fetches() -> &'static Mutex> { static IN_FLIGHT: OnceLock>> = OnceLock::new(); - IN_FLIGHT.get_or_init(Default::default) -} - -/// Starts `fetch` in the background, once per `key` at a time, unless there is -/// no runtime to run it on. The task resolves to whether `fetch` succeeded. -fn fetch_in_background( - key: &str, - fetch: impl Future> + Send + 'static, -) -> Option> { - let in_flight = in_flight_fetches(); - let runtime = tokio::runtime::Handle::try_current().ok()?; + let in_flight = IN_FLIGHT.get_or_init(Default::default); + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return false; + }; let key = key.to_string(); if !in_flight .lock() .is_ok_and(|mut keys| keys.insert(key.clone())) { - return None; + return false; } tracing::info!( artifact = key, "DFlash artifact is not cached; downloading it in the background, and this load goes on without it" ); - Some(runtime.spawn(async move { - let fetched = match fetch.await { - Ok(path) => { - tracing::info!( - artifact = %path.display(), - "DFlash artifact downloaded; the next load uses it" - ); - true - } + runtime.spawn(async move { + match fetch.await { + Ok(path) => tracing::info!( + artifact = %path.display(), + "DFlash artifact downloaded; the next load uses it" + ), Err(error) => { - tracing::warn!(artifact = key, "DFlash artifact download failed: {error:#}"); - false + tracing::warn!(artifact = key, "DFlash artifact download failed: {error:#}") } - }; + } if let Ok(mut keys) = in_flight.lock() { keys.remove(&key); } - fetched - })) + }); + false } async fn fetch_dflash_draft(draft: &DFlashDraft) -> Result { @@ -648,139 +606,27 @@ mod tests { ); } - /// The checked-in index this release pins. Its pairings resolve the - /// default targets as the bootstrap table does, so installing it leaves - /// other tests' defaults as they were. - fn checked_in_index() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../mesh-llm-skippy-adapter/data/dflash-pairings/index.json") - } - - /// The checked-in index's pin under a repo nothing else fetches, so a - /// test's fetch key never meets a real refresh's. - const TEST_PIN: DFlashPairingIndexPin = DFlashPairingIndexPin { - repo: "test/dflash-pairings", - sha256: mesh_llm_skippy_adapter::config::DFLASH_PAIRING_INDEX_SHA256, - }; - - /// A pin no published index hashes to, under the same test repo. - const OTHER_PIN: DFlashPairingIndexPin = DFlashPairingIndexPin { - repo: "test/dflash-pairings", - sha256: "0000000000000000000000000000000000000000000000000000000000000000", - }; - - /// The background fetch a refresh started; it resolves to whether the - /// fetched index was installed. - async fn fetched(refresh: IndexRefresh) -> bool { - let IndexRefresh::Fetching(Some(task)) = refresh else { - panic!("expected a background fetch, got {refresh:?}"); - }; - tokio::time::timeout(Duration::from_secs(5), task) - .await - .expect("background fetch did not finish") - .unwrap() - } - #[test] fn a_cached_pairing_index_is_installed_offline() { - let pin = TEST_PIN; + // The checked-in index is the bootstrap table, so installing it leaves + // other tests' defaults as they were. + let checked_in = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../skippy/evals/dflash-pairings/index.json"); let cache = tempfile::tempdir().unwrap(); let bad = cache.path().join("bad.json"); std::fs::write(&bad, "{\"schema_version\": 1, \"pairings\": [{}]}").unwrap(); // An unusable cached index is removed, so a later load fetches it again. - assert!(matches!( - refresh_cached_dflash_pairing_index(pin, vec![bad.clone()], async { - unreachable!("no runtime, so no fetch") - }), - IndexRefresh::Fetching(None) - )); + refresh_cached_dflash_pairing_index(&bad, "test/bad-index", async { + unreachable!("no runtime, so no fetch") + }); assert!(!bad.exists()); - let cached = cache.path().join(pin.file()); - std::fs::create_dir_all(cached.parent().unwrap()).unwrap(); - std::fs::copy(checked_in_index(), &cached).unwrap(); - // A corrupt copy in one snapshot does not hide a good one in another. - let corrupt = cache.path().join("corrupt.json"); - std::fs::write(&corrupt, "corrupt").unwrap(); + let cached = cache.path().join("index.json"); + std::fs::copy(checked_in, &cached).unwrap(); // No runtime and a fetch that must not run: the cache alone serves. - assert!(matches!( - refresh_cached_dflash_pairing_index( - pin, - vec![corrupt.clone(), cached.clone()], - async { unreachable!("a cached index is never fetched") } - ), - IndexRefresh::Installed - )); - assert!(dflash_pairing_index_installed()); - assert!(!corrupt.exists()); - assert!(cached.exists()); - } - - #[test] - fn a_cached_index_that_fails_its_hash_falls_back_to_the_bootstrap_table() { - let cache = tempfile::tempdir().unwrap(); - // A valid index, but not the one the pin names. - let cached = cache.path().join(OTHER_PIN.file()); - std::fs::create_dir_all(cached.parent().unwrap()).unwrap(); - std::fs::copy(checked_in_index(), &cached).unwrap(); - let error = install_cached_dflash_pairing_index(OTHER_PIN, &cached) - .unwrap_err() - .to_string(); - assert!(error.contains("expected"), "{error}"); - // Not installed, so loads keep choosing from the bootstrap table, and - // removed, so a later load fetches it again. - assert!(matches!( - refresh_cached_dflash_pairing_index(OTHER_PIN, vec![cached.clone()], async { - unreachable!("no runtime, so no fetch") - }), - IndexRefresh::Fetching(None) - )); - assert!(!cached.exists()); - } - - #[test] - fn the_pairing_index_is_fetched_by_its_hash_from_main() { - let pin = DFlashPairingIndexPin::shipped(); - assert_eq!( - pairing_index_fetch_key(pin), - format!( - "meshllm/dflash-pairings/index/{}.json@main", - mesh_llm_skippy_adapter::config::DFLASH_PAIRING_INDEX_SHA256 - ) - ); - assert_ne!( - pairing_index_fetch_key(pin), - pairing_index_fetch_key(TEST_PIN) - ); - assert_ne!( - pairing_index_fetch_key(TEST_PIN), - pairing_index_fetch_key(OTHER_PIN) - ); - } - - #[tokio::test] - async fn a_fetched_pairing_index_is_installed_only_if_it_hashes_to_the_pin() { - let snapshot = tempfile::tempdir().unwrap(); - - // A download whose bytes do not hash to the pin is discarded. - let wrong = snapshot.path().join(OTHER_PIN.file()); - std::fs::create_dir_all(wrong.parent().unwrap()).unwrap(); - std::fs::copy(checked_in_index(), &wrong).unwrap(); - let download = wrong.clone(); - let refresh = - refresh_cached_dflash_pairing_index(OTHER_PIN, Vec::new(), async move { Ok(download) }); - assert!(!fetched(refresh).await); - assert!(!wrong.exists()); - - // The pinned download is installed: the fetch reports its install, - // whatever other tests did to the process-wide index. - let right = snapshot.path().join(TEST_PIN.file()); - std::fs::copy(checked_in_index(), &right).unwrap(); - let download = right.clone(); - let refresh = - refresh_cached_dflash_pairing_index(TEST_PIN, Vec::new(), async move { Ok(download) }); - assert!(fetched(refresh).await); + refresh_cached_dflash_pairing_index(&cached, "test/index", async { + unreachable!("a cached index is never fetched") + }); assert!(dflash_pairing_index_installed()); - assert!(right.exists()); } #[test] diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs index e4889dabc9..8189adbbd2 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/loading.rs @@ -1105,10 +1105,13 @@ pub(super) async fn split_generation_load_settings_with<'a>( Some(_) => Some(split_dflash_fallback(&resolved, spec, &load_mode)?), None => None, }; - runtime_options.recurrent_rollback_tokens = split_dflash.as_ref().map_or( - 0, - skippy_serving::split_dflash::SplitDFlashStage::recurrent_rollback_tokens, - ); + runtime_options.recurrent_rollback_tokens = + runtime_options + .recurrent_rollback_tokens + .max(split_dflash.as_ref().map_or( + 0, + skippy_serving::split_dflash::SplitDFlashStage::recurrent_rollback_tokens, + )); tracing::info!( model = spec.model_ref, "KV cache: {} K + {} V", diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs index f02ea8ed28..235a36b916 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_split/test_support.rs @@ -548,6 +548,9 @@ stop = ["END"] Some(projector_path.to_string_lossy().as_ref()) ); assert!(!settings.runtime_options.config.native_mtp_enabled); + // The attached external draft remains active even with the legacy + // strategy label "disabled"; size its actual seven-input serial window. + assert_eq!(settings.runtime_options.recurrent_rollback_tokens, 7); assert!(!settings.embedded_openai.native_mtp_enabled); assert_eq!(settings.embedded_openai.generation_concurrency, 4); assert_eq!(settings.embedded_openai.default_max_tokens, 321); @@ -791,6 +794,7 @@ async fn split_load_of_a_paired_native_mtp_target_keeps_native_mtp() { assert!(unreadable.split_dflash.is_none()); assert!(unreadable.embedded_openai.native_mtp_enabled); assert!(settings.runtime_options.config.native_mtp_enabled); + assert!(settings.runtime_options.recurrent_rollback_tokens > 0); assert!(settings.embedded_openai.native_mtp_enabled); assert!(settings.embedded_openai.speculative.dflash.is_none()); assert_eq!( diff --git a/mesh/crates/mesh-llm-skippy-adapter/Cargo.toml b/mesh/crates/mesh-llm-skippy-adapter/Cargo.toml index 4db23a98b4..bf1899a874 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/Cargo.toml +++ b/mesh/crates/mesh-llm-skippy-adapter/Cargo.toml @@ -32,7 +32,6 @@ skippy-serving = { path = "../../../skippy/crates/skippy-serving", version = "0. anyhow = "1" dirs = "6.0.0" serde_json = "1" -sha2.workspace = true toml = "1.1" [dev-dependencies] diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/dflash_catalog.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/dflash_catalog.rs index 66b5a4cfd4..32c9d1e00e 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/dflash_catalog.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/dflash_catalog.rs @@ -6,14 +6,14 @@ //! cache on first load and serves without speculation if it cannot. //! //! The default draft comes from, in order: the layer package's own `dflash` -//! proposer, the pairing index this release pins by content hash, and, until -//! that index is cached (or if it cannot be read or fails its hash), the -//! bootstrap table compiled in here. +//! proposer, the pairing index published on Hugging Face at the revision this +//! release pins, and, until that index is published and cached, the bootstrap +//! table compiled in here. use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, RwLock}; -use anyhow::{Result, bail, ensure}; +use anyhow::{Context, Result, bail, ensure}; use hf_hub::RepoTypeModel; use skippy_model_artifact::gguf::{ GgufCompactMeta, scan_gguf_compact_meta, scan_gguf_dflash_target_layers, @@ -25,8 +25,44 @@ pub use skippy_package_format::{ }; use skippy_runtime::package::PackageGenerationInfo; -#[cfg(test)] -use super::dflash_index::load_dflash_pairing_index; +/// The Hugging Face repo that publishes the DFlash pairing index. +pub const DFLASH_PAIRING_INDEX_REPO: &str = "meshllm/dflash-pairings"; +/// The index file in [`DFLASH_PAIRING_INDEX_REPO`]. +pub const DFLASH_PAIRING_INDEX_FILE: &str = "index.json"; +/// The one index commit this release trusts. +pub const DFLASH_PAIRING_INDEX_REVISION: Option<&str> = + Some("91c1cb2cc50f4087ac73a7a74b01670a18015059"); + +/// A pairing index file pinned to one commit of a Hugging Face repo. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DFlashPairingIndexPin { + pub repo: &'static str, + pub revision: &'static str, + pub file: &'static str, +} + +impl DFlashPairingIndexPin { + /// The index this release trusts, once it is published. + pub fn shipped() -> Option { + DFLASH_PAIRING_INDEX_REVISION.map(|revision| Self { + repo: DFLASH_PAIRING_INDEX_REPO, + revision, + file: DFLASH_PAIRING_INDEX_FILE, + }) + } + + /// Where the Hugging Face cache keeps the index once fetched. + pub fn cache_path(&self) -> PathBuf { + huggingface_snapshot_path(self.repo, RepoTypeModel, self.revision).join(self.file) + } +} + +/// Reads and validates a pairing index file. +pub fn load_dflash_pairing_index(path: &Path) -> Result { + let json = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?; + DFlashPairingIndex::from_json(&json) + .map_err(|error| anyhow::anyhow!("{}: {error}", path.display())) +} static INSTALLED_INDEX: RwLock>>> = RwLock::new(None); static BOOTSTRAP_PAIRINGS: LazyLock>> = @@ -100,12 +136,13 @@ pub struct DefaultDFlash { pub source: DFlashPairingSource, } -/// The pairings this release falls back to until the pinned index is cached, -/// or when it cannot be read or fails its hash. +/// The pairings this release ships, used only until the published index is +/// cached. /// -/// TODO: delete once packages declare their drafts; the index -/// (`data/dflash-pairings/index.json`) is the source of truth, and a test -/// checks that it pairs every target here the same way. +/// TODO: delete once `meshllm/dflash-pairings` is published and +/// [`DFLASH_PAIRING_INDEX_REVISION`] pins it; the index then carries these +/// pairings (`skippy/evals/dflash-pairings/index.json` is generated from this +/// table). pub(super) fn bootstrap_pairings() -> Vec { vec![ // Qwen3.5-9B; the draft reads target layers 2..=30 at width 4096. @@ -583,6 +620,37 @@ mod tests { pairing_in(&bootstrap_pairings(), meta, metal).map(|pairing| pairing.draft.repo.clone()) } + const INDEX_PATH: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../skippy/evals/dflash-pairings/index.json" + ); + + /// The bootstrap table as the index `meshllm/dflash-pairings` publishes. + fn generated_index_json() -> String { + let index = DFlashPairingIndex { + schema_version: skippy_package_format::DFLASH_PAIRING_INDEX_SCHEMA_VERSION, + pairings: bootstrap_pairings(), + }; + serde_json::to_string_pretty(&index).unwrap() + "\n" + } + + /// `UPDATE_DFLASH_PAIRINGS_INDEX=1` rewrites the checked-in index from + /// the bootstrap table. + #[test] + fn the_checked_in_index_is_the_bootstrap_table() { + let generated = generated_index_json(); + if std::env::var_os("UPDATE_DFLASH_PAIRINGS_INDEX").is_some() { + std::fs::write(INDEX_PATH, &generated).unwrap(); + } + let checked_in = std::fs::read_to_string(INDEX_PATH).unwrap(); + assert_eq!( + checked_in, generated, + "regenerate with UPDATE_DFLASH_PAIRINGS_INDEX=1 cargo test -p mesh-llm-skippy-adapter the_checked_in_index" + ); + let index = load_dflash_pairing_index(Path::new(INDEX_PATH)).unwrap(); + assert_eq!(index.pairings, bootstrap_pairings()); + } + /// Every target the bootstrap table pairs by default, named as its GGUF /// names it: Qwen3.5-9B, Qwen3.6-27B, Qwen3.8-27B (with its NextN block), /// Qwen3.6-35B-A3B, Qwen3-Coder-Next, Nemotron-3.5-Bolt-E4B and @@ -624,13 +692,12 @@ mod tests { ] } - /// The pinned index: the checked-in `index.json`, or the file + /// The published index: the checked-in copy of `index.json` at + /// [`DFLASH_PAIRING_INDEX_REVISION`], or the file /// `DFLASH_PAIRING_INDEX_FIXTURE` names (a fresh download, say). fn published_index() -> DFlashPairingIndex { - let path = std::env::var_os("DFLASH_PAIRING_INDEX_FIXTURE").map_or_else( - || PathBuf::from(super::super::dflash_index::INDEX_PATH), - PathBuf::from, - ); + let path = std::env::var_os("DFLASH_PAIRING_INDEX_FIXTURE") + .map_or_else(|| PathBuf::from(INDEX_PATH), PathBuf::from); load_dflash_pairing_index(&path).unwrap() } @@ -1036,4 +1103,22 @@ mod tests { let error = load_dflash_pairing_index(&path).unwrap_err().to_string(); assert!(error.contains("sha256"), "{error}"); } + + #[test] + fn the_index_is_pinned_to_one_revision_of_its_repo() { + assert_eq!(DFLASH_PAIRING_INDEX_REPO, "meshllm/dflash-pairings"); + assert_eq!(DFLASH_PAIRING_INDEX_FILE, "index.json"); + if let Some(revision) = DFLASH_PAIRING_INDEX_REVISION { + assert_eq!(revision.len(), 40); + assert!(revision.bytes().all(|byte| byte.is_ascii_hexdigit())); + } + let pin = DFlashPairingIndexPin { + repo: DFLASH_PAIRING_INDEX_REPO, + revision: "0123456789abcdef0123456789abcdef01234567", + file: DFLASH_PAIRING_INDEX_FILE, + }; + assert!(pin.cache_path().ends_with( + "models--meshllm--dflash-pairings/snapshots/0123456789abcdef0123456789abcdef01234567/index.json" + )); + } } diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/mod.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/mod.rs index f7830927fa..c5d982d492 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/mod.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/mod.rs @@ -1,6 +1,5 @@ mod dflash; mod dflash_catalog; -mod dflash_index; mod request_defaults; mod resolution; mod speculative; @@ -23,6 +22,9 @@ mod tests; #[cfg(test)] mod speculative_tests; +#[cfg(test)] +mod recurrent_rollback_tests; + #[cfg(test)] mod exact_head_tests; @@ -33,12 +35,11 @@ mod hardware_tests; mod hardware_translation_tests; pub use dflash_catalog::{ - DFlashBackends, DFlashDraft, DFlashPairing, DFlashPairingIndex, DFlashPairingSource, - DFlashTarget, DefaultDFlash, check_split_dflash_draft, dflash_draft_cache_path, - dflash_pairing_index_installed, install_dflash_pairing_index, -}; -pub use dflash_index::{ - DFLASH_PAIRING_INDEX_REPO, DFLASH_PAIRING_INDEX_SHA256, DFlashPairingIndexPin, + DFLASH_PAIRING_INDEX_FILE, DFLASH_PAIRING_INDEX_REPO, DFLASH_PAIRING_INDEX_REVISION, + DFlashBackends, DFlashDraft, DFlashPairing, DFlashPairingIndex, DFlashPairingIndexPin, + DFlashPairingSource, DFlashTarget, DefaultDFlash, check_split_dflash_draft, + dflash_draft_cache_path, dflash_pairing_index_installed, install_dflash_pairing_index, + load_dflash_pairing_index, }; #[cfg(test)] pub(crate) use resolution::resolve_skippy_config; diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/recurrent_rollback_tests.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/recurrent_rollback_tests.rs new file mode 100644 index 0000000000..3f3a69ebc6 --- /dev/null +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/recurrent_rollback_tests.rs @@ -0,0 +1,41 @@ +use super::test_support::{parse_config, temp_model_file}; +use super::*; +use crate::SkippyTelemetryOptions; +use skippy_protocol::LoadMode; + +#[test] +fn embedded_runtime_sizes_only_active_speculative_plans() { + let config = parse_config("[defaults.speculative]\nmode = \"disabled\"\n"); + let model = temp_model_file(); + let mut resolved = resolve_skippy_config(SkippyConfigResolveRequest { + mesh_config: &config, + model_id: "test-model", + model_path: model.path(), + model_bytes: 4 * 1024 * 1024 * 1024, + allocatable_memory_bytes: None, + request_defaults: None, + package_generation: None, + compact_meta: None, + }) + .unwrap(); + let depth = |resolved: &ResolvedSkippyConfig| { + resolved + .to_embedded_runtime_options( + &SkippyTelemetryOptions::off(), + None, + LoadMode::RuntimeSlice, + ) + .unwrap() + .recurrent_rollback_tokens + }; + assert_eq!(depth(&resolved), 0); + resolved.speculative.native_mtp_enabled = true; + resolved.speculative.draft_max_tokens = 6; + assert_eq!(depth(&resolved), 7); + resolved.speculative.native_mtp_enabled = false; + resolved.speculative.draft_model_path = Some("draft.gguf".into()); + resolved.speculative.draft_max_tokens = 8; + assert_eq!(depth(&resolved), 8); + resolved.speculative.draft_model_path = None; + assert_eq!(depth(&resolved), 0); +} diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/speculative_tests.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/speculative_tests.rs index 50a9d45675..1889243775 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/speculative_tests.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/speculative_tests.rs @@ -1621,16 +1621,20 @@ fn native_mtp_is_preferred_only_when_no_pairing_exists() { assert_eq!(resolved.speculative.decode.effective_strategy, "native-mtp"); } -/// The pinned index (the checked-in `data/dflash-pairings/index.json`, or the -/// copy `DFLASH_PAIRING_INDEX_FIXTURE` names) resolves every default-on target -/// on this backend to the plan the bootstrap table resolves. +/// The published index (`index.json` at the pinned revision, checked in as +/// `skippy/evals/dflash-pairings/index.json`, or the copy +/// `DFLASH_PAIRING_INDEX_FIXTURE` names) resolves every default-on target on +/// this backend to the plan the bootstrap table resolves. #[test] fn the_published_index_resolves_every_default_as_the_table_does() { let path = std::env::var_os("DFLASH_PAIRING_INDEX_FIXTURE").map_or_else( - || Path::new(env!("CARGO_MANIFEST_DIR")).join("data/dflash-pairings/index.json"), + || { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../skippy/evals/dflash-pairings/index.json") + }, std::path::PathBuf::from, ); - let index = super::dflash_index::load_dflash_pairing_index(&path).unwrap(); + let index = super::dflash_catalog::load_dflash_pairing_index(&path).unwrap(); let metal = cfg!(target_os = "macos"); let (_plain_directory, plain) = default_dflash_target(); let (_mtp_directory, with_mtp) = native_mtp_target(); diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs index 9b4310eca9..ec99ae7e6e 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs @@ -323,7 +323,16 @@ impl ResolvedSkippyConfig { } else { MtpSource::Disabled }, - recurrent_rollback_tokens: 0, + recurrent_rollback_tokens: self.speculative.decode.recurrent_rollback_tokens( + self.speculative + .native_mtp_enabled + .then_some(self.speculative.draft_max_tokens as usize), + self.speculative + .draft_model_path + .as_ref() + .filter(|_| !self.speculative.native_mtp_enabled) + .map(|_| self.speculative.draft_max_tokens as usize), + ), metrics_otlp_grpc: telemetry.metrics_otlp_grpc.clone(), telemetry_queue_capacity: telemetry.queue_capacity, telemetry_level: telemetry.level, diff --git a/mesh/website/src/docs/pages/skippy-api.md b/mesh/website/src/docs/pages/skippy-api.md index b5244bcef9..e71d17759d 100644 --- a/mesh/website/src/docs/pages/skippy-api.md +++ b/mesh/website/src/docs/pages/skippy-api.md @@ -9,7 +9,7 @@ description: Generated reference for the capability-oriented Skippy C ABI. This reference is generated from the patched llama.cpp public headers. It documents the native C ABI used by Skippy's Rust FFI layer and staged runtime. The ABI is experimental and versioned for lockstep native/Rust builds. -Current generated surface: **21 headers** and **134 exported functions**. +Current generated surface: **22 headers** and **137 exported functions**. ## Quick navigation @@ -241,6 +241,14 @@ Current generated surface: **21 headers** and **134 exported functions**. skippy_parse_chat_response_json
+
+ tracing.h3 functions + +
workloads.h4 functions
@@ -286,6 +294,7 @@ Capability consumers can include a narrower header: | `include/skippy/state.h` | Moves KV, recurrent, checkpoint, and resident-prefix state. | | `include/skippy/system_one.h` | One-pass structured label scoring for diffusion decision models. | | `include/skippy/tokenization.h` | Token, detokenization, chat-template, and chat-response helpers. | +| `include/skippy/tracing.h` | Where time goes inside native calls: native spans and GPU command timing. Requires SKIPPY_FEATURE_NATIVE_TRACING. Two callbacks report what a native call did, for a caller that already times the call itself. Native spans name the phases of host work (preparing a batch, building and allocating the llama graph, encoding it, waiting for the device, extracting outputs, sampling, and in a backend that reports them, compiling kernel libraries and pipelines); each arrives when it ends, on the thread that did the work. GPU command timing reports each unit of device work (Metal: a command buffer) once the device has finished it, on a backend completion thread. Both carry the tag the calling thread set with skippy_set_trace_tag, so a caller that sets a fresh tag before each native call can place everything the call caused under it, though spans and device records arrive later. | | `include/skippy/workloads.h` | Full-model embedding, reranking, and encoder-decoder execution. These operations deliberately reject filtered stage models. Their explicit workload descriptor lets callers fail closed instead of inferring support from a model name or architecture family. | @@ -1216,7 +1225,7 @@ LLAMA_API enum skippy_status skippy_model_open_from_source( #### `skippy_runtime_config_default` -Returns a C-safe runtime configuration with all derived-default controls set to auto. +Returns a C-safe runtime configuration with derived-default controls set to auto and recurrent rollback depth explicitly set to 2. Set recurrent_rollback_tokens to 0 when no speculative rollback snapshots are wanted. ```cpp LLAMA_API struct skippy_runtime_config skippy_runtime_config_default( @@ -2179,6 +2188,43 @@ SKIPPY_COMMON_API enum skippy_status skippy_parse_chat_response_json( ↩ Back to function index + +### `tracing.h` + + +#### `skippy_set_native_span_callback` + +Installs the process-global native span callback. Install once, before the calls to observe; a null callback stops reporting. A callback already running may finish after it is cleared. Installing reaches every loaded backend, which may initialise the backend registry on the calling thread. Backend spans that ended before a backend received its first callback (device initialisation compiles kernel libraries) are delivered from within this call: those that began during it under the calling thread's tag, earlier ones with no parent. + +```cpp +LLAMA_API enum skippy_status skippy_set_native_span_callback( + skippy_native_span_callback callback, + void * user_data); +``` + + +#### `skippy_set_gpu_command_timing_callback` + +Installs the process-global GPU command timing callback. Install once, before submitting work; a null callback stops reporting. A callback already running may finish after it is cleared. Returns SKIPPY_STATUS_UNSUPPORTED when no loaded backend reports command timing. + +```cpp +LLAMA_API enum skippy_status skippy_set_gpu_command_timing_callback( + skippy_gpu_command_timing_callback callback, + void * user_data); +``` + + +#### `skippy_set_trace_tag` + +Sets the calling thread's trace tag for the work it does afterwards. Native spans without an enclosing native span, and GPU work the thread submits, carry the tag. Thread-local and cheap; pass 0 to stop tagging. Tags should leave SKIPPY_NATIVE_SPAN_ID_BIT clear. Backends see the tag once either callback has been installed. + +```cpp +LLAMA_API void skippy_set_trace_tag( + uint64_t tag); +``` + +↩ Back to function index + ### `workloads.h` @@ -2249,7 +2295,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `activation.h`: `skippy_activation_part_desc`, `skippy_activation_boundary_desc`, `skippy_activation_desc`, `SKIPPY_ACTIVATION_FRAME_VERSION = 2`, `SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION = 2`, `SKIPPY_ACTIVATION_IDENTITY_BYTES = 32`, `SKIPPY_ACTIVATION_MAX_DIMS = 4`, `SKIPPY_ACTIVATION_MAX_PARTS = 16`, `SKIPPY_ACTIVATION_PART_OPTIONAL = (UINT32_C(1) << 0)` - `asr.h`: `skippy_asr_model`, `skippy_asr_result`, `skippy_asr_info_v1`, `skippy_asr_transcribe_params_v1`, `skippy_asr_segment_v1`, `SKIPPY_ASR_INFO_V1_ABI_VERSION = 1`, `SKIPPY_ASR_TRANSCRIBE_PARAMS_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SEGMENT_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SAMPLE_RATE = 16000`, `SKIPPY_ASR_MAX_SAMPLES = (SKIPPY_ASR_SAMPLE_RATE * 60 * 30)` - `clef.h`: `skippy_clef_model`, `skippy_clef_order`, `skippy_clef_info_v1`, `SKIPPY_CLEF_INFO_V1_ABI_VERSION = 1` -- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 79`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` +- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 81`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` - `devices.h`: `skippy_backend_device_type`, `skippy_backend_device_cap`, `skippy_backend_device` - `events.h`: `skippy_runtime_event_v1`, `skippy_runtime_event_reporter_v1`, `SKIPPY_RUNTIME_EVENT_V1_ABI_VERSION = 1` - `execution.h`: `skippy_token_score_request`, `skippy_iteration_request` @@ -2264,6 +2310,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `stage_plan.h`: `skippy_stage_planner`, `skippy_stage_plan`, `skippy_stage_plan_string_ref_v1`, `skippy_stage_planner_tensor_v1`, `skippy_stage_planner_profile_v1`, `skippy_stage_planner_config_v1`, `skippy_stage_plan_value_kind`, `skippy_stage_plan_state_kind`, `skippy_stage_plan_state_access`, `skippy_stage_plan_state_residency`, `skippy_stage_plan_desc_v1`, `skippy_stage_plan_profile_desc_v1`, `skippy_stage_plan_value_desc_v1`, `skippy_stage_plan_state_desc_v1`, `SKIPPY_STAGE_PLANNER_CONFIG_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_TENSOR_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_PROFILE_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_PROFILE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_VALUE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_STATE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_MAX_DIMS = 4` - `state.h`: `skippy_memory_cache_capability`, `skippy_kv_page_flag`, `skippy_kv_page_codec`, `skippy_kv_page_component_role`, `skippy_cachegen_record_kind`, `skippy_cachegen_record_v1`, `skippy_kv_page_component_desc`, `skippy_kv_page_desc`, `SKIPPY_CACHEGEN_RECORD_V1_ABI_VERSION = 1` - `system_one.h`: `skippy_model`, `skippy_system_one_slot` +- `tracing.h`: `skippy_native_span_v1`, `skippy_gpu_command_timing_v1`, `SKIPPY_NATIVE_SPAN_V1_ABI_VERSION = 1`, `SKIPPY_NATIVE_SPAN_ID_BIT = (UINT64_C(1) << 63)`, `SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION = 1` - `workloads.h`: `skippy_model`, `skippy_session`, `skippy_workload_kind`, `skippy_workload_pooling`, `skippy_workload_info_v1`, `SKIPPY_WORKLOAD_INFO_V1_ABI_VERSION = 1` Source directory: `include/skippy/`. Regenerate this page after changing any public header or exported function. diff --git a/scripts/run-llama-benchy-openai.sh b/scripts/run-llama-benchy-openai.sh index 9614c123dd..63f62f86c0 100755 --- a/scripts/run-llama-benchy-openai.sh +++ b/scripts/run-llama-benchy-openai.sh @@ -20,6 +20,7 @@ SAVE_RESULT="${SAVE_RESULT:-}" SKIP_COHERENCE="${SKIP_COHERENCE:-1}" NO_ADAPT_PROMPT="${NO_ADAPT_PROMPT:-0}" NO_CACHE="${NO_CACHE:-0}" +PREFIX_CACHING="${PREFIX_CACHING:-0}" discover_model() { local -a automation=(cargo xtool) @@ -82,6 +83,9 @@ fi if [[ "$NO_CACHE" == "1" ]]; then cmd+=(--no-cache) fi +if [[ "$PREFIX_CACHING" == "1" ]]; then + cmd+=(--enable-prefix-caching) +fi printf 'Running:' # External benchy still requires its existing --api-key argv; never echo it. diff --git a/skippy/crates/llama-spec-bench/src/main.rs b/skippy/crates/llama-spec-bench/src/main.rs index 7baccb066f..835c8e0c71 100644 --- a/skippy/crates/llama-spec-bench/src/main.rs +++ b/skippy/crates/llama-spec-bench/src/main.rs @@ -183,8 +183,13 @@ fn main() -> Result<()> { args.speculative_window ); - let target_config = + let mut target_config = full_model_config(&args.target_model_path, args.ctx_size, args.n_gpu_layers)?; + // This context later verifies drafts, even though its first run is serial. + // DFlash includes the current-token anchor; reserve that bound for both + // benchmark modes rather than relying on a native default. + target_config.recurrent_rollback_tokens = + u32::try_from(args.speculative_window.saturating_add(1)).unwrap_or(u32::MAX); let mut target = StageModel::open(&args.target_model_path, &target_config) .with_context(|| format!("open target model {}", args.target_model_path.display()))?; // Baselines run before any draft exists: an attached DFlash draft makes diff --git a/skippy/crates/skippy-api/README.md b/skippy/crates/skippy-api/README.md index 5908da5b70..63d9289dd6 100644 --- a/skippy/crates/skippy-api/README.md +++ b/skippy/crates/skippy-api/README.md @@ -24,6 +24,14 @@ Guardrail/compaction wrapping uses the serving library implementation, including an optional caller-owned telemetry sink. `ModelOpenEvents` preserves the native load-with-events choice independently of whether an observer is supplied. +Before opening the target, model loading derives recurrent rollback retention +from enabled speculative proposals and preserves any larger caller-supplied +depth. In native ABI 0.1.81, an explicit zero disables recurrent snapshots for +ordinary decoding; direct runtime users must request positive retention for +in-place verification. Windows outside native retention continue through the +existing checkpoint/replay fallback. The C configuration factory and a null C +configuration retain their explicit legacy depth of two. + `native_runtime` selects and loads an explicitly supplied runtime bundle/cache. It performs no product discovery and does not download implicitly. The dependency direction is API → serving; the serving library does not depend on this API. diff --git a/skippy/crates/skippy-api/src/serving/lifecycle.rs b/skippy/crates/skippy-api/src/serving/lifecycle.rs index f2b84ebb53..d16f058abb 100644 --- a/skippy/crates/skippy-api/src/serving/lifecycle.rs +++ b/skippy/crates/skippy-api/src/serving/lifecycle.rs @@ -147,15 +147,19 @@ impl ModelLoadRequest { } impl ModelLoadRequest { - /// The target context is sized when it opens, before the DFlash draft - /// attaches, so the plan's rollback depth must travel with the runtime. + /// Size the target before any proposal model attaches or verification runs. fn size_recurrent_rollback(&mut self) { - if let Some(dflash) = &self.openai.speculative.dflash { - self.runtime.recurrent_rollback_tokens = self - .runtime - .recurrent_rollback_tokens - .max(dflash.recurrent_rollback_tokens()); - } + let planned = self.openai.speculative.recurrent_rollback_tokens( + self.openai + .native_mtp_enabled + .then_some(self.openai.native_mtp_max_tokens), + self.openai + .draft_model_path + .as_ref() + .map(|_| self.openai.speculative_window), + ); + self.runtime.recurrent_rollback_tokens = + self.runtime.recurrent_rollback_tokens.max(planned); } } @@ -270,6 +274,24 @@ mod tests { } } + #[test] + fn rollback_plan_covers_mtp_and_external_draft_before_open() { + let mut request = request(); + request.openai.native_mtp_enabled = true; + request.openai.native_mtp_max_tokens = 9; + request.size_recurrent_rollback(); + assert_eq!(request.runtime.recurrent_rollback_tokens, 10); + + request.openai.native_mtp_enabled = false; + request.openai.draft_model_path = Some("draft.gguf".into()); + request.openai.speculative_window = 12; + request.size_recurrent_rollback(); + assert_eq!(request.runtime.recurrent_rollback_tokens, 12); + request.runtime.recurrent_rollback_tokens = 20; + request.size_recurrent_rollback(); + assert_eq!(request.runtime.recurrent_rollback_tokens, 20); + } + #[test] fn worker_stage_is_rejected_before_native_loading() { let mut request = request(); diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 514d838109..29cd6dea63 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -2,7 +2,7 @@ "schema_version": 2, "native_recipe": { "llama_upstream_sha": "372dc5ca157276beb6c67b2e92477e8d662e964a", - "skippy_abi": "0.1.79", + "skippy_abi": "0.1.81", "patch_queue_sha256": "43a8209ac0ff99481d764c6b7c1ecef8943af7285643dcfaea958d5f7e7de026" }, "architectures": [ diff --git a/skippy/crates/skippy-cache/src/l3.rs b/skippy/crates/skippy-cache/src/l3.rs index 1308452fd5..bb9c2caa70 100644 --- a/skippy/crates/skippy-cache/src/l3.rs +++ b/skippy/crates/skippy-cache/src/l3.rs @@ -35,7 +35,9 @@ use serde::{Deserialize, Serialize}; use crate::fsinfo; mod packed; +mod pressure; use packed::{PACK_DIR, PACK_INDEX_DIR, PackedReadRequest, PackedSegmentStore}; +pub use pressure::StorePressure; const SEGMENT_DIR: &str = "segments"; const MANIFEST_DIR: &str = "manifests"; diff --git a/skippy/crates/skippy-cache/src/l3/pressure.rs b/skippy/crates/skippy-cache/src/l3/pressure.rs new file mode 100644 index 0000000000..48a0634233 --- /dev/null +++ b/skippy/crates/skippy-cache/src/l3/pressure.rs @@ -0,0 +1,72 @@ +//! How full the store is, from its running counters. `usage` lists and loads +//! every manifest, which is right for the status contract and too slow for a +//! sampler that reads the store several times a second. + +use std::sync::atomic::Ordering; + +use super::HandoffSegmentStore; +use crate::fsinfo; + +/// The store's budget and occupancy, read without touching its files except +/// for one filesystem free-space query. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StorePressure { + pub budget_bytes: u64, + /// Managed bytes on disk plus in-flight reservations; `None` until a scan + /// has established the running total the store keeps between scans. + pub used_bytes: Option, + pub reserved_inflight_bytes: u64, + pub filesystem_available_bytes: Option, + pub minimum_free_bytes: u64, + /// Manifests removed by budget enforcement or prune since open. + pub evicted_manifests: u64, + /// Objects quarantined after failing verification since open. + pub quarantined_objects: u64, +} + +impl HandoffSegmentStore { + pub fn pressure(&self) -> StorePressure { + let limits = self.limits(); + let reserved = self.reserved_inflight.load(Ordering::Acquire); + let used_bytes = self.usage_valid.load(Ordering::Acquire).then(|| { + self.usage_bytes + .load(Ordering::Acquire) + .saturating_add(reserved) + }); + StorePressure { + budget_bytes: limits.budget_bytes, + used_bytes, + reserved_inflight_bytes: reserved, + filesystem_available_bytes: fsinfo::available_bytes(&self.root).ok(), + minimum_free_bytes: limits.minimum_free_bytes, + evicted_manifests: self.evicted_manifests.load(Ordering::Relaxed), + quarantined_objects: self.quarantined_objects.load(Ordering::Relaxed), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pressure_reports_the_budget_and_the_running_total_once_known() { + let root = std::env::temp_dir() + .join("skippy-l3-tests") + .join(format!("pressure-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let store = HandoffSegmentStore::open(&root, 1 << 20).expect("open store"); + let before = store.pressure(); + assert_eq!(before.budget_bytes, 1 << 20); + assert!(before.filesystem_available_bytes.is_some()); + + store.put_segment(&[7u8; 4096]).expect("put segment"); + let usage = store.usage().expect("usage"); + let after = store.pressure(); + assert_eq!(after.used_bytes, Some(usage.used_bytes)); + assert_eq!(after.evicted_manifests, usage.evicted_manifests); + assert_eq!(after.quarantined_objects, usage.quarantined_objects); + drop(store); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/skippy/crates/skippy-cache/src/lib.rs b/skippy/crates/skippy-cache/src/lib.rs index a14df9c1cb..fbc6e33c5a 100644 --- a/skippy/crates/skippy-cache/src/lib.rs +++ b/skippy/crates/skippy-cache/src/lib.rs @@ -31,7 +31,7 @@ pub use l3::{ GeometryKind, HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, LEGACY_MANIFEST_VERSION, LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION, MANIFEST_VERSION, ManifestPin, PayloadCodec, PayloadGeometry, Reservation, SegmentCodecIdentity, SegmentHold, SegmentPut, StoreLimits, - StoreReconciliation, StoreUsage, StoredSegment, WriteRefusal, segment_digest, + StorePressure, StoreReconciliation, StoreUsage, StoredSegment, WriteRefusal, segment_digest, }; pub use l3_remote::{ FetchStats, KvFetchClient, serve_connection, serve_store, serve_store_with_timeout, diff --git a/skippy/crates/skippy-cache/src/manager.rs b/skippy/crates/skippy-cache/src/manager.rs index cd306060dc..210ec4fc00 100644 --- a/skippy/crates/skippy-cache/src/manager.rs +++ b/skippy/crates/skippy-cache/src/manager.rs @@ -467,6 +467,17 @@ impl L3CacheManager { Ok(self.inner.activity.snapshot(Some(&usage))) } + /// `activity` without its manifest scan: evictions and corrupt entries + /// come from the store's running counters, as `usage` reports them. + pub fn activity_without_inventory(&self) -> L3ActivitySnapshot { + let pressure = self.inner.store.pressure(); + L3ActivitySnapshot { + evictions: pressure.evicted_manifests, + corrupt_entries: pressure.quarantined_objects, + ..self.inner.activity.snapshot(None) + } + } + pub fn inventory(&self) -> Result> { let mut inventory = self .inner @@ -720,6 +731,34 @@ mod tests { } } + #[test] + fn activity_without_inventory_matches_activity() { + let root = temp_root("activity-counters"); + let manager = L3CacheManager::acquire(&root, StoreLimits::new(1_000_000, 0)).unwrap(); + let stage = manager.tier("state".to_string(), 4); + stage + .spill( + "namespace", + &[1, 2, 3], + &ExactStatePayload::full_state(b"state".to_vec()), + None, + None, + ) + .unwrap(); + assert_eq!( + manager.activity_without_inventory(), + manager.activity().unwrap() + ); + + let manifests = root.join("manifests"); + fs::rename(&manifests, root.join("saved-manifests")).unwrap(); + fs::write(&manifests, b"inventory unavailable").unwrap(); + assert!(manager.activity().is_err()); + assert_eq!(manager.activity_without_inventory().writes, 1); + drop((stage, manager)); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn activity_and_store_accounting_are_node_wide() { let root = temp_root("node-status"); diff --git a/skippy/crates/skippy-config/src/local_serving.rs b/skippy/crates/skippy-config/src/local_serving.rs index 0227f37b06..03565e83b9 100644 --- a/skippy/crates/skippy-config/src/local_serving.rs +++ b/skippy/crates/skippy-config/src/local_serving.rs @@ -1,7 +1,9 @@ //! Shared single-machine serving defaults used by Skippy and Mesh. pub const CTX_SIZE: u32 = 4096; -pub const BATCH: u32 = 512; +/// llama-server's batch: concurrent prompts that arrive together prefill in one +/// iteration, instead of one at a time while the requests already decoding wait. +pub const BATCH: u32 = 2048; pub const UBATCH: u32 = 512; // Automatic local serving uses the shared KV planner; this remains the // fallback for callers that construct a stage without model metadata. @@ -44,13 +46,13 @@ pub struct ThroughputProfileDefaults { pub fn throughput_profile_defaults(policy: &str) -> ThroughputProfileDefaults { match policy { "throughput" => ThroughputProfileDefaults { - batch: Some(BATCH * 2), + batch: Some(UBATCH * 2), ubatch: Some(UBATCH * 2), parallel: Some(2), continuous_batching: Some("true".to_string()), }, "saver" => ThroughputProfileDefaults { - batch: Some(BATCH / 2), + batch: Some(UBATCH / 2), ubatch: Some(UBATCH / 2), parallel: Some(1), continuous_batching: Some("false".to_string()), @@ -70,14 +72,14 @@ mod tests { #[test] fn throughput_profiles_preserve_mesh_tuning_behavior() { - for (name, batch, parallel, continuous) in [ - ("balanced", 512, 4, "auto"), - ("throughput", 1024, 2, "true"), - ("saver", 256, 1, "false"), + for (name, batch, ubatch, parallel, continuous) in [ + ("balanced", 2048, 512, 4, "auto"), + ("throughput", 1024, 1024, 2, "true"), + ("saver", 256, 256, 1, "false"), ] { let profile = throughput_profile_defaults(name); assert_eq!(profile.batch, Some(batch)); - assert_eq!(profile.ubatch, Some(batch)); + assert_eq!(profile.ubatch, Some(ubatch)); assert_eq!(profile.parallel, Some(parallel)); assert_eq!(profile.continuous_batching.as_deref(), Some(continuous)); } diff --git a/skippy/crates/skippy-ffi/README.md b/skippy/crates/skippy-ffi/README.md index 0afbed2eae..85482d1302 100644 --- a/skippy/crates/skippy-ffi/README.md +++ b/skippy/crates/skippy-ffi/README.md @@ -105,7 +105,7 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.79`. The patch header in +The staged ABI is versioned as `0.1.81`. The patch header in `skippy/llama_cpp/patches/` and the Rust constants in `skippy/crates/skippy-ffi/src/lib.rs` are the source of truth, so keep this README aligned with those files instead of treating it as canonical prose. diff --git a/skippy/crates/skippy-ffi/bindgen/wrapper/skippy_abi.h b/skippy/crates/skippy-ffi/bindgen/wrapper/skippy_abi.h index 83dc2f6c63..eb323291e4 100644 --- a/skippy/crates/skippy-ffi/bindgen/wrapper/skippy_abi.h +++ b/skippy/crates/skippy-ffi/bindgen/wrapper/skippy_abi.h @@ -43,6 +43,7 @@ static const uint64_t skippy_ffi_bridge_feature_laya_decisions = SKIPPY_FEATURE_ static const uint64_t skippy_ffi_bridge_feature_speech_recognition = SKIPPY_FEATURE_SPEECH_RECOGNITION; static const uint64_t skippy_ffi_bridge_feature_clef_decisions = SKIPPY_FEATURE_CLEF_DECISIONS; +static const uint64_t skippy_ffi_bridge_feature_native_tracing = SKIPPY_FEATURE_NATIVE_TRACING; /* Same cast-form macro bridge as the feature bits above. */ static const uint32_t skippy_ffi_bridge_activation_part_optional = SKIPPY_ACTIVATION_PART_OPTIONAL; diff --git a/skippy/crates/skippy-ffi/src/abi.rs b/skippy/crates/skippy-ffi/src/abi.rs index 999ffdc8aa..e893e33ed9 100644 --- a/skippy/crates/skippy-ffi/src/abi.rs +++ b/skippy/crates/skippy-ffi/src/abi.rs @@ -42,6 +42,13 @@ pub const FEATURE_SPEECH_RECOGNITION: u64 = bindings::skippy::skippy_ffi_bridge_feature_speech_recognition; /// Joint Clef decision reads (`skippy/clef.h`). pub const FEATURE_CLEF_DECISIONS: u64 = bindings::skippy::skippy_ffi_bridge_feature_clef_decisions; +/// Native span and GPU command timing callbacks (`skippy/tracing.h`). +pub const FEATURE_NATIVE_TRACING: u64 = bindings::skippy::skippy_ffi_bridge_feature_native_tracing; + +pub const NATIVE_SPAN_V1_ABI_VERSION: u32 = 1; +/// Set in every native span id, so span ids never collide with caller tags. +pub const NATIVE_SPAN_ID_BIT: u64 = 1 << 63; +pub const GPU_COMMAND_TIMING_V1_ABI_VERSION: u32 = 1; pub const MODEL_TENSOR_SOURCE_V1_ABI_VERSION: u32 = bindings::skippy::SKIPPY_MODEL_TENSOR_SOURCE_V1_ABI_VERSION; @@ -305,6 +312,93 @@ pub type SkippyRuntimeEventFailureCode = bindings::skippy::skippy_runtime_event_ pub type SkippyRuntimeEventV1 = bindings::skippy::skippy_runtime_event_v1; pub type SkippyRuntimeEventReporterV1 = bindings::skippy::skippy_runtime_event_reporter_v1; +/// One finished phase of native work (`skippy/tracing.h`). Times are Unix +/// nanoseconds. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SkippyNativeSpanV1 { + pub abi_version: u32, + pub struct_size: u32, + /// Process-unique and nonzero, with [`NATIVE_SPAN_ID_BIT`] set. + pub id: u64, + /// The enclosing native span's id, else the thread's trace tag, else 0. + pub parent: u64, + /// Dotted span name with static storage, such as `"llama.graph_compute"`. + pub name: *const c_char, + /// Null, or what the span worked on; valid only during the callback. + pub detail: *const c_char, + pub start_unix_ns: i64, + pub end_unix_ns: i64, + /// Null, or the name of one measured quantity with static storage. + pub value_name: *const c_char, + pub value: i64, +} + +pub type SkippyNativeSpanCallback = + Option; +pub type SkippySetNativeSpanCallbackFn = + unsafe extern "C" fn(callback: SkippyNativeSpanCallback, user_data: *mut c_void) -> Status; + +/// One unit of device work, such as a Metal command buffer +/// (`skippy/tracing.h`). Times are Unix nanoseconds; 0 when unobserved. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SkippyGpuCommandTimingV1 { + pub abi_version: u32, + pub struct_size: u32, + pub tag: u64, + /// Backend registry name with static storage, such as `"MTL"`. + pub backend_name: *const c_char, + pub context_id: u32, + pub compute_index: u32, + pub command_index: u32, + pub command_count: u32, + pub node_count: u32, + pub status: i32, + pub encode_start_unix_ns: i64, + pub encode_end_unix_ns: i64, + pub execute_start_unix_ns: i64, + pub execute_end_unix_ns: i64, + /// `"attention"`, `"matmul"`, `"recurrent"`, `"kv_write"`, `"other"` or + /// `"mixed"`, with static storage. Runtimes that predate op classes end + /// the record before this field; `struct_size` says which it is. + pub op_class: *const c_char, + /// The model layer of the command's first layer-named node; -1 when unknown. + pub layer: i32, + /// 1 when the backend split the graph at op class boundaries. + pub split_by_class: u32, + pub attention_kv_cells: u32, + pub attention_queries: u32, + pub attention_row_list_nodes: u32, + /// Attention nodes that are flash attention; unfused attention has none. + pub attention_flash_nodes: u32, + pub attention_nodes: u32, + pub matmul_nodes: u32, + pub recurrent_nodes: u32, + pub kv_write_nodes: u32, + pub other_nodes: u32, + pub attention_bytes: u64, + pub matmul_bytes: u64, + pub recurrent_bytes: u64, + pub kv_write_bytes: u64, + pub other_bytes: u64, + /// The most recurrent states one gather reads: the states of the batch's + /// sequences and every state between them. Runtimes that predate it end + /// the record before this field. + pub recurrent_states: u32, + /// The most gathered states a copy writes back unchanged because no + /// sequence in the batch owns them. + pub recurrent_states_carried: u32, +} + +pub type SkippyGpuCommandTimingCallback = + Option; +pub type SkippySetGpuCommandTimingCallbackFn = unsafe extern "C" fn( + callback: SkippyGpuCommandTimingCallback, + user_data: *mut c_void, +) -> Status; +pub type SkippySetTraceTagFn = unsafe extern "C" fn(tag: u64); + pub type Status = bindings::skippy::skippy_status; /// Decode a raw status code from the wire. The runtime-event ABI stores diff --git a/skippy/crates/skippy-ffi/src/bindings/skippy.rs b/skippy/crates/skippy-ffi/src/bindings/skippy.rs index 6f28bcc65a..e4b82c603d 100644 --- a/skippy/crates/skippy-ffi/src/bindings/skippy.rs +++ b/skippy/crates/skippy-ffi/src/bindings/skippy.rs @@ -6,13 +6,15 @@ pub const SKIPPY_ABI_VERSION_MAJOR: u32 = 0; pub const SKIPPY_ABI_VERSION_MINOR: u32 = 1; -pub const SKIPPY_ABI_VERSION_PATCH: u32 = 79; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 81; pub const SKIPPY_ACTIVATION_FRAME_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_IDENTITY_BYTES: u32 = 32; pub const SKIPPY_ACTIVATION_MAX_DIMS: u32 = 4; pub const SKIPPY_ACTIVATION_MAX_PARTS: u32 = 16; pub const SKIPPY_RUNTIME_EVENT_V1_ABI_VERSION: u32 = 1; +pub const SKIPPY_NATIVE_SPAN_V1_ABI_VERSION: u32 = 1; +pub const SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION: u32 = 1; pub const SKIPPY_MAX_LOGIT_BIAS: u32 = 256; pub const SKIPPY_MAX_SAMPLERS: u32 = 16; pub const SKIPPY_MAX_DRY_SEQUENCE_BREAKERS: u32 = 8; @@ -344,6 +346,111 @@ unsafe extern "C" { numeric_summary_0: u64, ); } +#[doc = " @brief One finished phase of native work."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_native_span_v1 { + pub abi_version: u32, + pub struct_size: u32, + #[doc = " Process-unique and nonzero; SKIPPY_NATIVE_SPAN_ID_BIT is set."] + pub id: u64, + #[doc = " The enclosing native span's id when there is one, else the reporting\n thread's trace tag, else 0. Children end, and so arrive, before their\n parent."] + pub parent: u64, + #[doc = " Dotted span name such as \"llama.graph_compute\"; static storage."] + pub name: *const ::std::os::raw::c_char, + #[doc = " Null, or what the span worked on; valid only during the callback."] + pub detail: *const ::std::os::raw::c_char, + #[doc = " Unix nanoseconds."] + pub start_unix_ns: i64, + pub end_unix_ns: i64, + #[doc = " Null, or the name of one measured quantity; static storage."] + pub value_name: *const ::std::os::raw::c_char, + pub value: i64, +} +#[doc = " @brief Receives one native span, on the thread that did the work.\n\n That is usually the thread inside the native call, so a slow callback\n slows the call it measures. The span is valid only for the call."] +pub type skippy_native_span_callback = ::std::option::Option< + unsafe extern "C" fn( + span: *const skippy_native_span_v1, + user_data: *mut ::std::os::raw::c_void, + ), +>; +unsafe extern "C" { + #[doc = " @brief Installs the process-global native span callback.\n\n Install once, before the calls to observe; a null callback stops\n reporting. A callback already running may finish after it is cleared.\n Installing reaches every loaded backend, which may initialise the backend\n registry on the calling thread. Backend spans that ended before a backend\n received its first callback (device initialisation compiles kernel\n libraries) are delivered from within this call: those that began during\n it under the calling thread's tag, earlier ones with no parent."] + pub fn skippy_set_native_span_callback( + callback: skippy_native_span_callback, + user_data: *mut ::std::os::raw::c_void, + ) -> skippy_status; +} +#[doc = " @brief Timing of one unit of device work, such as a Metal command buffer."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_gpu_command_timing_v1 { + pub abi_version: u32, + pub struct_size: u32, + #[doc = " The submitting thread's trace tag; 0 when none was set."] + pub tag: u64, + #[doc = " The ggml backend registry name, such as \"MTL\"; static storage."] + pub backend_name: *const ::std::os::raw::c_char, + #[doc = " Backend instance, and its 1-based graph compute count."] + pub context_id: u32, + pub compute_index: u32, + #[doc = " Execution order of this command within its graph compute."] + pub command_index: u32, + pub command_count: u32, + #[doc = " Graph nodes encoded into this command."] + pub node_count: u32, + #[doc = " 0 when the device completed the command, else a backend status."] + pub status: i32, + #[doc = " Unix nanoseconds; 0 when the backend did not observe the instant."] + pub encode_start_unix_ns: i64, + pub encode_end_unix_ns: i64, + pub execute_start_unix_ns: i64, + pub execute_end_unix_ns: i64, + #[doc = " What the command's graph nodes do: \"attention\", \"matmul\", \"recurrent\",\n \"kv_write\" or \"other\" when every classified node shares that class,\n else \"mixed\"; static storage. Views and reshapes have no class.\n Attention is flash attention, or the masked soft max and K/Q, K/Q/V\n products of unfused attention; recurrent is SSM, RWKV, gated linear\n attention and delta-net state, and copies to or from its cache."] + pub op_class: *const ::std::os::raw::c_char, + #[doc = " The model layer of the command's first layer-named node; -1 when unknown."] + pub layer: i32, + #[doc = " 1 when the backend split this graph at op class boundaries so each\n command holds one class (Metal: GGML_METAL_OP_PROFILE=1), else 0."] + pub split_by_class: u32, + #[doc = " Attention nodes: the most KV cells one query addresses (the row list\n length for attention that reads per-sequence row lists, else the K/V\n span; for unfused attention, the K/Q product's K span), the most query\n rows one node processes, how many nodes read row lists, and how many\n are flash attention (unfused attention has none)."] + pub attention_kv_cells: u32, + pub attention_queries: u32, + pub attention_row_list_nodes: u32, + pub attention_flash_nodes: u32, + #[doc = " Graph nodes by class."] + pub attention_nodes: u32, + pub matmul_nodes: u32, + pub recurrent_nodes: u32, + pub kv_write_nodes: u32, + pub other_nodes: u32, + #[doc = " Bytes the nodes read, by class: weights and activations for mat-muls;\n for gathers from and row writes into a cache, only the rows read or\n written; for attention only the K/V rows its nodes address."] + pub attention_bytes: u64, + pub matmul_bytes: u64, + pub recurrent_bytes: u64, + pub kv_write_bytes: u64, + pub other_bytes: u64, + #[doc = " Recurrent state caches: the most states one gather reads (the states\n of the batch's sequences and every state between them), and the most\n of those a copy writes back unchanged because no sequence in the batch\n owns them."] + pub recurrent_states: u32, + pub recurrent_states_carried: u32, +} +#[doc = " @brief Receives one timing record, on a backend-owned completion thread.\n\n The record is valid only for the duration of the call. Return quickly:\n the thread may be serving completion for every command on the device."] +pub type skippy_gpu_command_timing_callback = ::std::option::Option< + unsafe extern "C" fn( + timing: *const skippy_gpu_command_timing_v1, + user_data: *mut ::std::os::raw::c_void, + ), +>; +unsafe extern "C" { + #[doc = " @brief Installs the process-global GPU command timing callback.\n\n Install once, before submitting work; a null callback stops reporting. A\n callback already running may finish after it is cleared. Returns\n SKIPPY_STATUS_UNSUPPORTED when no loaded backend reports command timing."] + pub fn skippy_set_gpu_command_timing_callback( + callback: skippy_gpu_command_timing_callback, + user_data: *mut ::std::os::raw::c_void, + ) -> skippy_status; +} +unsafe extern "C" { + #[doc = " @brief Sets the calling thread's trace tag for the work it does afterwards.\n\n Native spans without an enclosing native span, and GPU work the thread\n submits, carry the tag. Thread-local and cheap; pass 0 to stop tagging.\n Tags should leave SKIPPY_NATIVE_SPAN_ID_BIT clear. Backends see the tag\n once either callback has been installed."] + pub fn skippy_set_trace_tag(tag: u64); +} #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum skippy_backend_device_type { @@ -532,11 +639,11 @@ pub struct skippy_runtime_config { pub host_expert_layer_start: i32, #[doc = " @brief One past the last such block index. `host_expert_layer_end <= host_expert_layer_start` keeps every routed expert on the accelerator, and a range wider than 4096 blocks is ignored the same way: no supported model approaches that block count, and the bound keeps override construction proportional to the model. Routing and precision are unchanged; only weight placement differs."] pub host_expert_layer_end: i32, - #[doc = " @brief Recurrent-state rollback depth (mirrors upstream `n_rs_seq`) for recurrent and hybrid models. Verifying an N-token speculative window in place needs at least N. 0 keeps the default of 2; `SKIPPY_RS_SEQ` overrides either."] + #[doc = " @brief Recurrent-state rollback depth (mirrors upstream `n_rs_seq`) for recurrent and hybrid models. 0 disables rollback snapshots; positive values request that depth, bounded to 64. Verifying an N-token speculative input window, including its committed anchor, in place needs at least N; otherwise verification uses a host checkpoint and replay while model computation remains on its selected backend. `SKIPPY_RS_SEQ` overrides the depth, including explicit 0. The native default configuration and a NULL configuration request 2 for legacy C callers."] pub recurrent_rollback_tokens: u32, } unsafe extern "C" { - #[doc = " @brief Returns a C-safe runtime configuration with all derived-default controls set to auto."] + #[doc = " @brief Returns a C-safe runtime configuration with derived-default controls set to auto and recurrent rollback depth explicitly set to 2. Set recurrent_rollback_tokens to 0 when no speculative rollback snapshots are wanted."] pub fn skippy_runtime_config_default() -> skippy_runtime_config; } unsafe extern "C" { @@ -2323,4 +2430,5 @@ pub const skippy_ffi_bridge_feature_cachegen_kv_page: u64 = 549755813888; pub const skippy_ffi_bridge_feature_laya_decisions: u64 = 1099511627776; pub const skippy_ffi_bridge_feature_speech_recognition: u64 = 2199023255552; pub const skippy_ffi_bridge_feature_clef_decisions: u64 = 4398046511104; +pub const skippy_ffi_bridge_feature_native_tracing: u64 = 8796093022208; pub const skippy_ffi_bridge_activation_part_optional: u32 = 1; diff --git a/skippy/crates/skippy-ffi/src/dynamic.rs b/skippy/crates/skippy-ffi/src/dynamic.rs index 31251e6dbc..3c11dde06b 100644 --- a/skippy/crates/skippy-ffi/src/dynamic.rs +++ b/skippy/crates/skippy-ffi/src/dynamic.rs @@ -447,6 +447,32 @@ pub fn skippy_clear_runtime_event_reporter_fn() -> Option Option { + static CACHE: OnceLock> = OnceLock::new(); + *CACHE.get_or_init(|| { + symbols().lookup_optional::( + b"skippy_set_gpu_command_timing_callback\0", + ) + }) +} + +pub fn skippy_set_native_span_callback_fn() -> Option { + static CACHE: OnceLock> = OnceLock::new(); + *CACHE.get_or_init(|| { + symbols().lookup_optional::( + b"skippy_set_native_span_callback\0", + ) + }) +} + +pub fn skippy_set_trace_tag_fn() -> Option { + static CACHE: OnceLock> = OnceLock::new(); + *CACHE.get_or_init(|| { + symbols().lookup_optional::(b"skippy_set_trace_tag\0") + }) +} + pub fn skippy_abi_features_optional() -> Option { static CACHE: OnceLock> = OnceLock::new(); *CACHE diff --git a/skippy/crates/skippy-ffi/src/lib.rs b/skippy/crates/skippy-ffi/src/lib.rs index aacbd2291e..8ae546b423 100644 --- a/skippy/crates/skippy-ffi/src/lib.rs +++ b/skippy/crates/skippy-ffi/src/lib.rs @@ -5,7 +5,7 @@ mod dynamic_library; // without compiling the crate to determine native-runtime compatibility. pub const ABI_VERSION_MAJOR: u32 = 0; pub const ABI_VERSION_MINOR: u32 = 1; -pub const ABI_VERSION_PATCH: u32 = 79; +pub const ABI_VERSION_PATCH: u32 = 81; // The facade constants are parsed without compiling; tie them to the generated // bindings' view of the native ABI version at compile time so a common.h bump @@ -52,20 +52,23 @@ pub use abi::{ FEATURE_BACKEND_DEVICES, FEATURE_CACHEGEN_KV_PAGE, FEATURE_CLEF_DECISIONS, FEATURE_DEVICE_EVENTS, FEATURE_DIAGNOSTIC_EVENTS, FEATURE_ITERATION_BATCH, FEATURE_KV_EVENTS, FEATURE_LAYA_DECISIONS, FEATURE_MODEL_LOAD_EVENTS_V2, FEATURE_MODEL_SOURCE, - FEATURE_MTP_MULTIMODAL, FEATURE_NATIVE_MTP_N1, FEATURE_NGRAM_CACHE_DRAFT, - FEATURE_NON_CHAT_WORKLOADS, FEATURE_RUNTIME_EVENT_REPORTER, FEATURE_RUNTIME_EVENTS, - FEATURE_SPEECH_RECOGNITION, FEATURE_STAGE_PLAN, FEATURE_SYSTEM_ONE, FEATURE_UNLOAD_EVENTS, - IterationRequest, LAYA_INFO_V1_ABI_VERSION, LAYA_MEMORY_V1_ABI_VERSION, LAYA_QTYPE_COUNT, - LayaInfoV1, LayaMemoryV1, LayaModel, LayaSequence, LlamaLogCallback, LlamaPerfContextData, + FEATURE_MTP_MULTIMODAL, FEATURE_NATIVE_MTP_N1, FEATURE_NATIVE_TRACING, + FEATURE_NGRAM_CACHE_DRAFT, FEATURE_NON_CHAT_WORKLOADS, FEATURE_RUNTIME_EVENT_REPORTER, + FEATURE_RUNTIME_EVENTS, FEATURE_SPEECH_RECOGNITION, FEATURE_STAGE_PLAN, FEATURE_SYSTEM_ONE, + FEATURE_UNLOAD_EVENTS, GPU_COMMAND_TIMING_V1_ABI_VERSION, IterationRequest, + LAYA_INFO_V1_ABI_VERSION, LAYA_MEMORY_V1_ABI_VERSION, LAYA_QTYPE_COUNT, LayaInfoV1, + LayaMemoryV1, LayaModel, LayaSequence, LlamaLogCallback, LlamaPerfContextData, LlamaPerfContextFn, LoadMode, MODEL_TENSOR_SOURCE_V1_ABI_VERSION, Model, ModelImatrixEntryV1, ModelInfo, ModelReadTensorF32Callback, ModelTensorSourceV1, MtmdProgressCallback, MtpSource, - NgramCache, Opaque, RuntimeConfig, Session, SkippyDecodeStepSampledMtpFn, - SkippyModelAttachMtpDraftModelFn, SkippyRuntimeEventCallback, SkippyRuntimeEventCategory, - SkippyRuntimeEventEmitterKind, SkippyRuntimeEventFailureCode, SkippyRuntimeEventKind, - SkippyRuntimeEventProgressUnit, SkippyRuntimeEventReporterV1, SkippyRuntimeEventV1, Status, - SystemOneSlot, TRISTATE_AUTO, TRISTATE_FALSE, TRISTATE_TRUE, TensorRole, TokenScoreRequest, - WORKLOAD_INFO_V1_ABI_VERSION, WorkloadInfoV1, WorkloadKind, WorkloadPooling, - runtime_abi_supported, status_from_raw, + NATIVE_SPAN_ID_BIT, NATIVE_SPAN_V1_ABI_VERSION, NgramCache, Opaque, RuntimeConfig, Session, + SkippyDecodeStepSampledMtpFn, SkippyGpuCommandTimingCallback, SkippyGpuCommandTimingV1, + SkippyModelAttachMtpDraftModelFn, SkippyNativeSpanCallback, SkippyNativeSpanV1, + SkippyRuntimeEventCallback, SkippyRuntimeEventCategory, SkippyRuntimeEventEmitterKind, + SkippyRuntimeEventFailureCode, SkippyRuntimeEventKind, SkippyRuntimeEventProgressUnit, + SkippyRuntimeEventReporterV1, SkippyRuntimeEventV1, SkippySetGpuCommandTimingCallbackFn, + SkippySetNativeSpanCallbackFn, SkippySetTraceTagFn, Status, SystemOneSlot, TRISTATE_AUTO, + TRISTATE_FALSE, TRISTATE_TRUE, TensorRole, TokenScoreRequest, WORKLOAD_INFO_V1_ABI_VERSION, + WorkloadInfoV1, WorkloadKind, WorkloadPooling, runtime_abi_supported, status_from_raw, }; pub use abi::{ RUNTIME_EVENT_CATEGORY_BACKEND, RUNTIME_EVENT_CATEGORY_DEVICE, @@ -220,7 +223,9 @@ pub use dynamic::{ #[cfg(feature = "dynamic-runtime")] pub use dynamic::{ - skippy_clear_runtime_event_reporter_fn, skippy_set_runtime_event_reporter_fn, symbol_present, + skippy_clear_runtime_event_reporter_fn, skippy_set_gpu_command_timing_callback_fn, + skippy_set_native_span_callback_fn, skippy_set_runtime_event_reporter_fn, + skippy_set_trace_tag_fn, symbol_present, }; #[cfg(not(feature = "dynamic-runtime"))] diff --git a/skippy/crates/skippy-runtime/src/activation.rs b/skippy/crates/skippy-runtime/src/activation.rs index 7143ce809c..4be062668b 100644 --- a/skippy/crates/skippy-runtime/src/activation.rs +++ b/skippy/crates/skippy-runtime/src/activation.rs @@ -1,5 +1,6 @@ mod iteration_execution; +use crate::native_timing::native_call; use iteration_execution::{exporting_stage_requires_one_request, frame_has_optional_parts}; use std::ffi::c_void; @@ -113,7 +114,7 @@ impl StageSession { let mut error = ptr::null_mut(); let status = unsafe { if positions.is_empty() { - skippy_ffi::skippy_prefill_chunk_frame( + native_call!(skippy_prefill_chunk_frame( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -124,9 +125,9 @@ impl StageSession { output_payload.len(), &mut output_bytes, &mut error, - ) + )) } else { - skippy_ffi::skippy_prefill_chunk_frame_with_positions( + native_call!(skippy_prefill_chunk_frame_with_positions( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -139,7 +140,7 @@ impl StageSession { output_payload.len(), &mut output_bytes, &mut error, - ) + )) } }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { @@ -220,7 +221,7 @@ impl StageSession { let mut error = ptr::null_mut(); let status = unsafe { if positions.is_empty() { - skippy_ffi::skippy_prefill_chunk_frame_sampled( + native_call!(skippy_prefill_chunk_frame_sampled( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -233,9 +234,9 @@ impl StageSession { &mut output_bytes, &mut predicted_token, &mut error, - ) + )) } else { - skippy_ffi::skippy_prefill_chunk_frame_sampled_with_positions( + native_call!(skippy_prefill_chunk_frame_sampled_with_positions( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -250,7 +251,7 @@ impl StageSession { &mut output_bytes, &mut predicted_token, &mut error, - ) + )) } }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { @@ -346,7 +347,7 @@ impl StageSession { .as_ref() .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let status = unsafe { - skippy_ffi::skippy_decode_step_frame_sampled( + native_call!(skippy_decode_step_frame_sampled( self.raw, token_id, sampling_ptr, @@ -358,7 +359,7 @@ impl StageSession { &mut output_bytes, &mut predicted_token, &mut error, - ) + )) }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { free_error(error); @@ -396,7 +397,7 @@ impl StageSession { .as_ref() .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let status = unsafe { - skippy_ffi::skippy_decode_step_frame_sampled_mtp( + native_call!(skippy_decode_step_frame_sampled_mtp( self.raw, token_id, sampling_ptr, @@ -410,7 +411,7 @@ impl StageSession { max_draft_tokens.min(skippy_ffi::NATIVE_MTP_MAX_DRAFT_TOKENS), &mut mtp_draft, &mut error, - ) + )) }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { free_error(error); @@ -499,7 +500,7 @@ impl StageSession { let mut predicted_tokens = vec![0_i32; requests.len()]; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_decode_step_frame_batch_sampled( + native_call!(skippy_decode_step_frame_batch_sampled( sessions.as_ptr(), token_ids.as_ptr(), sampling.as_ptr(), @@ -513,7 +514,7 @@ impl StageSession { predicted_tokens.len(), requests.len(), &mut error, - ) + )) }; if status == Status::BufferTooSmall { free_error(error); @@ -685,7 +686,7 @@ impl StageSession { .as_ref() .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let status = unsafe { - skippy_ffi::skippy_verify_tokens_frame_sampled( + native_call!(skippy_verify_tokens_frame_sampled( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -702,7 +703,7 @@ impl StageSession { max_draft_tokens.min(skippy_ffi::NATIVE_MTP_MAX_DRAFT_TOKENS), &mut output_draft, &mut error, - ) + )) }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { free_error(error); @@ -758,7 +759,7 @@ impl StageSession { let mut output_bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_copy_output_activation_frame( + native_call!(skippy_session_copy_output_activation_frame( self.raw, token_count, &mut output_desc, @@ -766,7 +767,7 @@ impl StageSession { output_payload.len(), &mut output_bytes, &mut error, - ) + )) }; if status == Status::BufferTooSmall && output_bytes > output_payload.len() { free_error(error); @@ -785,12 +786,12 @@ impl StageSession { let mut predicted = 0_i32; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_sample_current( + native_call!(skippy_session_sample_current( self.raw, sampling_ptr, &mut predicted, &mut error, - ) + )) }; ensure_ok(status, error)?; Ok(predicted) diff --git a/skippy/crates/skippy-runtime/src/activation/iteration_execution.rs b/skippy/crates/skippy-runtime/src/activation/iteration_execution.rs index dac8e8c4bc..ae30f8cc57 100644 --- a/skippy/crates/skippy-runtime/src/activation/iteration_execution.rs +++ b/skippy/crates/skippy-runtime/src/activation/iteration_execution.rs @@ -227,7 +227,7 @@ impl StageSession { let mut sampled_output_count = 0_usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_iteration_batch_sampled( + native_call!(skippy_iteration_batch_sampled( raw_requests.as_ptr(), raw_requests.len(), output_descs.as_mut_ptr(), @@ -239,7 +239,7 @@ impl StageSession { predicted_tokens.len(), &mut sampled_output_count, &mut error, - ) + )) }; if status == Status::BufferTooSmall && output_bytes diff --git a/skippy/crates/skippy-runtime/src/capability_probe.rs b/skippy/crates/skippy-runtime/src/capability_probe.rs index 4acc0a9cee..6d32eb10a0 100644 --- a/skippy/crates/skippy-runtime/src/capability_probe.rs +++ b/skippy/crates/skippy-runtime/src/capability_probe.rs @@ -1,8 +1,8 @@ use skippy_ffi::{ FEATURE_CLEF_DECISIONS, FEATURE_DEVICE_EVENTS, FEATURE_DIAGNOSTIC_EVENTS, FEATURE_KV_EVENTS, - FEATURE_LAYA_DECISIONS, FEATURE_MODEL_LOAD_EVENTS_V2, FEATURE_NON_CHAT_WORKLOADS, - FEATURE_RUNTIME_EVENT_REPORTER, FEATURE_RUNTIME_EVENTS, FEATURE_SPEECH_RECOGNITION, - FEATURE_UNLOAD_EVENTS, + FEATURE_LAYA_DECISIONS, FEATURE_MODEL_LOAD_EVENTS_V2, FEATURE_NATIVE_TRACING, + FEATURE_NON_CHAT_WORKLOADS, FEATURE_RUNTIME_EVENT_REPORTER, FEATURE_RUNTIME_EVENTS, + FEATURE_SPEECH_RECOGNITION, FEATURE_UNLOAD_EVENTS, }; use crate::logging::write_native_log_note; @@ -13,7 +13,7 @@ use crate::runtime_events::abi_features_bitmask; /// specific family, and is reported once rather than disabling anything. /// It tracks the highest `FEATURE_*` bit `skippy_ffi` defines, family or /// not: a bit this build names is not reserved to a future one. -const MAX_KNOWN_FEATURE_BIT: u32 = 42; +const MAX_KNOWN_FEATURE_BIT: u32 = 43; struct FamilySpec { bit: u64, @@ -114,6 +114,15 @@ const FAMILIES: &[FamilySpec] = &[ b"skippy_asr_result_free\0", ], }, + FamilySpec { + bit: FEATURE_NATIVE_TRACING, + name: "native_tracing", + required_symbols: &[ + b"skippy_set_native_span_callback\0", + b"skippy_set_gpu_command_timing_callback\0", + b"skippy_set_trace_tag\0", + ], + }, ]; /// Confirmed-family bitmask plus the bounded set of health messages this diff --git a/skippy/crates/skippy-runtime/src/checkpoint.rs b/skippy/crates/skippy-runtime/src/checkpoint.rs index fc70cff5e6..a4741a8bd1 100644 --- a/skippy/crates/skippy-runtime/src/checkpoint.rs +++ b/skippy/crates/skippy-runtime/src/checkpoint.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::{CStr, CString, c_char, c_void}; use std::fs; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -444,7 +445,7 @@ pub(crate) fn open_safetensors( // SAFETY: metadata and callback state remain alive until the synchronous native open returns; // output pointers are valid and the configuration owns its backing C strings. let status = unsafe { - skippy_ffi::skippy_model_open_from_source( + native_call!(skippy_model_open_from_source( callback_state.checkpoint.metadata_gguf().as_ptr().cast(), callback_state.checkpoint.metadata_gguf().len(), &callback_source, @@ -452,7 +453,7 @@ pub(crate) fn open_safetensors( &raw_config.raw, &mut raw, &mut error, - ) + )) }; ensure_ok(status, error)?; if raw.is_null() { diff --git a/skippy/crates/skippy-runtime/src/config.rs b/skippy/crates/skippy-runtime/src/config.rs index cbaf5887ca..6407e68d1f 100644 --- a/skippy/crates/skippy-runtime/src/config.rs +++ b/skippy/crates/skippy-runtime/src/config.rs @@ -156,7 +156,8 @@ pub struct RuntimeConfig { pub host_expert_layers: Option, /// Recurrent-state rollback depth for recurrent and hybrid models. A /// speculative plan sets it to its largest verify window so verify rolls - /// back in place; `0` keeps the native default. + /// back in place; `0` disables snapshots. Windows outside native retention + /// use the existing checkpoint/replay fallback. pub recurrent_rollback_tokens: u32, } @@ -560,6 +561,18 @@ pub fn parse_cache_type(value: &str) -> Result { #[cfg(test)] mod tests { + #[test] + fn recurrent_rollback_zero_and_positive_values_reach_native_unchanged() -> anyhow::Result<()> { + for depth in [0, 1, 2, 16, 100] { + let config = super::RuntimeConfig { + recurrent_rollback_tokens: depth, + ..super::RuntimeConfig::default() + }; + assert_eq!(config.as_raw()?.raw.recurrent_rollback_tokens, depth); + } + Ok(()) + } + use std::ffi::CStr; use super::*; diff --git a/skippy/crates/skippy-runtime/src/devices.rs b/skippy/crates/skippy-runtime/src/devices.rs index 9d26c31f87..d5d5b9ecc7 100644 --- a/skippy/crates/skippy-runtime/src/devices.rs +++ b/skippy/crates/skippy-runtime/src/devices.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::{CStr, c_char}; use std::ptr; @@ -37,9 +38,35 @@ pub struct BackendDevice { } pub fn backend_devices() -> Result> { + query_backend_devices(DeviceQuery::Traced) +} + +/// [`backend_devices`] without native call timing, for samplers that poll +/// device memory: polling should not fill the trace with spans of its own. +pub fn backend_devices_untraced() -> Result> { + query_backend_devices(DeviceQuery::Untraced) +} + +#[derive(Clone, Copy)] +enum DeviceQuery { + Traced, + Untraced, +} + +fn query_backend_devices(query: DeviceQuery) -> Result> { let mut error = ptr::null_mut(); let mut count = 0usize; - let status = unsafe { skippy_ffi::skippy_backend_device_count(&mut count, &mut error) }; + // SAFETY: both pointers are valid for the call. + let status = unsafe { + match query { + DeviceQuery::Traced => { + native_call!(skippy_backend_device_count(&mut count, &mut error)) + } + DeviceQuery::Untraced => { + skippy_ffi::skippy_backend_device_count(&mut count, &mut error) + } + } + }; super::ensure_ok(status, error)?; let mut devices = Vec::with_capacity(count); @@ -55,7 +82,17 @@ pub fn backend_devices() -> Result> { caps: 0, }; let mut error = ptr::null_mut(); - let status = unsafe { skippy_ffi::skippy_backend_device_at(index, &mut raw, &mut error) }; + // SAFETY: both pointers are valid for the call. + let status = unsafe { + match query { + DeviceQuery::Traced => { + native_call!(skippy_backend_device_at(index, &mut raw, &mut error)) + } + DeviceQuery::Untraced => { + skippy_ffi::skippy_backend_device_at(index, &mut raw, &mut error) + } + } + }; super::ensure_ok(status, error)?; devices.push(backend_device_from_raw(raw)?); } diff --git a/skippy/crates/skippy-runtime/src/gguf_writer.rs b/skippy/crates/skippy-runtime/src/gguf_writer.rs index 5711bc9138..929bb69ec4 100644 --- a/skippy/crates/skippy-runtime/src/gguf_writer.rs +++ b/skippy/crates/skippy-runtime/src/gguf_writer.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::CStr; use std::path::Path; use std::ptr; @@ -20,7 +21,7 @@ impl ModelInfo { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_model_info_open(path.as_ptr(), &mut raw, &mut error) }; + unsafe { native_call!(skippy_model_info_open(path.as_ptr(), &mut raw, &mut error)) }; ensure_ok(status, error)?; if raw.is_null() { return Err(anyhow!("skippy_model_info_open returned a null handle")); @@ -129,19 +130,19 @@ fn write_gguf_from_parts_impl( let mut error = ptr::null_mut(); let status = unsafe { if consume_inputs { - skippy_ffi::skippy_write_gguf_from_parts_consuming( + native_call!(skippy_write_gguf_from_parts_consuming( input_ptrs.as_ptr(), input_ptrs.len(), output_path.as_ptr(), &mut error, - ) + )) } else { - skippy_ffi::skippy_write_gguf_from_parts( + native_call!(skippy_write_gguf_from_parts( input_ptrs.as_ptr(), input_ptrs.len(), output_path.as_ptr(), &mut error, - ) + )) } }; ensure_ok(status, error) @@ -168,12 +169,12 @@ pub fn write_gguf_metadata_from_parts( let output_path = path_to_cstring(output_path.as_ref(), "output path")?; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_write_gguf_metadata_from_parts( + native_call!(skippy_write_gguf_metadata_from_parts( input_ptrs.as_ptr(), input_ptrs.len(), output_path.as_ptr(), &mut error, - ) + )) }; ensure_ok(status, error) } diff --git a/skippy/crates/skippy-runtime/src/kv_pages.rs b/skippy/crates/skippy-runtime/src/kv_pages.rs index 5346fb1268..d232b0061a 100644 --- a/skippy/crates/skippy-runtime/src/kv_pages.rs +++ b/skippy/crates/skippy-runtime/src/kv_pages.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ptr; use anyhow::{Result, ensure}; @@ -218,7 +219,7 @@ impl StageSession { let mut bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_state( + native_call!(skippy_export_state( self.raw, layer_start, layer_end, @@ -226,7 +227,7 @@ impl StageSession { 0, &mut bytes, &mut error, - ) + )) }; if status != Status::BufferTooSmall && status != Status::Ok { ensure_ok(status, error)?; @@ -238,7 +239,7 @@ impl StageSession { let mut written = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_state( + native_call!(skippy_export_state( self.raw, layer_start, layer_end, @@ -246,7 +247,7 @@ impl StageSession { payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; payload.truncate(written); @@ -256,14 +257,14 @@ impl StageSession { pub fn import_state(&mut self, layer_start: i32, layer_end: i32, input: &[u8]) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_import_state( + native_call!(skippy_import_state( self.raw, layer_start, layer_end, input.as_ptr().cast(), input.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; // Imported target state has no matching draft features. @@ -286,7 +287,7 @@ impl StageSession { let mut bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_full_state( + native_call!(skippy_export_full_state( self.raw, layer_start, layer_end, @@ -294,7 +295,7 @@ impl StageSession { 0, &mut bytes, &mut error, - ) + )) }; if status != Status::BufferTooSmall && status != Status::Ok { ensure_ok(status, error)?; @@ -306,7 +307,7 @@ impl StageSession { let mut written = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_full_state( + native_call!(skippy_export_full_state( self.raw, layer_start, layer_end, @@ -314,7 +315,7 @@ impl StageSession { payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; payload.truncate(written); @@ -329,14 +330,14 @@ impl StageSession { ) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_import_full_state( + native_call!(skippy_import_full_state( self.raw, layer_start, layer_end, input.as_ptr().cast(), input.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; // Imported target state has no matching draft features. @@ -369,7 +370,7 @@ impl StageSession { let mut bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_kv_page( + native_call!(skippy_export_kv_page( self.raw, layer_start, layer_end, @@ -380,7 +381,7 @@ impl StageSession { 0, &mut bytes, &mut error, - ) + )) }; if status != Status::BufferTooSmall && status != Status::Ok { ensure_ok(status, error)?; @@ -392,7 +393,7 @@ impl StageSession { let mut written = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_kv_page( + native_call!(skippy_export_kv_page( self.raw, layer_start, layer_end, @@ -403,7 +404,7 @@ impl StageSession { payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; payload.truncate(written); @@ -425,7 +426,7 @@ impl StageSession { let mut written = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_kv_page( + native_call!(skippy_export_kv_page( self.raw, layer_start, layer_end, @@ -436,7 +437,7 @@ impl StageSession { output.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; if written != output.len() { @@ -456,13 +457,13 @@ impl StageSession { let raw = desc.as_raw(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_import_kv_page( + native_call!(skippy_import_kv_page( self.raw, &raw, payload.as_ptr().cast(), payload.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -488,13 +489,13 @@ impl StageSession { let raw = desc.as_raw(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_import_cachegen_kv_page_v1( + native_call!(skippy_import_cachegen_kv_page_v1( self.raw, &raw, records.as_ptr(), records.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -509,13 +510,13 @@ impl StageSession { let mut bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_recurrent_state( + native_call!(skippy_export_recurrent_state( self.raw, ptr::null_mut(), 0, &mut bytes, &mut error, - ) + )) }; if status != Status::BufferTooSmall && status != Status::Ok { ensure_ok(status, error)?; @@ -527,13 +528,13 @@ impl StageSession { let mut written = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_export_recurrent_state( + native_call!(skippy_export_recurrent_state( self.raw, payload.as_mut_ptr().cast(), payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; payload.truncate(written); @@ -543,12 +544,12 @@ impl StageSession { pub fn import_recurrent_state(&mut self, input: &[u8]) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_import_recurrent_state( + native_call!(skippy_import_recurrent_state( self.raw, input.as_ptr().cast(), input.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; // Imported target state has no matching draft features. diff --git a/skippy/crates/skippy-runtime/src/laya.rs b/skippy/crates/skippy-runtime/src/laya.rs index 8fbe5cae58..f896bbd710 100644 --- a/skippy/crates/skippy-runtime/src/laya.rs +++ b/skippy/crates/skippy-runtime/src/laya.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::path::Path; use std::ptr; @@ -114,7 +115,7 @@ impl LayaModel { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_laya_model_open( + native_call!(skippy_laya_model_open( c_path.as_ptr(), threads, c_device @@ -122,7 +123,7 @@ impl LayaModel { .map_or(ptr::null(), |device| device.as_ptr()), &mut raw, &mut error, - ) + )) }; ensure_ok(status, error).with_context(|| format!("open Laya model {}", path.display()))?; if raw.is_null() { @@ -221,7 +222,7 @@ impl LayaModel { let mut count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_laya_tokenize( + native_call!(skippy_laya_tokenize( self.raw, text.as_ptr().cast(), text.len(), @@ -229,7 +230,7 @@ impl LayaModel { tokens.len(), &mut count, &mut error, - ) + )) }; ensure_ok(status, error).with_context(|| { format!( @@ -275,7 +276,7 @@ impl LayaModel { let mut act_logits = vec![0.0_f32; sequences.len() * action_classes]; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_laya_read( + native_call!(skippy_laya_read( self.raw, tokens.as_ptr(), tokens.len(), @@ -288,7 +289,7 @@ impl LayaModel { act_logits.as_mut_ptr(), act_logits.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; @@ -308,7 +309,7 @@ impl LayaModel { impl Drop for LayaModel { fn drop(&mut self) { if !self.raw.is_null() { - unsafe { skippy_ffi::skippy_laya_model_free(self.raw) }; + unsafe { native_call!(skippy_laya_model_free(self.raw)) }; } } } diff --git a/skippy/crates/skippy-runtime/src/lib.rs b/skippy/crates/skippy-runtime/src/lib.rs index d85901f94f..2af3b4a692 100644 --- a/skippy/crates/skippy-runtime/src/lib.rs +++ b/skippy/crates/skippy-runtime/src/lib.rs @@ -19,6 +19,8 @@ mod media; mod native; mod native_mtp; mod native_test_evidence; +pub mod native_timing; +pub mod native_tracing; mod ngram; pub mod package; mod path_cstring; @@ -50,7 +52,7 @@ pub use decision::{ DecisionError, DecisionModel, DecisionOutput, DecisionQuestion, DecisionQuestionKind, DecisionRequest, DecisionValue, }; -pub use devices::{BackendDevice, BackendDeviceType, backend_devices}; +pub use devices::{BackendDevice, BackendDeviceType, backend_devices, backend_devices_untraced}; pub use dflash::{ DFLASH_BORROWED_TARGET_TENSOR, DFlashDraftInfo, DFlashDraftOptions, DFlashDraftStats, DFlashFeatureEncoding, DFlashFeatureRows, DFlashHealth, DFlashProposal, DFlashVariant, diff --git a/skippy/crates/skippy-runtime/src/media.rs b/skippy/crates/skippy-runtime/src/media.rs index d12f5f88d8..584bd5ccbc 100644 --- a/skippy/crates/skippy-runtime/src/media.rs +++ b/skippy/crates/skippy-runtime/src/media.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::{CStr, CString}; use std::ptr; @@ -59,8 +60,12 @@ impl SpeechEmbeddingsGuard { // context; speech generation holds exclusive access to the session. unsafe { skippy_ffi::llama_set_embeddings(self.context, false) }; let mut error = ptr::null_mut(); - let status = - unsafe { skippy_ffi::skippy_session_begin_external_decode(self.session, &mut error) }; + let status = unsafe { + native_call!(skippy_session_begin_external_decode( + self.session, + &mut error + )) + }; ensure_ok(status, error).context("refresh stage program after speech synthesis")?; // The begin has been issued, so this guard's restore is complete. The // external-decode scope is now owned by the caller's ExternalDecodeGuard, @@ -71,7 +76,7 @@ impl SpeechEmbeddingsGuard { self.active = false; let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_session_end_external_decode(self.session, &mut error) }; + unsafe { native_call!(skippy_session_end_external_decode(self.session, &mut error)) }; ensure_ok(status, error).context("end stage-program refresh after speech synthesis")?; Ok(()) } @@ -88,10 +93,12 @@ impl Drop for SpeechEmbeddingsGuard { let mut error = ptr::null_mut(); unsafe { skippy_ffi::llama_set_embeddings(self.context, false); - if skippy_ffi::skippy_session_begin_external_decode(self.session, &mut error) - == skippy_ffi::Status::Ok + if native_call!(skippy_session_begin_external_decode( + self.session, + &mut error + )) == skippy_ffi::Status::Ok { - let _ = skippy_ffi::skippy_session_end_external_decode(self.session, &mut error); + let _ = native_call!(skippy_session_end_external_decode(self.session, &mut error)); } } free_error(error); @@ -163,7 +170,7 @@ impl MediaProjector { params.batch_max_tokens = i32::try_from(value).context("batch_max_tokens exceeds i32")?; } - let raw = unsafe { skippy_ffi::mtmd_init_from_file(path.as_ptr(), raw_model, params) }; + let raw = unsafe { native_call!(mtmd_init_from_file(path.as_ptr(), raw_model, params)) }; if raw.is_null() { return Err(anyhow!("failed to load multimodal projector {path:?}")); } @@ -189,7 +196,7 @@ impl Drop for MediaProjector { fn drop(&mut self) { if !self.raw.is_null() { unsafe { - skippy_ffi::mtmd_free(self.raw); + native_call!(mtmd_free(self.raw)); } } } @@ -272,7 +279,7 @@ impl StageModel { } let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_end_external_decode(self.session, &mut error) + native_call!(skippy_session_end_external_decode(self.session, &mut error)) }; ensure_ok(status, error).context("end speech external-decode scope")?; self.active = false; @@ -288,7 +295,7 @@ impl StageModel { let mut error = ptr::null_mut(); unsafe { let _ = - skippy_ffi::skippy_session_end_external_decode(self.session, &mut error); + native_call!(skippy_session_end_external_decode(self.session, &mut error)); } free_error(error); } @@ -302,15 +309,19 @@ impl StageModel { }; let mut guard_error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_begin_external_decode(session.raw, &mut guard_error) + native_call!(skippy_session_begin_external_decode( + session.raw, + &mut guard_error + )) }; ensure_ok(status, guard_error)?; let mut external_decode = ExternalDecodeGuard { session: session.raw, active: true, }; - let generator = - AudioGenerator(unsafe { skippy_ffi::mtmd_helper_gen_audio_init(lctx, projector.raw) }); + let generator = AudioGenerator(unsafe { + native_call!(mtmd_helper_gen_audio_init(lctx, projector.raw)) + }); if generator.0.is_null() { return Err(anyhow!("failed to initialize speech synthesis pipeline")); } @@ -330,7 +341,7 @@ impl StageModel { input.top_p = config.top_p; input.seed = config.seed; input.out_type = output_type; - if unsafe { skippy_ffi::mtmd_helper_gen_audio_set_input(generator.0, &input) } != 0 { + if unsafe { native_call!(mtmd_helper_gen_audio_set_input(generator.0, &input)) } != 0 { return Err(anyhow!("speech synthesis rejected the input")); } let batch_size = @@ -340,7 +351,7 @@ impl StageModel { return Err(anyhow!("speech synthesis cancelled")); } let remaining = - unsafe { skippy_ffi::mtmd_helper_gen_audio_step_prompt(generator.0, batch_size) }; + unsafe { native_call!(mtmd_helper_gen_audio_step_prompt(generator.0, batch_size)) }; if remaining < 0 { return Err(anyhow!("speech prompt evaluation failed")); } @@ -371,13 +382,13 @@ impl StageModel { let mut next_hidden_state = ptr::null(); let mut stop = false; let step = unsafe { - skippy_ffi::mtmd_helper_gen_audio_step_gen( + native_call!(mtmd_helper_gen_audio_step_gen( generator.0, sampled, hidden_state, &mut next_hidden_state, &mut stop, - ) + )) }; if step != 0 { return Err(anyhow!( @@ -408,13 +419,13 @@ impl StageModel { let mut data_len = 0usize; let mut sample_count = 0_i64; let output_status = unsafe { - skippy_ffi::mtmd_helper_gen_audio_get_output( + native_call!(mtmd_helper_gen_audio_get_output( generator.0, &mut sample_rate, &mut data, &mut data_len, &mut sample_count, - ) + )) }; if output_status != 0 || data.is_null() || data_len == 0 { return Err(anyhow!("speech synthesis produced no audio")); @@ -493,13 +504,13 @@ impl StageModel { } check_declared_media_size(&item.bytes)?; let wrapper = unsafe { - skippy_ffi::mtmd_helper_bitmap_init_from_buf( + native_call!(mtmd_helper_bitmap_init_from_buf( projector.raw, item.bytes.as_ptr(), item.bytes.len(), false, skippy_ffi::mtmd_helper_init_opt_default(), - ) + )) }; // Take ownership before the null check: on a partial failure the // wrapper can still carry a video context that has to be freed. @@ -533,13 +544,13 @@ impl StageModel { .map(|bitmap| bitmap.raw.cast_const()) .collect::>(); let tokenize_status = unsafe { - skippy_ffi::mtmd_tokenize( + native_call!(mtmd_tokenize( projector.raw, chunks.raw, &input_text, bitmap_ptrs.as_ptr(), bitmap_ptrs.len(), - ) + )) }; if tokenize_status != 0 { return Err(anyhow!( @@ -569,7 +580,10 @@ impl StageModel { } let mut guard_error = ptr::null_mut(); let guard_status = unsafe { - skippy_ffi::skippy_session_begin_external_decode(session.raw, &mut guard_error) + native_call!(skippy_session_begin_external_decode( + session.raw, + &mut guard_error + )) }; ensure_ok(guard_status, guard_error)?; @@ -579,7 +593,7 @@ impl StageModel { fn drop(&mut self) { let mut error = ptr::null_mut(); unsafe { - let _ = skippy_ffi::skippy_session_end_external_decode(self.0, &mut error); + let _ = native_call!(skippy_session_end_external_decode(self.0, &mut error)); } free_error(error); } @@ -589,7 +603,7 @@ impl StageModel { let mut new_n_past = 0_i32; let eval_status = unsafe { - skippy_ffi::mtmd_helper_eval_chunks( + native_call!(mtmd_helper_eval_chunks( projector.raw, lctx, chunks.raw, @@ -598,7 +612,7 @@ impl StageModel { n_batch, true, &mut new_n_past, - ) + )) }; if eval_status != 0 { return Err(anyhow!( @@ -607,8 +621,13 @@ impl StageModel { } let mut error = ptr::null_mut(); - let status = - unsafe { skippy_ffi::skippy_session_set_position(session.raw, new_n_past, &mut error) }; + let status = unsafe { + native_call!(skippy_session_set_position( + session.raw, + new_n_past, + &mut error + )) + }; ensure_ok(status, error)?; session.token_count = u64::try_from(new_n_past).context("multimodal position is negative")?; @@ -668,7 +687,7 @@ impl StageModel { fn drop(&mut self) { let mut error = ptr::null_mut(); unsafe { - let _ = skippy_ffi::skippy_session_end_external_decode(self.0, &mut error); + let _ = native_call!(skippy_session_end_external_decode(self.0, &mut error)); } free_error(error); } @@ -682,13 +701,13 @@ impl StageModel { } check_declared_media_size(&item.bytes)?; let wrapper = unsafe { - skippy_ffi::mtmd_helper_bitmap_init_from_buf( + native_call!(mtmd_helper_bitmap_init_from_buf( projector.raw, item.bytes.as_ptr(), item.bytes.len(), false, skippy_ffi::mtmd_helper_init_opt_default(), - ) + )) }; // Take ownership before the null check: on a partial failure the // wrapper can still carry a video context that has to be freed. @@ -722,13 +741,13 @@ impl StageModel { .map(|bitmap| bitmap.raw.cast_const()) .collect::>(); let tokenize_status = unsafe { - skippy_ffi::mtmd_tokenize( + native_call!(mtmd_tokenize( projector.raw, chunks.raw, &input_text, bitmap_ptrs.as_ptr(), bitmap_ptrs.len(), - ) + )) }; if tokenize_status != 0 { return Err(anyhow!( @@ -759,7 +778,10 @@ impl StageModel { let mut guard_error = ptr::null_mut(); let guard_status = unsafe { - skippy_ffi::skippy_session_begin_external_decode(session.raw, &mut guard_error) + native_call!(skippy_session_begin_external_decode( + session.raw, + &mut guard_error + )) }; ensure_ok(guard_status, guard_error)?; let _external_decode_guard = ExternalDecodeGuard(session.raw); @@ -850,7 +872,7 @@ impl StageModel { let mut new_n_past = n_past; let mut capture = ChunkCapture::new(session); let eval_status = unsafe { - skippy_ffi::mtmd_helper_eval_chunk_single_with_callback( + native_call!(mtmd_helper_eval_chunk_single_with_callback( projector.raw, lctx, chunk, @@ -861,7 +883,7 @@ impl StageModel { &mut new_n_past, Some(capture_microbatch), (&mut capture as *mut ChunkCapture<'_>).cast(), - ) + )) }; let frames = capture .finish(eval_status) @@ -880,7 +902,7 @@ impl StageModel { let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_session_set_position(session.raw, n_past, &mut error) }; + unsafe { native_call!(skippy_session_set_position(session.raw, n_past, &mut error)) }; ensure_ok(status, error)?; session.token_count = u64::try_from(n_past).context("multimodal position is negative")?; diff --git a/skippy/crates/skippy-runtime/src/native.rs b/skippy/crates/skippy-runtime/src/native.rs index 0f6489183c..cfab68b3f3 100644 --- a/skippy/crates/skippy-runtime/src/native.rs +++ b/skippy/crates/skippy-runtime/src/native.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::CString; use std::path::Path; use std::ptr; @@ -284,18 +285,25 @@ impl StageModel { #[cfg(not(test))] let (raw, status, error) = runtime_events::run_model_open( |out_model, out_error| unsafe { - skippy_ffi::skippy_model_open(path.as_ptr(), &raw_config.raw, out_model, out_error) + native_call!(skippy_model_open( + path.as_ptr(), + &raw_config.raw, + out_model, + out_error + )) }, |reporter, out_model, out_error| unsafe { let open_with_events_symbol = runtime_events::model_open_with_events_symbol() .expect("runtime-event symbol availability checked before use"); - open_with_events_symbol( - path.as_ptr(), - &raw_config.raw, - reporter, - out_model, - out_error, - ) + crate::native_timing::timed("skippy_model_open_with_events", || { + open_with_events_symbol( + path.as_ptr(), + &raw_config.raw, + reporter, + out_model, + out_error, + ) + }) }, event_queue, use_events, @@ -305,12 +313,12 @@ impl StageModel { debug_assert!(event_queue.is_none()); runtime_events::run_model_open( |out_model, out_error| unsafe { - skippy_ffi::skippy_model_open( + native_call!(skippy_model_open( path.as_ptr(), &raw_config.raw, out_model, out_error, - ) + )) }, |_reporter, _out_model, _out_error| { unreachable!("test builds do not link _with_events model-open symbols") @@ -374,26 +382,28 @@ impl StageModel { #[cfg(not(test))] let (raw, status, error) = runtime_events::run_model_open( |out_model, out_error| unsafe { - skippy_ffi::skippy_model_open_from_parts( + native_call!(skippy_model_open_from_parts( path_ptrs.as_ptr(), path_ptrs.len(), &raw_config.raw, out_model, out_error, - ) + )) }, |reporter, out_model, out_error| unsafe { let open_from_parts_with_events_symbol = runtime_events::model_open_from_parts_with_events_symbol() .expect("runtime-event symbol availability checked before use"); - open_from_parts_with_events_symbol( - path_ptrs.as_ptr(), - path_ptrs.len(), - &raw_config.raw, - reporter, - out_model, - out_error, - ) + crate::native_timing::timed("skippy_model_open_from_parts_with_events", || { + open_from_parts_with_events_symbol( + path_ptrs.as_ptr(), + path_ptrs.len(), + &raw_config.raw, + reporter, + out_model, + out_error, + ) + }) }, event_queue, use_events, @@ -403,13 +413,13 @@ impl StageModel { debug_assert!(event_queue.is_none()); runtime_events::run_model_open( |out_model, out_error| unsafe { - skippy_ffi::skippy_model_open_from_parts( + native_call!(skippy_model_open_from_parts( path_ptrs.as_ptr(), path_ptrs.len(), &raw_config.raw, out_model, out_error, - ) + )) }, |_reporter, _out_model, _out_error| { unreachable!( @@ -528,7 +538,7 @@ impl StageModel { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_session_create(self.inner.raw, &mut raw, &mut error) }; + unsafe { native_call!(skippy_session_create(self.inner.raw, &mut raw, &mut error)) }; write_native_log_note(format!("skippy_session_create returned status={status:?}")); ensure_ok(status, error)?; if raw.is_null() { @@ -554,14 +564,14 @@ impl StageModel { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_create_from_resident_prefix( + native_call!(skippy_session_create_from_resident_prefix( self.inner.raw, cache_seq_id, token_ids.as_ptr(), token_ids.len(), &mut raw, &mut error, - ) + )) }; ensure_ok(status, error)?; if raw.is_null() { @@ -662,7 +672,7 @@ impl StageModel { let mut output_count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_system_one_read( + native_call!(skippy_system_one_read( self.inner.raw, prompt_tokens.as_ptr(), prompt_tokens.len(), @@ -676,7 +686,7 @@ impl StageModel { probabilities.len(), &mut output_count, &mut error, - ) + )) }; ensure_ok(status, error)?; if output_count != probabilities.len() { @@ -709,11 +719,11 @@ impl StageModel { let mut canvas_token_count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_system_one_canvas_length( + native_call!(skippy_system_one_canvas_length( self.inner.raw, &mut canvas_token_count, &mut error, - ) + )) }; ensure_ok(status, error)?; if canvas_token_count == 0 { @@ -862,7 +872,7 @@ fn parse_chat_response_json_native( let mut bytes = output.len(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_parse_chat_response_json( + native_call!(skippy_parse_chat_response_json( generated_text.as_ptr(), metadata_json.as_ptr(), is_partial, @@ -870,7 +880,7 @@ fn parse_chat_response_json_native( output.len(), &mut bytes, &mut error, - ) + )) }; if status == Status::Ok { ensure_ok(status, error)?; @@ -885,7 +895,7 @@ fn parse_chat_response_json_native( output.resize(bytes.max(1), 0); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_parse_chat_response_json( + native_call!(skippy_parse_chat_response_json( generated_text.as_ptr(), metadata_json.as_ptr(), is_partial, @@ -893,7 +903,7 @@ fn parse_chat_response_json_native( output.len(), &mut bytes, &mut error, - ) + )) }; ensure_ok(status, error)?; output.truncate(bytes); @@ -1049,7 +1059,7 @@ fn tokenize_bounded( let mut count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_tokenize( + native_call!(skippy_tokenize( raw, text.as_ptr(), add_special, @@ -1057,7 +1067,7 @@ fn tokenize_bounded( tokens.len(), &mut count, &mut error, - ) + )) }; if status == Status::Ok { ensure_ok(status, error)?; @@ -1076,7 +1086,7 @@ fn tokenize_bounded( tokens.resize(count, 0); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_tokenize( + native_call!(skippy_tokenize( raw, text.as_ptr(), add_special, @@ -1084,7 +1094,7 @@ fn tokenize_bounded( tokens.len(), &mut count, &mut error, - ) + )) }; if status == Status::BufferTooSmall { free_error(error); @@ -1164,7 +1174,7 @@ fn apply_chat_template_json( let mut metadata_bytes = metadata.len(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_apply_chat_template_json( + native_call!(skippy_apply_chat_template_json( raw, messages_json.as_ptr(), tools_ptr, @@ -1187,7 +1197,7 @@ fn apply_chat_template_json( metadata.len(), &mut metadata_bytes, &mut error, - ) + )) }; if status == Status::Ok { ensure_ok(status, error)?; @@ -1204,7 +1214,7 @@ fn apply_chat_template_json( metadata.resize(metadata_bytes.max(1), 0); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_apply_chat_template_json( + native_call!(skippy_apply_chat_template_json( raw, messages_json.as_ptr(), tools_ptr, @@ -1227,7 +1237,7 @@ fn apply_chat_template_json( metadata.len(), &mut metadata_bytes, &mut error, - ) + )) }; ensure_ok(status, error)?; prompt.truncate(prompt_bytes); @@ -1242,7 +1252,7 @@ impl Drop for StageModelInner { self.dflash_capture.take(); if !self.raw.is_null() { unsafe { - let _ = skippy_ffi::skippy_model_free(self.raw, ptr::null_mut()); + let _ = native_call!(skippy_model_free(self.raw, ptr::null_mut())); } } } diff --git a/skippy/crates/skippy-runtime/src/native_timing.rs b/skippy/crates/skippy-runtime/src/native_timing.rs new file mode 100644 index 0000000000..73e3bd501c --- /dev/null +++ b/skippy/crates/skippy-runtime/src/native_timing.rs @@ -0,0 +1,140 @@ +//! Wall-clock timing of calls into the native Skippy ABI. +//! +//! Timings go to one optional process-wide observer; serving installs it for +//! debug telemetry. With no observer a timed call costs one atomic load. While +//! observed, each call also sets the id the observer gave it as the native +//! trace tag, so the spans and GPU work it causes name it as their parent +//! (see [`crate::native_tracing`]). + +use std::{ + sync::OnceLock, + time::{Instant, SystemTime, UNIX_EPOCH}, +}; + +/// One completed call across the native ABI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct NativeCall { + /// The exported C symbol, for example `skippy_prefill_chunk`. + pub symbol: &'static str, + /// The id [`NativeCallObserver::begin`] returned for this call. + pub id: u64, + pub start_unix_nanos: u64, + pub end_unix_nanos: u64, +} + +pub trait NativeCallObserver: Send + Sync { + /// Called on the calling thread just before the call. The id comes back + /// in [`NativeCall::id`] and tags the native spans and GPU work the call + /// causes, so it should be nonzero, unique among calls in flight, and + /// leave the top bit (native span ids) clear. + fn begin(&self, symbol: &'static str) -> u64; + fn observe(&self, call: NativeCall); +} + +static OBSERVER: OnceLock> = OnceLock::new(); + +/// Install the process-wide observer. The first installation wins; returns +/// false when one is already installed. +pub fn set_native_call_observer(observer: Box) -> bool { + OBSERVER.set(observer).is_ok() +} + +/// Run `call`, reporting its wall time as `symbol` when observed. +pub(crate) fn timed(symbol: &'static str, call: impl FnOnce() -> T) -> T { + let Some(observer) = OBSERVER.get() else { + return call(); + }; + // Installation is observed as a call of its own, before this one starts. + crate::native_tracing::ensure_installed(); + observe(observer.as_ref(), symbol, |_| call()) +} + +/// Run `call` with the id its observation will carry, without installing +/// native tracing: for the installation itself. +pub(crate) fn timed_with_id(symbol: &'static str, call: impl FnOnce(u64) -> T) -> T { + match OBSERVER.get() { + Some(observer) => observe(observer.as_ref(), symbol, call), + None => call(0), + } +} + +fn observe( + observer: &dyn NativeCallObserver, + symbol: &'static str, + call: impl FnOnce(u64) -> T, +) -> T { + let id = observer.begin(symbol); + let start_unix_nanos = unix_nanos_now(); + let started = Instant::now(); + let caller = crate::native_tracing::swap_tag(id); + let result = call(id); + crate::native_tracing::swap_tag(caller); + let elapsed = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); + observer.observe(NativeCall { + symbol, + id, + start_unix_nanos, + end_unix_nanos: start_unix_nanos.saturating_add(elapsed), + }); + result +} + +fn unix_nanos_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since| { + u64::try_from(since.as_nanos()).unwrap_or(u64::MAX) + }) +} + +/// Call `skippy_ffi::$symbol(..)` with its wall time reported under the +/// symbol's own name, so a span can never be mislabelled. Keep the +/// surrounding `unsafe` block at the call site. +macro_rules! native_call { + ($symbol:ident($($arg:expr),* $(,)?)) => { + $crate::native_timing::timed(stringify!($symbol), || { + skippy_ffi::$symbol($($arg),*) + }) + }; +} +pub(crate) use native_call; + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use super::{NativeCall, NativeCallObserver, set_native_call_observer, timed}; + + struct Recorder(Arc>>); + + impl NativeCallObserver for Recorder { + fn begin(&self, _symbol: &'static str) -> u64 { + 41 + } + + fn observe(&self, call: NativeCall) { + self.0.lock().expect("recorder lock").push(call); + } + } + + #[test] + fn observed_calls_report_their_symbol_and_wall_time() { + let calls = Arc::new(Mutex::new(Vec::new())); + assert!(set_native_call_observer(Box::new(Recorder(calls.clone())))); + assert!(!set_native_call_observer(Box::new(Recorder(calls.clone())))); + + let value = timed("skippy_test_symbol", || { + std::thread::sleep(std::time::Duration::from_millis(1)); + 7 + }); + + assert_eq!(value, 7); + let calls = calls.lock().expect("recorder lock"); + let call = calls + .iter() + .find(|call| call.symbol == "skippy_test_symbol") + .expect("timed call observed"); + assert!(call.end_unix_nanos - call.start_unix_nanos >= 1_000_000); + assert_eq!(call.id, 41, "the observer's id names the call"); + } +} diff --git a/skippy/crates/skippy-runtime/src/native_tracing.rs b/skippy/crates/skippy-runtime/src/native_tracing.rs new file mode 100644 index 0000000000..6222603056 --- /dev/null +++ b/skippy/crates/skippy-runtime/src/native_tracing.rs @@ -0,0 +1,202 @@ +//! Where time goes inside native calls (`skippy/tracing.h`). +//! +//! Two native callbacks report what a timed call did: [`spans`] names the +//! phases of host work (llama graph build, encode, synchronize, sampling, +//! Metal library and pipeline compilation) on the thread that did it, and +//! [`gpu_commands`] reports each command buffer once the GPU has finished it. +//! Both carry the trace tag the calling thread set, and timed native calls +//! set the id their observer hands out (see [`crate::native_timing`]), so a +//! consumer can place everything a call caused under it. +//! +//! The callbacks only copy records into bounded lock-free rings; consumers +//! drain them on their own thread. Installation is deferred to the first +//! timed native call after [`request_native_tracing`], when the runtime +//! library is certainly loaded, and is itself observed as a native call: +//! installing reaches every backend, and initialising Metal compiles its +//! kernel libraries there. + +use std::cell::Cell; +use std::ffi::{CStr, c_char}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU8, Ordering}; + +use skippy_ffi::{ + SkippySetGpuCommandTimingCallbackFn, SkippySetNativeSpanCallbackFn, SkippySetTraceTagFn, Status, +}; + +pub mod gpu_commands; +pub mod spans; + +const UNREQUESTED: u8 = 0; +const REQUESTED: u8 = 1; +const INSTALLING: u8 = 2; +const ACTIVE: u8 = 3; +const UNAVAILABLE: u8 = 4; + +static STATE: AtomicU8 = AtomicU8::new(UNREQUESTED); +static TAG_FN: OnceLock = OnceLock::new(); + +thread_local! { + /// The tag this thread last set, so a call nested in another (a native + /// callback into Rust that calls back down) can restore its caller's. + static TAG: Cell = const { Cell::new(0) }; +} + +/// Ask for native spans and GPU command timing. Nothing is installed until +/// the next timed native call; with no call observer, never. +pub fn request_native_tracing() { + let _ = STATE.compare_exchange(UNREQUESTED, REQUESTED, Ordering::AcqRel, Ordering::Acquire); +} + +/// Whether the runtime is reporting native spans. +pub fn native_tracing_active() -> bool { + STATE.load(Ordering::Acquire) == ACTIVE +} + +/// Install the native callbacks if tracing was requested and nobody has yet. +/// One caller installs; calls racing it on other threads run untagged. +pub(crate) fn ensure_installed() { + if STATE + .compare_exchange(REQUESTED, INSTALLING, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + let state = if install() { ACTIVE } else { UNAVAILABLE }; + STATE.store(state, Ordering::Release); + } +} + +/// Tag native spans and GPU work this thread causes from now on, returning +/// the tag it replaces; 0 stops tagging. The native tag is untouched unless +/// tracing is active. +pub(crate) fn swap_tag(tag: u64) -> u64 { + let previous = TAG.with(|current| current.replace(tag)); + if STATE.load(Ordering::Acquire) == ACTIVE + && let Some(set_tag) = TAG_FN.get() + { + // SAFETY: a thread-local store in the native runtime; takes no pointers. + unsafe { set_tag(tag) }; + } + previous +} + +struct InstallFns { + set_span_callback: SkippySetNativeSpanCallbackFn, + set_gpu_callback: SkippySetGpuCommandTimingCallbackFn, + set_tag: SkippySetTraceTagFn, +} + +fn install() -> bool { + let Some(fns) = install_fns() else { + return false; + }; + // Allocate before the first callback can arrive. + spans::ring(); + gpu_commands::ring(); + let _ = TAG_FN.set(fns.set_tag); + crate::native_timing::timed_with_id("skippy_set_native_span_callback", |id| { + // Kernel libraries compiled while installing land under this call. + // SAFETY: a thread-local store in the native runtime. + unsafe { (fns.set_tag)(id) }; + // SAFETY: the trampolines match the ABI callback types, never + // unwind, and use no user data. + let spans = + unsafe { (fns.set_span_callback)(Some(spans::trampoline), std::ptr::null_mut()) }; + // A runtime without a GPU backend has no command timing to report; + // its native spans are still worth having. + // SAFETY: as above. + let _ = + unsafe { (fns.set_gpu_callback)(Some(gpu_commands::trampoline), std::ptr::null_mut()) }; + // SAFETY: as above. + unsafe { (fns.set_tag)(0) }; + spans == Status::Ok + }) +} + +fn install_fns() -> Option { + #[cfg(feature = "dynamic-native-runtime")] + { + Some(InstallFns { + set_span_callback: skippy_ffi::skippy_set_native_span_callback_fn()?, + set_gpu_callback: skippy_ffi::skippy_set_gpu_command_timing_callback_fn()?, + set_tag: skippy_ffi::skippy_set_trace_tag_fn()?, + }) + } + #[cfg(not(feature = "dynamic-native-runtime"))] + { + let set_span_callback = linked_symbol(c"skippy_set_native_span_callback")?; + let set_gpu_callback = linked_symbol(c"skippy_set_gpu_command_timing_callback")?; + let set_tag = linked_symbol(c"skippy_set_trace_tag")?; + // SAFETY: each symbol, when linked, has exactly the transmuted signature. + unsafe { + Some(InstallFns { + set_span_callback: std::mem::transmute::< + *mut std::ffi::c_void, + SkippySetNativeSpanCallbackFn, + >(set_span_callback), + set_gpu_callback: std::mem::transmute::< + *mut std::ffi::c_void, + SkippySetGpuCommandTimingCallbackFn, + >(set_gpu_callback), + set_tag: std::mem::transmute::<*mut std::ffi::c_void, SkippySetTraceTagFn>(set_tag), + }) + } + } +} + +#[cfg(not(feature = "dynamic-native-runtime"))] +fn linked_symbol(name: &CStr) -> Option<*mut std::ffi::c_void> { + #[cfg(unix)] + { + // SAFETY: looks up a symbol in the already-loaded process image. + let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) }; + (!symbol.is_null()).then_some(symbol) + } + #[cfg(not(unix))] + { + let _ = name; + None + } +} + +/// A NUL-terminated string the ABI gives static storage; `fallback` when null +/// or not UTF-8. +fn static_str(name: *const c_char, fallback: &'static str) -> &'static str { + if name.is_null() { + return fallback; + } + // SAFETY: the ABI gives these strings static storage. + unsafe { CStr::from_ptr(name) }.to_str().unwrap_or(fallback) +} + +fn unix_nanos(value: i64) -> u64 { + u64::try_from(value).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tagging_without_a_request_never_touches_the_runtime() { + // No library is loaded in unit tests; reaching the FFI would panic. + if STATE.load(Ordering::Acquire) == UNREQUESTED { + assert_eq!(swap_tag(7), 0); + ensure_installed(); + } + assert!(!native_tracing_active()); + } + + #[test] + fn a_nested_call_restores_its_callers_tag() { + let outer = swap_tag(11); + assert_eq!(swap_tag(12), 11); + assert_eq!(swap_tag(11), 12); + assert_eq!(swap_tag(outer), 11); + } + + #[test] + fn static_strings_fall_back_when_missing() { + assert_eq!(static_str(std::ptr::null(), "gpu"), "gpu"); + assert_eq!(static_str(c"MTL".as_ptr(), "gpu"), "MTL"); + } +} diff --git a/skippy/crates/skippy-runtime/src/native_tracing/gpu_commands.rs b/skippy/crates/skippy-runtime/src/native_tracing/gpu_commands.rs new file mode 100644 index 0000000000..68c9a5e7bb --- /dev/null +++ b/skippy/crates/skippy-runtime/src/native_tracing/gpu_commands.rs @@ -0,0 +1,504 @@ +//! Device-side timing of the work native calls submit. +//! +//! A supporting backend (Metal) reports each command buffer after the GPU has +//! finished it, on the backend's completion thread, carrying the trace tag +//! the submitting thread had set. The callback only copies the record into +//! the ring: it runs on a thread that completes every command on the device, +//! and anything slower there would delay the very work being measured. A push +//! into a full ring drops the record and counts it. + +use std::ffi::{CStr, c_void}; +use std::mem::offset_of; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crossbeam_queue::ArrayQueue; +use skippy_ffi::{GPU_COMMAND_TIMING_V1_ABI_VERSION, SkippyGpuCommandTimingV1 as RawTiming}; + +use super::{static_str, unix_nanos}; + +/// Records the ring holds before it starts dropping: a few seconds of decode +/// steps between drains. +pub const GPU_TIMING_RING_CAPACITY: usize = 4096; + +/// One unit of device work, such as a Metal command buffer. Times are Unix +/// nanoseconds; 0 when the backend did not observe the instant. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct GpuCommandTiming { + /// The submitting native call's id; 0 when the work was submitted untagged. + pub tag: u64, + /// The backend registry name, such as `"MTL"`. + pub backend: &'static str, + pub context_id: u32, + /// 1-based graph compute count of the backend instance; for Metal it + /// counts like `GGML_METAL_CAPTURE_COMPUTE`. + pub compute_index: u32, + pub command_index: u32, + pub command_count: u32, + pub node_count: u32, + /// 0 when the device completed the command. + pub status: i32, + pub encode_start_unix_nanos: u64, + pub encode_end_unix_nanos: u64, + pub execute_start_unix_nanos: u64, + pub execute_end_unix_nanos: u64, + /// What the command's graph nodes do; `None` from a runtime that does + /// not classify them. + pub op_classes: Option, +} + +/// What a command's graph nodes do. Views and reshapes have no class. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +pub enum GpuOpClass { + /// Flash attention, or the masked soft max and K/Q, K/Q/V products of + /// unfused attention. + Attention, + /// Matrix products with weights. + Matmul, + /// SSM, RWKV, gated linear attention and delta-net state, and copies to + /// or from its cache. + Recurrent, + /// Writes into the attention KV cache. + KvWrite, + Other, +} + +impl GpuOpClass { + pub const ALL: [Self; 5] = [ + Self::Attention, + Self::Matmul, + Self::Recurrent, + Self::KvWrite, + Self::Other, + ]; + + pub fn name(self) -> &'static str { + match self { + Self::Attention => "attention", + Self::Matmul => "matmul", + Self::Recurrent => "recurrent", + Self::KvWrite => "kv_write", + Self::Other => "other", + } + } + + /// The class a native label names; `None` for `"mixed"` and any label + /// this build does not know. + fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|class| class.name() == name) + } +} + +/// One value per [`GpuOpClass`]. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PerOpClass { + pub attention: T, + pub matmul: T, + pub recurrent: T, + pub kv_write: T, + pub other: T, +} + +impl PerOpClass { + pub fn get(&self, class: GpuOpClass) -> T { + match class { + GpuOpClass::Attention => self.attention, + GpuOpClass::Matmul => self.matmul, + GpuOpClass::Recurrent => self.recurrent, + GpuOpClass::KvWrite => self.kv_write, + GpuOpClass::Other => self.other, + } + } +} + +/// How a command's graph nodes divide among op classes. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct GpuOpClasses { + /// The class of every classified node, or `None` when the command mixes + /// classes. + pub single: Option, + pub layer: Option, + /// The backend split the graph at class boundaries (op profiling), so + /// this command's GPU time belongs to `single` alone. + pub split_by_class: bool, + /// The most KV cells one query addresses: the row list length when + /// attention reads per-sequence row lists, else the K/V span. + pub attention_kv_cells: u32, + /// The most query rows one attention node processes. + pub attention_queries: u32, + /// Attention nodes that read per-sequence row lists. + pub attention_row_list_nodes: u32, + /// Attention nodes that are flash attention. + pub attention_flash_nodes: u32, + pub nodes: PerOpClass, + /// Bytes the nodes read: a gather from or row write into a cache counts + /// only its rows, and attention only the K/V rows its nodes address. + pub bytes: PerOpClass, + /// The recurrent states the command moves; `None` from a runtime that + /// does not count them. + pub recurrent_states: Option, +} + +/// The recurrent states one step moves through its state caches. A graph +/// gathers the states from the batch's first state cell to its last; those no +/// sequence of the batch owns are copied back unchanged. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct RecurrentStates { + /// The most states one gather reads. + pub gathered: u32, + /// The most gathered states copied back unchanged. + pub carried: u32, +} + +/// How attention read the KV cache. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +pub enum AttentionPath { + /// Flash attention over each sequence's own row list. + RowLists, + /// Flash attention over the whole K/V span, masked. + Flash, + /// Masked soft max between K/Q and K/Q/V products, over the whole span. + Unfused, +} + +impl AttentionPath { + pub fn name(self) -> &'static str { + match self { + Self::RowLists => "row_lists", + Self::Flash => "flash", + Self::Unfused => "unfused", + } + } +} + +impl GpuOpClasses { + /// The path the command's attention took; `None` when it has none. + pub fn attention_path(&self) -> Option { + if self.nodes.attention == 0 { + None + } else if self.attention_row_list_nodes > 0 { + Some(AttentionPath::RowLists) + } else if self.attention_flash_nodes > 0 { + Some(AttentionPath::Flash) + } else { + Some(AttentionPath::Unfused) + } + } + + /// Reads the fields a runtime with op classes appends; `None` for an + /// older, shorter record. + fn from_raw(raw: &RawTiming) -> Option { + let size = raw.struct_size as usize; + if size < OP_CLASS_TIMING_SIZE { + return None; + } + let recurrent_states = (size >= size_of::()).then_some(RecurrentStates { + gathered: raw.recurrent_states, + carried: raw.recurrent_states_carried, + }); + let label = if raw.op_class.is_null() { + "mixed" + } else { + // SAFETY: the runtime passes null or a static NUL-terminated label. + unsafe { CStr::from_ptr(raw.op_class) } + .to_str() + .unwrap_or("mixed") + }; + Some(Self { + single: GpuOpClass::from_name(label), + layer: u32::try_from(raw.layer).ok(), + split_by_class: raw.split_by_class != 0, + attention_kv_cells: raw.attention_kv_cells, + attention_queries: raw.attention_queries, + attention_row_list_nodes: raw.attention_row_list_nodes, + attention_flash_nodes: raw.attention_flash_nodes, + nodes: PerOpClass { + attention: raw.attention_nodes, + matmul: raw.matmul_nodes, + recurrent: raw.recurrent_nodes, + kv_write: raw.kv_write_nodes, + other: raw.other_nodes, + }, + bytes: PerOpClass { + attention: raw.attention_bytes, + matmul: raw.matmul_bytes, + recurrent: raw.recurrent_bytes, + kv_write: raw.kv_write_bytes, + other: raw.other_bytes, + }, + recurrent_states, + }) + } +} + +/// The fields every runtime with command timing reports, up to op classes. +const BASE_TIMING_SIZE: usize = offset_of!(RawTiming, op_class); +/// The fields a runtime with op classes reports, up to recurrent state counts. +const OP_CLASS_TIMING_SIZE: usize = offset_of!(RawTiming, recurrent_states); + +/// Copy the `struct_size` bytes a runtime reported into a whole record, the +/// fields an older runtime does not have left zero; `None` for a null or +/// unrecognised record. +/// +/// # Safety +/// +/// `timing` must be null or point to a record of at least `struct_size` +/// bytes whose header fields are valid. +unsafe fn read_record(timing: *const RawTiming) -> Option { + if timing.is_null() { + return None; + } + // SAFETY: the header fields precede op classes in every record version; + // reading them through the place does not assume a whole record. + let (abi_version, struct_size) = unsafe { + ( + std::ptr::addr_of!((*timing).abi_version).read(), + std::ptr::addr_of!((*timing).struct_size).read() as usize, + ) + }; + if abi_version != GPU_COMMAND_TIMING_V1_ABI_VERSION || struct_size < BASE_TIMING_SIZE { + return None; + } + let mut record = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the source holds `struct_size` bytes and the copy is capped at + // the destination's size; an all-zero RawTiming is valid (null labels). + unsafe { + std::ptr::copy_nonoverlapping( + timing.cast::(), + record.as_mut_ptr().cast::(), + struct_size.min(size_of::()), + ); + Some(record.assume_init()) + } +} + +static RING: OnceLock> = OnceLock::new(); +static DROPPED: AtomicU64 = AtomicU64::new(0); + +pub(super) fn ring() -> &'static ArrayQueue { + RING.get_or_init(|| ArrayQueue::new(GPU_TIMING_RING_CAPACITY)) +} + +/// Records lost to a full ring since the process started. +pub fn dropped_gpu_command_timings() -> u64 { + DROPPED.load(Ordering::Relaxed) +} + +/// Hand every pending record to `consume`, oldest first. +pub fn drain_gpu_command_timings(mut consume: impl FnMut(GpuCommandTiming)) { + let Some(ring) = RING.get() else { + return; + }; + while let Some(timing) = ring.pop() { + consume(timing); + } +} + +/// Copy one record into the ring. Runs on the backend's completion thread: +/// no locks, no waiting, and no allocation once the ring exists. +pub(super) unsafe extern "C" fn trampoline(timing: *const RawTiming, _user_data: *mut c_void) { + // SAFETY: the native caller passes null or a record valid for this call. + let Some(raw) = (unsafe { read_record(timing) }) else { + return; + }; + let raw = &raw; + let record = GpuCommandTiming { + tag: raw.tag, + backend: static_str(raw.backend_name, "gpu"), + context_id: raw.context_id, + compute_index: raw.compute_index, + command_index: raw.command_index, + command_count: raw.command_count, + node_count: raw.node_count, + status: raw.status, + encode_start_unix_nanos: unix_nanos(raw.encode_start_unix_ns), + encode_end_unix_nanos: unix_nanos(raw.encode_end_unix_ns), + execute_start_unix_nanos: unix_nanos(raw.execute_start_unix_ns), + execute_end_unix_nanos: unix_nanos(raw.execute_end_unix_ns), + op_classes: GpuOpClasses::from_raw(raw), + }; + if ring().push(record).is_err() { + DROPPED.fetch_add(1, Ordering::Relaxed); + } +} + +/// Deliver a raw record as the native callback would. +/// +/// # Safety +/// +/// `timing` must be null or point to a record valid for the call, whose +/// `backend_name` is null or a NUL-terminated string with static storage. +#[doc(hidden)] +pub unsafe fn deliver_gpu_command_timing_for_test(timing: *const RawTiming) { + unsafe { trampoline(timing, std::ptr::null_mut()) }; +} + +#[cfg(test)] +mod tests { + use std::sync::{Mutex, PoisonError}; + + use super::*; + + /// Draining takes every queued record, so tests that drain run one at a time. + static RING_TESTS: Mutex<()> = Mutex::new(()); + + fn raw(tag: u64) -> RawTiming { + RawTiming { + abi_version: GPU_COMMAND_TIMING_V1_ABI_VERSION, + struct_size: u32::try_from(size_of::()).unwrap(), + tag, + backend_name: c"MTL".as_ptr(), + context_id: 2, + compute_index: 9, + command_index: 1, + command_count: 3, + node_count: 120, + status: 0, + encode_start_unix_ns: 1_000, + encode_end_unix_ns: 2_000, + execute_start_unix_ns: 2_500, + execute_end_unix_ns: -1, + op_class: c"attention".as_ptr(), + layer: 7, + split_by_class: 1, + attention_kv_cells: 4096, + attention_queries: 4, + attention_row_list_nodes: 1, + attention_flash_nodes: 1, + attention_nodes: 1, + matmul_nodes: 0, + recurrent_nodes: 0, + kv_write_nodes: 0, + other_nodes: 2, + attention_bytes: 1 << 20, + matmul_bytes: 0, + recurrent_bytes: 0, + kv_write_bytes: 0, + other_bytes: 64, + recurrent_states: 6, + recurrent_states_carried: 2, + } + } + + fn drained_with_tag(tag: u64) -> Vec { + let mut found = Vec::new(); + drain_gpu_command_timings(|timing| { + if timing.tag == tag { + found.push(timing); + } + }); + found + } + + #[test] + fn delivered_records_drain_with_their_tag_and_backend() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let record = raw(0xa11ce); + // SAFETY: a valid record with a static backend name. + unsafe { deliver_gpu_command_timing_for_test(&raw const record) }; + + let drained = drained_with_tag(0xa11ce); + assert_eq!(drained.len(), 1); + let timing = drained[0]; + assert_eq!(timing.backend, "MTL"); + assert_eq!((timing.context_id, timing.compute_index), (2, 9)); + assert_eq!((timing.command_index, timing.command_count), (1, 3)); + assert_eq!(timing.node_count, 120); + assert_eq!(timing.encode_start_unix_nanos, 1_000); + assert_eq!(timing.execute_start_unix_nanos, 2_500); + assert_eq!( + timing.execute_end_unix_nanos, 0, + "negative means unobserved" + ); + } + + #[test] + fn records_from_another_abi_version_are_ignored() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let mut record = raw(0xb0b); + record.abi_version += 1; + // SAFETY: a valid record with a static backend name. + unsafe { deliver_gpu_command_timing_for_test(&raw const record) }; + // SAFETY: null is accepted. + unsafe { deliver_gpu_command_timing_for_test(std::ptr::null()) }; + assert!(drained_with_tag(0xb0b).is_empty()); + } + + #[test] + fn op_classes_are_parsed_at_the_boundary() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let record = raw(0xc1a55); + // SAFETY: a valid record with static labels. + unsafe { deliver_gpu_command_timing_for_test(&raw const record) }; + let classes = drained_with_tag(0xc1a55)[0] + .op_classes + .expect("a runtime with op classes"); + assert_eq!(classes.single, Some(GpuOpClass::Attention)); + assert_eq!(classes.layer, Some(7)); + assert!(classes.split_by_class); + assert_eq!( + (classes.attention_kv_cells, classes.attention_queries), + (4096, 4) + ); + assert_eq!(classes.nodes.get(GpuOpClass::Other), 2); + assert_eq!(classes.bytes.get(GpuOpClass::Attention), 1 << 20); + assert_eq!( + classes.recurrent_states, + Some(RecurrentStates { + gathered: 6, + carried: 2 + }) + ); + assert_eq!(classes.attention_path(), Some(AttentionPath::RowLists)); + let flash = GpuOpClasses { + attention_row_list_nodes: 0, + ..classes + }; + assert_eq!(flash.attention_path(), Some(AttentionPath::Flash)); + let unfused = GpuOpClasses { + attention_flash_nodes: 0, + ..flash + }; + assert_eq!(unfused.attention_path(), Some(AttentionPath::Unfused)); + + let mixed = RawTiming { + op_class: c"mixed".as_ptr(), + layer: -1, + ..raw(0xc1a56) + }; + // SAFETY: as above. + unsafe { deliver_gpu_command_timing_for_test(&raw const mixed) }; + let classes = drained_with_tag(0xc1a56)[0].op_classes.expect("classes"); + assert_eq!((classes.single, classes.layer), (None, None)); + } + + #[test] + fn a_record_from_before_op_classes_still_times_the_command() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + // Only the older prefix is valid: what an older runtime hands over. + let record = RawTiming { + struct_size: u32::try_from(BASE_TIMING_SIZE).unwrap(), + ..raw(0x01d) + }; + // SAFETY: the record is whole; the size marks the rest as absent. + unsafe { deliver_gpu_command_timing_for_test(&raw const record) }; + let drained = drained_with_tag(0x01d); + assert_eq!(drained.len(), 1); + assert_eq!(drained[0].node_count, 120); + assert_eq!(drained[0].op_classes, None); + } + + #[test] + fn a_record_from_before_recurrent_counts_keeps_its_op_classes() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let record = RawTiming { + struct_size: u32::try_from(OP_CLASS_TIMING_SIZE).unwrap(), + ..raw(0x01e) + }; + // SAFETY: the record is whole; the size marks the counts as absent. + unsafe { deliver_gpu_command_timing_for_test(&raw const record) }; + let classes = drained_with_tag(0x01e)[0].op_classes.expect("op classes"); + assert_eq!(classes.single, Some(GpuOpClass::Attention)); + assert_eq!(classes.recurrent_states, None); + } +} diff --git a/skippy/crates/skippy-runtime/src/native_tracing/spans.rs b/skippy/crates/skippy-runtime/src/native_tracing/spans.rs new file mode 100644 index 0000000000..ccdcef99c9 --- /dev/null +++ b/skippy/crates/skippy-runtime/src/native_tracing/spans.rs @@ -0,0 +1,189 @@ +//! Native spans: the phases of host work inside a native call. +//! +//! The runtime reports each span when it ends, on the thread that did the +//! work, usually the one inside the timed call, so the callback only copies +//! the span into the ring. A span's detail is the one thing it allocates for, +//! and only spans that name what they worked on (a pipeline, a kernel +//! library) carry one. A push into a full ring drops the span and counts it. + +use std::ffi::{CStr, c_void}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crossbeam_queue::ArrayQueue; +use skippy_ffi::{NATIVE_SPAN_ID_BIT, NATIVE_SPAN_V1_ABI_VERSION, SkippyNativeSpanV1 as RawSpan}; + +use super::{static_str, unix_nanos}; + +/// Spans the ring holds before it starts dropping: a few hundred decode +/// steps between drains. +pub const NATIVE_SPAN_RING_CAPACITY: usize = 8192; + +/// One finished phase of native work. Times are Unix nanoseconds. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeSpan { + /// Process-unique; has [`NATIVE_SPAN_ID_BIT`] set. + pub id: u64, + /// The enclosing native span ([`is_native_span_id`]), else the trace tag + /// of the thread that did the work, else 0. + pub parent: u64, + /// Dotted name such as `"llama.graph_compute"`. + pub name: &'static str, + /// What the span worked on, such as a Metal pipeline name. + pub detail: Option>, + pub start_unix_nanos: u64, + pub end_unix_nanos: u64, + /// One measured quantity, such as `("tokens", 4)`. + pub value: Option<(&'static str, i64)>, +} + +/// Whether `id` names a native span rather than a caller's trace tag. +pub fn is_native_span_id(id: u64) -> bool { + id & NATIVE_SPAN_ID_BIT != 0 +} + +static RING: OnceLock> = OnceLock::new(); +static DROPPED: AtomicU64 = AtomicU64::new(0); + +pub(super) fn ring() -> &'static ArrayQueue { + RING.get_or_init(|| ArrayQueue::new(NATIVE_SPAN_RING_CAPACITY)) +} + +/// Spans lost to a full ring since the process started. +pub fn dropped_native_spans() -> u64 { + DROPPED.load(Ordering::Relaxed) +} + +/// Hand every pending span to `consume`, in the order they ended. +pub fn drain_native_spans(mut consume: impl FnMut(NativeSpan)) { + let Some(ring) = RING.get() else { + return; + }; + while let Some(span) = ring.pop() { + consume(span); + } +} + +/// Copy one span into the ring. Runs inside native work: no locks and no +/// waiting. +pub(super) unsafe extern "C" fn trampoline(span: *const RawSpan, _user_data: *mut c_void) { + // SAFETY: the native caller passes null or a span valid for this call. + let Some(raw) = (unsafe { span.as_ref() }) else { + return; + }; + if raw.abi_version != NATIVE_SPAN_V1_ABI_VERSION + || (raw.struct_size as usize) < size_of::() + || !is_native_span_id(raw.id) + { + return; + } + let detail = (!raw.detail.is_null()).then(|| { + // SAFETY: a non-null detail is NUL-terminated and valid for this call. + unsafe { CStr::from_ptr(raw.detail) } + .to_string_lossy() + .into() + }); + let value = + (!raw.value_name.is_null()).then(|| (static_str(raw.value_name, "value"), raw.value)); + let span = NativeSpan { + id: raw.id, + parent: raw.parent, + name: static_str(raw.name, "native"), + detail, + start_unix_nanos: unix_nanos(raw.start_unix_ns), + end_unix_nanos: unix_nanos(raw.end_unix_ns), + value, + }; + if ring().push(span).is_err() { + DROPPED.fetch_add(1, Ordering::Relaxed); + } +} + +/// Deliver a raw span as the native callback would. +/// +/// # Safety +/// +/// `span` must be null or point to a span valid for the call, whose `name` +/// and `value_name` are null or NUL-terminated strings with static storage +/// and whose `detail` is null or NUL-terminated. +#[doc(hidden)] +pub unsafe fn deliver_native_span_for_test(span: *const RawSpan) { + unsafe { trampoline(span, std::ptr::null_mut()) }; +} + +#[cfg(test)] +mod tests { + use std::sync::{Mutex, PoisonError}; + + use super::*; + + /// Draining takes every queued record, so tests that drain run one at a time. + static RING_TESTS: Mutex<()> = Mutex::new(()); + + fn raw(id: u64, detail: &CStr) -> RawSpan { + RawSpan { + abi_version: NATIVE_SPAN_V1_ABI_VERSION, + struct_size: u32::try_from(size_of::()).unwrap(), + id: id | NATIVE_SPAN_ID_BIT, + parent: 41, + name: c"llama.graph_build".as_ptr(), + detail: detail.as_ptr(), + start_unix_ns: 1_000, + end_unix_ns: 4_000, + value_name: c"nodes".as_ptr(), + value: 1_234, + } + } + + fn drained_with_id(id: u64) -> Vec { + let mut found = Vec::new(); + drain_native_spans(|span| { + if span.id == id | NATIVE_SPAN_ID_BIT { + found.push(span); + } + }); + found + } + + #[test] + fn delivered_spans_keep_their_identity_detail_and_value() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let detail = std::ffi::CString::new("kernel_mul_mv_q4_K_f32").unwrap(); + let span = raw(0x5a, &detail); + // SAFETY: a valid span with static names and a live detail. + unsafe { deliver_native_span_for_test(&raw const span) }; + // The detail was copied; the native buffer may go away. + drop(detail); + + let drained = drained_with_id(0x5a); + assert_eq!(drained.len(), 1); + let span = &drained[0]; + assert_eq!(span.name, "llama.graph_build"); + assert_eq!(span.parent, 41); + assert_eq!(span.detail.as_deref(), Some("kernel_mul_mv_q4_K_f32")); + assert_eq!(span.value, Some(("nodes", 1_234))); + assert_eq!((span.start_unix_nanos, span.end_unix_nanos), (1_000, 4_000)); + } + + #[test] + fn malformed_spans_are_ignored() { + let _serial = RING_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let mut span = raw(0x6b, c"x"); + span.abi_version += 1; + // SAFETY: a valid span with static strings. + unsafe { deliver_native_span_for_test(&raw const span) }; + let mut span = raw(0x6b, c"x"); + span.id &= !NATIVE_SPAN_ID_BIT; + // SAFETY: as above. + unsafe { deliver_native_span_for_test(&raw const span) }; + // SAFETY: null is accepted. + unsafe { deliver_native_span_for_test(std::ptr::null()) }; + assert!(drained_with_id(0x6b).is_empty()); + } + + #[test] + fn span_ids_are_told_apart_from_caller_tags() { + assert!(is_native_span_id(NATIVE_SPAN_ID_BIT | 7)); + assert!(!is_native_span_id(7)); + } +} diff --git a/skippy/crates/skippy-runtime/src/ngram.rs b/skippy/crates/skippy-runtime/src/ngram.rs index 683157bb15..fb64d4395e 100644 --- a/skippy/crates/skippy-runtime/src/ngram.rs +++ b/skippy/crates/skippy-runtime/src/ngram.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ptr::{self, NonNull}; use anyhow::{Context, Result, bail}; @@ -30,7 +31,9 @@ impl Cache { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_ngram_cache_create(ngram_min, ngram_max, &mut raw, &mut error) + native_call!(skippy_ngram_cache_create( + ngram_min, ngram_max, &mut raw, &mut error + )) }; super::ensure_ok(status, error)?; let raw = NonNull::new(raw).context("llama.cpp created a null N-gram cache")?; @@ -62,7 +65,7 @@ impl Cache { let mut output_token_count = 0_usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_ngram_cache_draft( + native_call!(skippy_ngram_cache_draft( self.raw.as_ptr(), continuation_prefix.as_ptr(), continuation_prefix.len(), @@ -71,7 +74,7 @@ impl Cache { output_tokens.len(), &mut output_token_count, &mut error, - ) + )) }; super::ensure_ok(status, error)?; if output_token_count > output_tokens.len() { @@ -85,19 +88,19 @@ impl Cache { let mut error = ptr::null_mut(); let status = unsafe { if reset { - skippy_ffi::skippy_ngram_cache_reset( + native_call!(skippy_ngram_cache_reset( self.raw.as_ptr(), tokens.as_ptr(), tokens.len(), &mut error, - ) + )) } else { - skippy_ffi::skippy_ngram_cache_append( + native_call!(skippy_ngram_cache_append( self.raw.as_ptr(), tokens.as_ptr(), tokens.len(), &mut error, - ) + )) } }; super::ensure_ok(status, error) diff --git a/skippy/crates/skippy-runtime/src/resident_prefix.rs b/skippy/crates/skippy-runtime/src/resident_prefix.rs index 731e93ce76..743e782bf8 100644 --- a/skippy/crates/skippy-runtime/src/resident_prefix.rs +++ b/skippy/crates/skippy-runtime/src/resident_prefix.rs @@ -1,5 +1,6 @@ //! Export cache-owned prefixes only at explicit cold/offload boundaries. use crate::error::{ensure_ok, free_error}; +use crate::native_timing::native_call; use crate::{RuntimeKvPage, RuntimeKvPageDesc, Status, session::StageSession}; use anyhow::{Result, ensure}; use std::ptr; @@ -16,7 +17,7 @@ impl StageSession { let mut error = ptr::null_mut(); // SAFETY: The live session and all output pointers remain valid for the call. let status = unsafe { - skippy_ffi::skippy_session_export_resident_kv_page( + native_call!(skippy_session_export_resident_kv_page( self.raw, sequence, layers.0, @@ -28,7 +29,7 @@ impl StageSession { 0, &mut bytes, &mut error, - ) + )) }; check_export_size(status, error)?; ensure!( @@ -51,7 +52,7 @@ impl StageSession { let mut error = ptr::null_mut(); // SAFETY: The session is live and the output allocation has the advertised capacity. let status = unsafe { - skippy_ffi::skippy_session_export_resident_kv_page( + native_call!(skippy_session_export_resident_kv_page( self.raw, sequence, layers.0, @@ -63,7 +64,7 @@ impl StageSession { payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; ensure!( @@ -82,14 +83,14 @@ impl StageSession { let mut error = ptr::null_mut(); // SAFETY: The live session and byte-count/error outputs are valid. let status = unsafe { - skippy_ffi::skippy_session_export_resident_recurrent_state( + native_call!(skippy_session_export_resident_recurrent_state( self.raw, sequence, ptr::null_mut(), 0, &mut bytes, &mut error, - ) + )) }; check_export_size(status, error)?; Ok(bytes) @@ -105,14 +106,14 @@ impl StageSession { let mut error = ptr::null_mut(); // SAFETY: The session is live and output storage matches the reserved capacity. let status = unsafe { - skippy_ffi::skippy_session_export_resident_recurrent_state( + native_call!(skippy_session_export_resident_recurrent_state( self.raw, sequence, payload.as_mut_ptr().cast(), payload.len(), &mut written, &mut error, - ) + )) }; ensure_ok(status, error)?; ensure!( diff --git a/skippy/crates/skippy-runtime/src/session.rs b/skippy/crates/skippy-runtime/src/session.rs index 090845233f..140edad793 100644 --- a/skippy/crates/skippy-runtime/src/session.rs +++ b/skippy/crates/skippy-runtime/src/session.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::CString; use std::ptr; @@ -93,12 +94,12 @@ impl StageSession { // SAFETY: the session is owned by self and the token slice remains valid // for the call; native code copies the tokens and checks its position. let status = unsafe { - skippy_ffi::skippy_session_restore_token_history( + native_call!(skippy_session_restore_token_history( self.raw, token_ids.as_ptr(), token_ids.len(), &mut error, - ) + )) }; ensure_ok(status, error) } @@ -151,7 +152,7 @@ impl StageSession { pub fn reset(&mut self) -> Result<()> { let mut error = ptr::null_mut(); - let status = unsafe { skippy_ffi::skippy_session_reset(self.raw, &mut error) }; + let status = unsafe { native_call!(skippy_session_reset(self.raw, &mut error)) }; ensure_ok(status, error)?; self.token_count = 0; self.dflash_after_replace(); @@ -167,7 +168,7 @@ impl StageSession { let mut actual_dimensions = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_embed( + native_call!(skippy_session_embed( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -175,7 +176,7 @@ impl StageSession { output.len(), &mut actual_dimensions, &mut error, - ) + )) }; ensure_ok(status, error)?; if actual_dimensions != dimensions { @@ -196,14 +197,14 @@ impl StageSession { let mut token_count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_rerank( + native_call!(skippy_session_rerank( self.raw, query.as_ptr(), document.as_ptr(), &mut score, &mut token_count, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = u64::try_from(token_count).context("token count exceeds u64")?; @@ -215,13 +216,13 @@ impl StageSession { let mut decoder_start_token = 0_i32; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_encode_prompt( + native_call!(skippy_session_encode_prompt( self.raw, token_ids.as_ptr(), token_ids.len(), &mut decoder_start_token, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = 0; @@ -242,13 +243,13 @@ impl StageSession { .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_configure_chat_sampling( + native_call!(skippy_session_configure_chat_sampling( self.raw, sampling_ptr, metadata_json.as_ptr(), prompt_token_count, &mut error, - ) + )) }; ensure_ok(status, error) } @@ -257,12 +258,12 @@ impl StageSession { pub fn retire_verify_checkpoint(&mut self, token_start: u64, token_count: u64) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_retire_verify_checkpoint( + native_call!(skippy_retire_verify_checkpoint( self.raw, token_start, token_count, &mut error, - ) + )) }; ensure_ok(status, error) } @@ -286,7 +287,8 @@ impl StageSession { pub fn trim_session(&mut self, token_count: u64) -> Result<()> { let mut error = ptr::null_mut(); - let status = unsafe { skippy_ffi::skippy_trim_session(self.raw, token_count, &mut error) }; + let status = + unsafe { native_call!(skippy_trim_session(self.raw, token_count, &mut error)) }; ensure_ok(status, error)?; self.token_count = token_count; self.dflash_after_rewind(); @@ -297,7 +299,7 @@ impl StageSession { let n_past = i32::try_from(token_count).context("session position exceeds i32")?; let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_session_set_position(self.raw, n_past, &mut error) }; + unsafe { native_call!(skippy_session_set_position(self.raw, n_past, &mut error)) }; ensure_ok(status, error)?; self.token_count = token_count; self.dflash_after_rewind(); @@ -310,12 +312,12 @@ impl StageSession { let mut error = ptr::null_mut(); // SAFETY: The session is live and both output pointers are valid for this call. let status = unsafe { - skippy_ffi::skippy_session_resident_prefix_bytes( + native_call!(skippy_session_resident_prefix_bytes( self.raw, cache_seq_id, &mut bytes, &mut error, - ) + )) }; ensure_ok(status, error)?; Ok(bytes) @@ -324,7 +326,12 @@ impl StageSession { pub fn save_prefix(&mut self, cache_seq_id: i32, token_count: u64) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_save_prefix(self.raw, cache_seq_id, token_count, &mut error) + native_call!(skippy_session_save_prefix( + self.raw, + cache_seq_id, + token_count, + &mut error + )) }; ensure_ok(status, error) } @@ -332,13 +339,13 @@ impl StageSession { pub fn restore_prefix(&mut self, cache_seq_id: i32, token_ids: &[i32]) -> Result<()> { let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_restore_prefix( + native_call!(skippy_session_restore_prefix( self.raw, cache_seq_id, token_ids.as_ptr(), token_ids.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = u64::try_from(token_ids.len()).context("token count exceeds u64")?; @@ -349,7 +356,7 @@ impl StageSession { pub fn drop_sequence(&mut self, seq_id: i32) -> Result<()> { let mut error = ptr::null_mut(); let status = - unsafe { skippy_ffi::skippy_session_drop_sequence(self.raw, seq_id, &mut error) }; + unsafe { native_call!(skippy_session_drop_sequence(self.raw, seq_id, &mut error)) }; ensure_ok(status, error) } @@ -357,7 +364,11 @@ impl StageSession { let mut used_cells = 0u64; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_memory_used_cells(self.raw, &mut used_cells, &mut error) + native_call!(skippy_session_memory_used_cells( + self.raw, + &mut used_cells, + &mut error + )) }; ensure_ok(status, error)?; Ok(used_cells) @@ -367,7 +378,7 @@ impl StageSession { let mut output_bytes = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_prefill_chunk( + native_call!(skippy_prefill_chunk( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -377,7 +388,7 @@ impl StageSession { 0, &mut output_bytes, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -416,7 +427,7 @@ impl StageSession { .as_ref() .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let status = unsafe { - skippy_ffi::skippy_decode_step_sampled( + native_call!(skippy_decode_step_sampled( self.raw, token_id, sampling_ptr, @@ -427,7 +438,7 @@ impl StageSession { &mut output_bytes, &mut predicted_token, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -458,7 +469,7 @@ impl StageSession { .as_ref() .map_or(ptr::null(), |sampling| sampling as *const RawSamplingConfig); let status = unsafe { - skippy_ffi::skippy_decode_step_sampled_mtp( + native_call!(skippy_decode_step_sampled_mtp( self.raw, token_id, sampling_ptr, @@ -466,7 +477,7 @@ impl StageSession { max_draft_tokens.min(skippy_ffi::NATIVE_MTP_MAX_DRAFT_TOKENS), &mut mtp_draft, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -505,7 +516,7 @@ impl StageSession { let mut predicted_tokens = vec![0_i32; requests.len()]; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_decode_batch_sampled( + native_call!(skippy_decode_batch_sampled( sessions.as_ptr(), token_ids.as_ptr(), sampling.as_ptr(), @@ -513,7 +524,7 @@ impl StageSession { predicted_tokens.as_mut_ptr(), predicted_tokens.len(), &mut error, - ) + )) }; ensure_ok(status, error)?; for (row, request) in requests.iter_mut().enumerate() { @@ -533,7 +544,11 @@ impl StageSession { let mut signal = RawTokenSignal::default(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_last_token_signal(self.raw, &mut signal, &mut error) + native_call!(skippy_session_last_token_signal( + self.raw, + &mut signal, + &mut error + )) }; ensure_ok(status, error)?; Ok(signal.into()) @@ -545,13 +560,13 @@ impl StageSession { let mut pending = 0_usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_take_token_logprobs( + native_call!(skippy_session_take_token_logprobs( self.raw, ptr::null_mut(), 0, &mut pending, &mut error, - ) + )) }; ensure_ok(status, error)?; if pending == 0 { @@ -561,13 +576,13 @@ impl StageSession { let mut taken = 0_usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_take_token_logprobs( + native_call!(skippy_session_take_token_logprobs( self.raw, raw.as_mut_ptr(), raw.len(), &mut taken, &mut error, - ) + )) }; ensure_ok(status, error)?; raw.truncate(taken); @@ -578,12 +593,12 @@ impl StageSession { let mut window = RawGenerationSignalWindow::default(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_session_signal_window( + native_call!(skippy_session_signal_window( self.raw, window_tokens, &mut window, &mut error, - ) + )) }; ensure_ok(status, error)?; Ok(window.into()) @@ -601,7 +616,7 @@ impl StageSession { let mut output_count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_verify_tokens( + native_call!(skippy_verify_tokens( self.raw, token_ids.as_ptr(), token_ids.len(), @@ -609,7 +624,7 @@ impl StageSession { predicted.len(), &mut output_count, &mut error, - ) + )) }; ensure_ok(status, error)?; self.token_count = self @@ -652,7 +667,7 @@ impl Drop for StageSession { fn drop(&mut self) { if !self.raw.is_null() { unsafe { - let _ = skippy_ffi::skippy_session_free(self.raw, ptr::null_mut()); + let _ = native_call!(skippy_session_free(self.raw, ptr::null_mut())); } } } diff --git a/skippy/crates/skippy-runtime/src/speech_recognition.rs b/skippy/crates/skippy-runtime/src/speech_recognition.rs index 107a308c21..fc74ac3220 100644 --- a/skippy/crates/skippy-runtime/src/speech_recognition.rs +++ b/skippy/crates/skippy-runtime/src/speech_recognition.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::ffi::{CStr, CString, c_void}; use std::path::Path; use std::ptr; @@ -105,14 +106,14 @@ impl SpeechRecognitionModel { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_asr_model_open( + native_call!(skippy_asr_model_open( c_path.as_ptr(), c_device .as_ref() .map_or(ptr::null(), |device| device.as_ptr()), &mut raw, &mut error, - ) + )) }; ensure_ok(status, error) .with_context(|| format!("open speech model {}", path.display()))?; @@ -200,7 +201,7 @@ impl SpeechRecognitionModel { let mut raw = ptr::null_mut(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_asr_transcribe( + native_call!(skippy_asr_transcribe( self.raw, samples.as_ptr(), samples.len(), @@ -209,7 +210,7 @@ impl SpeechRecognitionModel { &cancelled as *const F as *mut c_void, &mut raw, &mut error, - ) + )) }; ensure_ok(status, error).context("transcribe audio")?; if raw.is_null() { @@ -223,7 +224,7 @@ impl SpeechRecognitionModel { impl Drop for SpeechRecognitionModel { fn drop(&mut self) { if !self.raw.is_null() { - unsafe { skippy_ffi::skippy_asr_model_free(self.raw) }; + unsafe { native_call!(skippy_asr_model_free(self.raw)) }; } } } @@ -236,13 +237,13 @@ pub fn decode_audio(bytes: &[u8]) -> Result> { let mut count = 0usize; let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_asr_decode_audio( + native_call!(skippy_asr_decode_audio( bytes.as_ptr(), bytes.len(), &mut samples, &mut count, &mut error, - ) + )) }; ensure_ok(status, error).context("decode audio upload")?; if samples.is_null() { diff --git a/skippy/crates/skippy-runtime/src/stage_planning.rs b/skippy/crates/skippy-runtime/src/stage_planning.rs index 51d79b57d4..8c16b69f21 100644 --- a/skippy/crates/skippy-runtime/src/stage_planning.rs +++ b/skippy/crates/skippy-runtime/src/stage_planning.rs @@ -1,3 +1,4 @@ +use crate::native_timing::native_call; use std::collections::BTreeMap; use std::ffi::CString; use std::path::{Path, PathBuf}; @@ -260,8 +261,13 @@ fn plan_gguf_stage_runtime_plans_impl( }; let mut planner = ptr::null_mut(); let mut error = ptr::null_mut(); - let status = - unsafe { skippy_ffi::skippy_stage_planner_create_v1(&config, &mut planner, &mut error) }; + let status = unsafe { + native_call!(skippy_stage_planner_create_v1( + &config, + &mut planner, + &mut error + )) + }; if let Err(error) = ensure_ok(status, error).context("create native stage planner") { if !planner.is_null() { unsafe { skippy_ffi::skippy_stage_planner_free(planner) }; @@ -285,11 +291,11 @@ fn plan_gguf_stage_runtime_plans_impl( .collect::>(); let mut error = ptr::null_mut(); let status = unsafe { - skippy_ffi::skippy_stage_plan_validate_chain_v1( + native_call!(skippy_stage_plan_validate_chain_v1( plan_ptrs.as_ptr(), plan_ptrs.len(), &mut error, - ) + )) }; ensure_ok(status, error).context("validate native stage plan chain")?; } @@ -434,14 +440,16 @@ fn hash_len_prefixed(hash: &mut Sha256, value: &[u8]) { fn realize_plan(planner: &Planner, layer_start: u32, layer_end: u32) -> Result { let mut plan = ptr::null_mut(); let mut error = ptr::null_mut(); + let layer_start = i32::try_from(layer_start).context("stage layer start exceeds i32")?; + let layer_end = i32::try_from(layer_end).context("stage layer end exceeds i32")?; let status = unsafe { - skippy_ffi::skippy_stage_planner_realize_v1( + native_call!(skippy_stage_planner_realize_v1( planner.0, - i32::try_from(layer_start).context("stage layer start exceeds i32")?, - i32::try_from(layer_end).context("stage layer end exceeds i32")?, + layer_start, + layer_end, &mut plan, &mut error, - ) + )) }; if let Err(error) = ensure_ok(status, error).context("realize native stage plan") { if !plan.is_null() { diff --git a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs index e9c3206378..a907747015 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/binary_messaging.rs @@ -427,6 +427,7 @@ fn run_binary_stage( ) -> Result> { options.tuning.validate()?; let mtp_source = options.resolved_mtp_source(); + let recurrent_rollback_tokens = options.recurrent_rollback_tokens(); let BinaryStageOptions { tuning, config, @@ -486,10 +487,7 @@ fn run_binary_stage( mtp_source, n_threads: tuning.n_threads, n_threads_batch: tuning.n_threads_batch, - recurrent_rollback_tokens: split_dflash.as_ref().map_or( - 0, - crate::split_dflash::SplitDFlashStage::recurrent_rollback_tokens, - ), + recurrent_rollback_tokens, }; let runtime = match load_runtime_with_overrides(&config, &overrides, None) { // A native runtime that predates borrowed tensors refuses them; the diff --git a/skippy/crates/skippy-serving/src/binary_transport/options.rs b/skippy/crates/skippy-serving/src/binary_transport/options.rs index fa043bea32..d6456ca931 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/options.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/options.rs @@ -72,6 +72,26 @@ pub struct EmbeddedOpenAiStageOptions { } impl BinaryStageOptions { + /// Size known plans before opening the stage. A transport-only stage has + /// no proposal-window contract, so retain the historical two-input floor; + /// larger incoming windows still use checkpoint/replay fallback. + pub(super) fn recurrent_rollback_tokens(&self) -> u32 { + let planned = self.openai.as_ref().map_or(2, |openai| { + openai.speculative.recurrent_rollback_tokens( + (self.resolved_mtp_source() != MtpSource::Disabled) + .then_some(openai.native_mtp_max_tokens), + openai + .draft_model_path + .as_ref() + .map(|_| openai.speculative_window), + ) + }); + planned.max(self.split_dflash.as_ref().map_or( + 0, + crate::split_dflash::SplitDFlashStage::recurrent_rollback_tokens, + )) + } + /// Resolve the MTP source from the admitted stage and optional OpenAI settings. pub fn resolved_mtp_source(&self) -> MtpSource { if !self.native_mtp_enabled || !self.config.native_mtp_enabled { @@ -90,3 +110,43 @@ impl BinaryStageOptions { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn options() -> BinaryStageOptions { + BinaryStageOptions { + tuning: Default::default(), + config: StageConfig::default(), + topology: None, + bind_addr: "127.0.0.1:0".parse().unwrap(), + metrics_otlp_grpc: None, + telemetry_queue_capacity: 0, + telemetry_level: TelemetryLevel::Off, + max_inflight: 1, + reply_credit_limit: None, + async_prefill_forward: false, + downstream_wire_condition: WireCondition::new(0.0, None).unwrap(), + downstream_connect_timeout_secs: 1, + native_mtp_enabled: false, + last_stage_decode_batch: None, + continuous_batching: true, + openai: None, + compute_meter: None, + l3_manager: None, + split_dflash: None, + } + } + + #[test] + fn unknown_binary_verifiers_keep_a_compatibility_floor() { + let mut options = options(); + assert_eq!(options.recurrent_rollback_tokens(), 2); + options.split_dflash = Some(crate::split_dflash::SplitDFlashStage { + max_draft_tokens: Some(7), + ..Default::default() + }); + assert_eq!(options.recurrent_rollback_tokens(), 8); + } +} diff --git a/skippy/crates/skippy-serving/src/embedded.rs b/skippy/crates/skippy-serving/src/embedded.rs index a00f79fd39..b7b2d97cef 100644 --- a/skippy/crates/skippy-serving/src/embedded.rs +++ b/skippy/crates/skippy-serving/src/embedded.rs @@ -20,7 +20,11 @@ use crate::{ RuntimeLaunchOverrides, RuntimeSessionStats, RuntimeState, load_runtime_with_overrides, load_runtime_with_overrides_and_open_events, }, - telemetry::{Telemetry, TelemetryLevel, TelemetryStats, lifecycle_attrs, now_unix_nanos}, + telemetry::{ + Telemetry, TelemetryLevel, TelemetryStats, + active_span::{ActiveSpan, SpanLevel}, + lifecycle_attrs, now_unix_nanos, + }, tokenizer::{TokenizerCapability, TokenizerCapabilityError, tokenizer_http_router}, }; @@ -200,6 +204,12 @@ impl SkippyRuntimeHandle { options.config.clone(), options.telemetry_level, ); + let load = ActiveSpan::start( + Some(&telemetry), + "stage.embedded_runtime_load", + SpanLevel::Summary, + ); + let entered = load.enter(); telemetry.emit( "stage.embedded_runtime_load_start", lifecycle_attrs(&options.config), @@ -219,6 +229,10 @@ impl SkippyRuntimeHandle { "stage.embedded_runtime_ready", lifecycle_attrs(&options.config), ); + telemetry.record_resources("runtime_ready"); + crate::telemetry::log_events::mark_serving(); + drop(entered); + load.end(); Ok(Self::ready( options.config, options.topology, @@ -241,6 +255,12 @@ impl SkippyRuntimeHandle { options.config.clone(), options.telemetry_level, ); + let load = ActiveSpan::start( + Some(&telemetry), + "stage.embedded_runtime_load", + SpanLevel::Summary, + ); + let entered = load.enter(); telemetry.emit( "stage.embedded_runtime_load_start", lifecycle_attrs(&options.config), @@ -261,6 +281,10 @@ impl SkippyRuntimeHandle { "stage.embedded_runtime_ready", lifecycle_attrs(&options.config), ); + telemetry.record_resources("runtime_ready"); + crate::telemetry::log_events::mark_serving(); + drop(entered); + load.end(); Ok(Self::ready( options.config, options.topology, @@ -346,6 +370,7 @@ impl SkippyRuntimeHandle { "stage.embedded_runtime_stopped", lifecycle_attrs(&self.config), ); + self.telemetry.finish_process(); } } diff --git a/skippy/crates/skippy-serving/src/frontend/backend/phase_spans.rs b/skippy/crates/skippy-serving/src/frontend/backend/phase_spans.rs new file mode 100644 index 0000000000..45954c1aa4 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/backend/phase_spans.rs @@ -0,0 +1,84 @@ +//! OpenAI request phases as spans. A phase that will be exported can be +//! entered so the work inside it, including native calls, nests beneath it; +//! one that will not be exported is never entered, so nothing points at it. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use crate::frontend::generation::{PhaseTimer, StageOpenAiBackend}; +use crate::telemetry::now_unix_nanos; +use crate::telemetry::trace_context::{Entered, TaskEntered}; + +impl StageOpenAiBackend { + /// Nest synchronous work under a phase emitted by [`Self::emit_openai_phase`]. + pub(in crate::frontend) fn enter_openai_phase(&self, timer: &PhaseTimer) -> Option { + self.telemetry + .is_debug_enabled() + .then(|| timer.frame.enter()) + } + + /// Nest async work under a phase emitted by [`Self::emit_openai_phase`]. + pub(in crate::frontend) fn enter_openai_phase_task( + &self, + timer: &PhaseTimer, + ) -> Option { + self.telemetry + .is_debug_enabled() + .then(|| timer.frame.enter_task()) + } + + /// Nest synchronous work under a phase emitted by [`Self::emit_openai_summary`]. + pub(in crate::frontend) fn enter_openai_summary(&self, timer: &PhaseTimer) -> Option { + self.telemetry.is_enabled().then(|| timer.frame.enter()) + } + + /// Nest async work under a phase emitted by [`Self::emit_openai_summary`]. + pub(in crate::frontend) fn enter_openai_summary_task( + &self, + timer: &PhaseTimer, + ) -> Option { + self.telemetry + .is_enabled() + .then(|| timer.frame.enter_task()) + } + + pub(in crate::frontend) fn emit_openai_phase( + &self, + name: &str, + timer: PhaseTimer, + mut attrs: BTreeMap, + ) -> f64 { + let elapsed_ms = timer.elapsed_ms(); + attrs.insert("llama_stage.elapsed_ms".to_string(), json!(elapsed_ms)); + let end = now_unix_nanos() as u64; + self.telemetry.emit_debug_frame_span( + &timer.frame, + name, + attrs, + timer.start_unix_nanos, + end, + ); + elapsed_ms + } + + pub(in crate::frontend) fn emit_openai_summary( + &self, + name: &str, + timer: PhaseTimer, + mut attrs: BTreeMap, + ) -> f64 { + let elapsed_ms = timer.elapsed_ms(); + attrs.insert("llama_stage.elapsed_ms".to_string(), json!(elapsed_ms)); + let end = now_unix_nanos() as u64; + self.telemetry.emit_frame_span( + &timer.frame, + name, + attrs, + timer.start_unix_nanos, + end, + Vec::new(), + ); + elapsed_ms + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/generation.rs b/skippy/crates/skippy-serving/src/frontend/generation.rs index fb7db8aa36..d069ecc635 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation.rs @@ -2,6 +2,7 @@ mod cache_hints; mod concurrency; mod draft_runner; mod execution; +mod http_request_span; mod incremental_text; mod live_request_defaults; mod parsing; diff --git a/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs b/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs new file mode 100644 index 0000000000..c4415c66d9 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs @@ -0,0 +1,160 @@ +//! One span per OpenAI HTTP request. Everything the handler does, including +//! blocking work it hands off, nests beneath it. A streamed response keeps the +//! span open until its body ends or the client goes away, so the span covers +//! the whole generation instead of stopping at the response headers. + +use std::{ + pin::Pin, + task::{Context, Poll}, +}; + +use axum::{ + body::{Body, BodyDataStream, Bytes}, + extract::State, + http::{Request, header}, + middleware::Next, + response::Response, +}; +use futures_util::Stream; +use serde_json::json; + +use crate::telemetry::{ + Telemetry, + active_span::{ActiveSpan, SpanLevel}, + trace_context, +}; + +pub(in crate::frontend) async fn openai_http_telemetry( + State(telemetry): State, + request: Request, + next: Next, +) -> Response { + let mut span = ActiveSpan::start( + Some(&telemetry), + "stage.openai_http_request", + SpanLevel::Summary, + ); + telemetry.record_resources_on(span.frame(), "request_start"); + let method = request.method().to_string(); + let path = request.uri().path().to_string(); + let response = trace_context::in_task(span.frame().clone(), next.run(request)).await; + telemetry.record_resources_on(span.frame(), "request_response"); + let streamed = is_event_stream(&response); + span.extend_attributes([ + ("llama_stage.http_method".to_string(), json!(method)), + ("llama_stage.http_path".to_string(), json!(path)), + ( + "llama_stage.http_status".to_string(), + json!(response.status().as_u16()), + ), + // Time to response headers; the span itself runs to the body's end. + ( + "llama_stage.elapsed_ms".to_string(), + json!(span.elapsed().as_secs_f64() * 1_000.0), + ), + ("llama_stage.http_streamed".to_string(), json!(streamed)), + ]); + if !streamed { + span.end(); + return response; + } + response.map(|body| { + Body::from_stream(SpannedBody { + inner: body.into_data_stream(), + _span: span, + }) + }) +} + +fn is_event_stream(response: &Response) -> bool { + response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.starts_with("text/event-stream")) +} + +/// A response body that ends the request span when it is dropped: after the +/// last chunk is sent, or when the client disconnects. +struct SpannedBody { + inner: BodyDataStream, + _span: ActiveSpan, +} + +impl Stream for SpannedBody { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_next(cx) + } +} + +#[cfg(test)] +mod tests { + use axum::{Router, middleware, routing::get}; + use serde_json::json; + use tower::ServiceExt; + + use super::*; + use crate::telemetry::{TelemetryLevel, capture_stage_config}; + + fn router(telemetry: Telemetry) -> Router { + Router::new() + .route( + "/stream", + get(|| async { + Response::builder() + .header(header::CONTENT_TYPE, "text/event-stream") + .body(Body::from_stream(futures_util::stream::iter([Ok::< + _, + std::io::Error, + >( + "data: x\n\n", + )]))) + .expect("stream response") + }), + ) + .route("/json", get(|| async { "{}" })) + .layer(middleware::from_fn_with_state( + telemetry, + openai_http_telemetry, + )) + } + + fn get_request(path: &str) -> Request { + Request::get(path).body(Body::empty()).expect("request") + } + + #[tokio::test] + async fn a_streamed_response_keeps_its_span_open_until_the_body_ends() { + let (telemetry, rx) = Telemetry::captured(capture_stage_config(), TelemetryLevel::Summary); + let response = router(telemetry) + .oneshot(get_request("/stream")) + .await + .expect("response"); + assert!( + rx.try_recv().is_err(), + "headers alone must not end the span" + ); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + assert_eq!(body, "data: x\n\n"); + let span = rx.try_recv().expect("span ends with the body"); + assert_eq!(span.event, "stage.openai_http_request"); + assert_eq!(span.attributes["llama_stage.http_streamed"], json!(true)); + } + + #[tokio::test] + async fn a_buffered_response_ends_its_span_at_the_response() { + let (telemetry, rx) = Telemetry::captured(capture_stage_config(), TelemetryLevel::Summary); + let _response = router(telemetry) + .oneshot(get_request("/json")) + .await + .expect("response"); + let span = rx.try_recv().expect("span ends with the response"); + assert_eq!(span.attributes["llama_stage.http_streamed"], json!(false)); + assert_eq!(span.attributes["llama_stage.http_status"], json!(200)); + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index c5fb78bcb9..19e573303b 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -1,3 +1,4 @@ +use super::http_request_span::openai_http_telemetry; use super::request_defaults::EmbeddedOpenAiRequestDefaults; use crate::binary_transport::PredictionReturnHub; use crate::binary_transport::WireCondition; @@ -11,7 +12,6 @@ use crate::frontend::generation::GenerationConcurrencyController; use crate::frontend::generation::GenerationServiceEstimator; use crate::frontend::generation::InferenceBackendMode; use crate::frontend::generation::PersistentStageLanePool; -use crate::frontend::generation::PhaseTimer; use crate::frontend::generation::StageOpenAiBackend; use crate::frontend::generation::attach_dflash_draft; use crate::frontend::generation::attach_native_mtp_draft_model; @@ -29,8 +29,8 @@ use crate::listener::bind_serve_listener; use crate::runtime_state::RuntimeState; use crate::runtime_state::loaded_model_state_kind; use crate::telemetry::Telemetry; +use crate::telemetry::active_span::{ActiveSpan, SpanLevel}; use crate::telemetry::lifecycle_attrs; -use crate::telemetry::now_unix_nanos; use crate::thinking_probe::ThinkingProbeInputs; use crate::thinking_probe::emit_probe_status; use crate::thinking_probe::native_renderer_identity; @@ -41,12 +41,7 @@ use anyhow::Result; use anyhow::anyhow; use anyhow::bail; use axum::Router; -use axum::body::Body; -use axum::extract::State; -use axum::http::Request; use axum::middleware; -use axum::middleware::Next; -use axum::response::Response; use serde_json::Value; use serde_json::json; use skippy_inference_api::InferenceBackend; @@ -243,6 +238,13 @@ fn embedded_openai_backend_with_state_kind( iteration_scheduler: Option, state_kind: Option, ) -> Result { + // Startup work (prewarm, cache wiring, scheduler start) nests here. + let setup = ActiveSpan::start( + Some(&args.telemetry), + "stage.openai_server_setup", + SpanLevel::Summary, + ); + let _setup = setup.enter(); if args.prefill_chunk_size == 0 { bail!("--prefill-chunk-size must be greater than zero"); } @@ -390,6 +392,7 @@ fn embedded_openai_backend_with_state_kind( ); args.telemetry .emit("stage.openai_server_start", server_start_attrs); + args.telemetry.record_resources("server_start"); #[cfg(test)] if !modelless { prewarm_generation_sessions( @@ -636,34 +639,6 @@ pub(in crate::frontend) fn instrumented_openai_router( )) } -pub(in crate::frontend) async fn openai_http_telemetry( - State(telemetry): State, - request: Request, - next: Next, -) -> Response { - let timer = PhaseTimer::start(); - let method = request.method().to_string(); - let path = request.uri().path().to_string(); - let response = next.run(request).await; - let status = response.status().as_u16(); - let mut attrs = BTreeMap::from([ - ("llama_stage.http_method".to_string(), json!(method)), - ("llama_stage.http_path".to_string(), json!(path)), - ("llama_stage.http_status".to_string(), json!(status)), - ]); - attrs.insert( - "llama_stage.elapsed_ms".to_string(), - json!(timer.elapsed_ms()), - ); - telemetry.emit_span( - "stage.openai_http_request", - attrs, - timer.start_unix_nanos, - now_unix_nanos() as u64, - ); - response -} - /// Readiness cannot be printed for a socket whose bind failed. A writer error /// drops the already-owned listener before returning to the command caller. fn bind_with_readiness( diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 83e53459aa..a13a1ad5a6 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -1,10 +1,12 @@ pub(super) mod cache_runtime; mod cache_wave; +mod command_waits; mod detached_runtime; mod direct_batch; mod direct_execution; mod direct_reply; pub(crate) mod readout; +mod step_telemetry; use self::cache_runtime::{ CacheAffinityRefresh, CacheRuntimeQueue, CacheRuntimeTelemetry, @@ -17,6 +19,7 @@ use self::direct_batch::{ should_serve_direct, take_direct_iteration_batch, validate_direct_iteration, }; use self::direct_reply::DirectReply; +use self::step_telemetry::{StepTiming, sample_kv_used_cells}; use crate::frontend::admission::DECODE_BATCH_HEADROOM_TOKENS; use crate::frontend::generation::TokenControl; use crate::frontend::generation::generation_queue_full_error; @@ -25,6 +28,9 @@ use crate::kv_integration::scheduling::CacheSchedulingPolicy; use crate::runtime_state::panic_recovery::lock_runtime; use crate::runtime_state::{RuntimeIterationBatchRequest, RuntimeSessionAlignStats, RuntimeState}; use crate::telemetry::Telemetry; +use crate::telemetry::active_span::{ActiveSpan, SpanLevel}; +use crate::telemetry::resource_metrics; +use crate::telemetry::trace_context; use serde_json::json; use skippy_inference_api::{InferenceError, InferenceResult}; use skippy_protocol::StageConfig; @@ -51,6 +57,13 @@ const DIRECT_ITERATION_COALESCE_WINDOW: Duration = Duration::from_millis(2); const CACHE_AGING_COST_PER_TURN: u64 = 4_096; const SAFE_MODE_ENV: &str = "SKIPPY_ITERATION_SCHEDULER_SAFE_MODE"; +/// One planned iteration's native outputs and the pool occupancy observed +/// under the same runtime lease. +struct ExecutedPlan { + predicted: Vec, + kv_used_cells: Option, +} + #[derive(Debug, Clone, Copy, Default, PartialEq)] pub(super) struct ScheduledGenerationStats { pub(super) prompt_ms: f64, @@ -246,10 +259,12 @@ where { let (reply, result) = std_mpsc::sync_channel(1); let enqueued_at = Instant::now(); + let origin = trace_context::current_frame(); let operation = RuntimeOperation { label, control: None, run: Box::new(move |runtime: &Arc>| { + let _origin = origin.as_ref().map(trace_context::Frame::enter); let queue_wait_ms = enqueued_at.elapsed().as_secs_f64() * 1_000.0; let lock_started = Instant::now(); // The compute meter covers lock-held work only: from guard @@ -297,10 +312,12 @@ where let enqueued_at = Instant::now(); let control = CacheRuntimeContext::new(operation_id, deadline, cancellation); let worker_control = control.clone(); + let origin = trace_context::current_frame(); let runtime_operation = RuntimeOperation { label, control: Some(control.clone()), run: Box::new(move |runtime: &Arc>| { + let _origin = origin.as_ref().map(trace_context::Frame::enter); let queue_wait_ms = enqueued_at.elapsed().as_secs_f64() * 1_000.0; let lock_started = Instant::now(); // Compute meter: lock-held work only, as in `runtime_operation`. @@ -477,9 +494,19 @@ impl IterationScheduler { ]), ); let (commands, receiver) = std_mpsc::sync_channel(command_queue_capacity); + // The worker outlives whatever constructs it, so its span hangs off + // the process root rather than the setup section that starts it. + let scheduler_span = ActiveSpan::start_under_process( + Some(&telemetry), + "stage.scheduler", + SpanLevel::Summary, + ); let worker = thread::Builder::new() .name("skippy-iteration-scheduler".to_string()) .spawn(move || { + // Iterations and runtime work on this thread nest under the + // scheduler's span for its whole life. + let _scheduler = scheduler_span.enter(); SchedulerWorker { runtime, scheduler, @@ -527,6 +554,7 @@ impl IterationScheduler { ) -> InferenceResult { let started = Instant::now(); let (reply, events) = std_mpsc::channel(); + let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), prompt_tokens: request.prompt_tokens.to_vec(), @@ -556,6 +584,7 @@ impl IterationScheduler { ) -> InferenceResult { let started = Instant::now(); let (reply, events) = std_mpsc::channel(); + let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), prompt_tokens: request.prompt_tokens.to_vec(), @@ -738,6 +767,7 @@ impl IterationScheduler { self.shared.max_direct_iteration_tokens, )?; ensure_direct_iteration_active(deadline, cancellation)?; + let _sequence = trace_context::bind_sequence(session_id); self.enqueue_command(SchedulerCommand::ExecuteIteration(Box::new( DirectIteration { session_id: session_id.to_string(), @@ -878,11 +908,9 @@ impl SchedulerWorker { if self.requests.is_empty() && self.direct_iterations.is_empty() && self.cache_runtime_queue.is_empty() + && !self.wait_idle() { - match self.commands.recv() { - Ok(SchedulerCommand::Shutdown) | Err(_) => break, - Ok(command) => self.handle_command(command), - } + break; } for _ in 0..self.max_commands_per_turn { match self.commands.try_recv() { @@ -903,7 +931,10 @@ impl SchedulerWorker { } self.refresh_cache_wave_sessions(); if self.should_defer_cache_runtime() { - if !self.wait_for_scheduler_command(DIRECT_ITERATION_COALESCE_WINDOW) { + if !self.wait_for_scheduler_command( + "stage.scheduler_cache_defer", + DIRECT_ITERATION_COALESCE_WINDOW, + ) { return; } continue; @@ -922,16 +953,8 @@ impl SchedulerWorker { return; } self.run_work_turn(); - if !self.iteration_interval.is_zero() { - match self.commands.recv_timeout(self.iteration_interval) { - Ok(SchedulerCommand::Shutdown) => { - self.fail_all(InferenceError::backend("iteration scheduler stopped")); - return; - } - Ok(command) => self.handle_command(command), - Err(std_mpsc::RecvTimeoutError::Timeout) => {} - Err(std_mpsc::RecvTimeoutError::Disconnected) => return, - } + if !self.wait_iteration_interval() { + return; } } } @@ -965,21 +988,6 @@ impl SchedulerWorker { } } - fn wait_for_scheduler_command(&mut self, timeout: Duration) -> bool { - match self.commands.recv_timeout(timeout) { - Ok(SchedulerCommand::Shutdown) => { - self.fail_all(InferenceError::backend("iteration scheduler stopped")); - false - } - Ok(command) => { - self.handle_command(command); - true - } - Err(std_mpsc::RecvTimeoutError::Timeout) => true, - Err(std_mpsc::RecvTimeoutError::Disconnected) => false, - } - } - fn run_cache_runtime_operation(&mut self) { let Some((queued, telemetry)) = self.cache_runtime_queue.pop_next() else { return; @@ -995,9 +1003,17 @@ impl SchedulerWorker { let started = Instant::now(); let label = operation.label; let cache_operation = operation.control.clone(); + // The operation's native calls nest under its span. + let mut span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_feature_runtime", + SpanLevel::Debug, + ); + let entered = span.enter(); // Only lock-held runtime work counts as compute time; scheduler-side // waits, including lock contention, are excluded from the meter. let compute = (operation.run)(&self.runtime); + drop(entered); self.record_compute(compute); { let runtime = lock_runtime(&self.runtime); @@ -1012,7 +1028,7 @@ impl SchedulerWorker { // another cache restore cannot slip in during that gap. self.direct_wave_full = true; } - if let Some(telemetry) = self.telemetry.as_ref() { + if self.telemetry.is_some() { let mut attrs = BTreeMap::from([ ("skippy.scheduler.operation".to_string(), json!(label)), ( @@ -1061,36 +1077,9 @@ impl SchedulerWorker { json!(cache.stale_affinity_fallback), ); } - telemetry.emit_debug("stage.scheduler_feature_runtime", attrs); - } - } - - fn coalesce_direct_iterations(&mut self) -> bool { - let target = direct_coalesce_target( - self.active_runtime_sessions, - self.direct_iterations.len(), - self.direct_group_batch_size, - ); - if target <= self.direct_iterations.len() { - return true; - } - - let deadline = Instant::now() + DIRECT_ITERATION_COALESCE_WINDOW; - while self.direct_iterations.len() < target { - let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { - break; - }; - match self.commands.recv_timeout(remaining) { - Ok(SchedulerCommand::Shutdown) => { - self.fail_all(InferenceError::backend("iteration scheduler stopped")); - return false; - } - Ok(command) => self.handle_command(command), - Err(std_mpsc::RecvTimeoutError::Timeout) => break, - Err(std_mpsc::RecvTimeoutError::Disconnected) => return false, - } + span.extend_attributes(attrs); } - true + span.end(); } fn submit(&mut self, request: ScheduledRequest) { @@ -1211,11 +1200,24 @@ impl SchedulerWorker { return; } - let iteration_started = Instant::now(); + let iteration = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_iteration", + SpanLevel::Debug, + ); + let plan_span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_plan", + SpanLevel::Debug, + ); let mut plan = self.scheduler.plan_iteration(); + plan_span.end(); if plan.work.is_empty() { + iteration.discard(); return; } + // Session setup and native execution for this step nest under it. + let entered = iteration.enter(); self.last_served_direct = false; let mut setup_ids = BTreeSet::new(); @@ -1233,7 +1235,18 @@ impl SchedulerWorker { )); } } - let (configured, setup_failures) = match self.prepare_runtime_sessions(&setup) { + let setup_span = (!setup.is_empty()).then(|| { + ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_session_setup", + SpanLevel::Debug, + ) + }); + let prepared = self.prepare_runtime_sessions(&setup); + if let Some(span) = setup_span { + span.end(); + } + let (configured, setup_failures) = match prepared { Ok(result) => result, Err(error) => { self.fail_all(error); @@ -1258,18 +1271,45 @@ impl SchedulerWorker { let execution_started = Instant::now(); let result = self.execute_plan(&plan); let execution_elapsed = execution_started.elapsed(); - let predicted = match result { - Ok(predicted) => predicted, + let executed = match result { + Ok(executed) => executed, Err(error) => { self.fail_all(error); return; } }; + let complete_span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_complete", + SpanLevel::Debug, + ); self.scheduler .observe_iteration_duration(&plan, execution_elapsed); - let step = self.scheduler.complete_iteration(&plan, &predicted); - self.finish_iteration(&plan, &predicted); - self.emit_step_telemetry(&step, iteration_started.elapsed(), execution_elapsed); + let step = self + .scheduler + .complete_iteration(&plan, &executed.predicted); + self.finish_iteration(&plan, &executed.predicted); + resource_metrics::record_scheduler( + step.active_sequences, + step.waiting_sequences, + plan.work.len(), + ); + complete_span.end(); + drop(entered); + let links = plan + .work + .iter() + .filter_map(|work| trace_context::sequence_context(&work.sequence_id)) + .collect(); + self.emit_step_telemetry( + &step, + StepTiming { + span: iteration, + execution_elapsed, + kv_used_cells: executed.kv_used_cells, + links, + }, + ); } fn finish_iteration( @@ -1345,129 +1385,11 @@ impl SchedulerWorker { } } - fn emit_step_telemetry( - &mut self, - step: &skippy_scheduler::IterationTelemetry, - elapsed: Duration, - execution_elapsed: Duration, - ) { - if self.telemetry.is_none() { - return; - } - let lifecycle_counters = ( - step.finished, - step.failed, - step.cancelled, - step.rejected_overload, - ); - let lifecycle_changed = lifecycle_counters != self.last_emitted_lifecycle_counters; - if lifecycle_changed { - self.last_emitted_lifecycle_counters = lifecycle_counters; - } - let telemetry = self - .telemetry - .as_ref() - .expect("telemetry presence checked above"); - let mut attrs = BTreeMap::from([ - ( - "skippy.scheduler.iteration".to_string(), - json!(step.iteration), - ), - ( - "skippy.scheduler.running".to_string(), - json!(step.active_sequences), - ), - ( - "skippy.scheduler.waiting".to_string(), - json!(step.waiting_sequences), - ), - ( - "skippy.scheduler.admitted".to_string(), - json!(step.admitted), - ), - ( - "skippy.scheduler.preempted".to_string(), - json!(step.preempted), - ), - ( - "skippy.scheduler.prefill_tokens".to_string(), - json!(step.prefill_tokens), - ), - ( - "skippy.scheduler.recompute_tokens".to_string(), - json!(step.recompute_tokens), - ), - ( - "skippy.scheduler.decode_tokens".to_string(), - json!(step.decode_tokens), - ), - ( - "skippy.scheduler.prefix_hits".to_string(), - json!(step.prefix_hits), - ), - ( - "skippy.scheduler.prefix_misses".to_string(), - json!(step.prefix_misses), - ), - ( - "skippy.scheduler.step_ms".to_string(), - json!(elapsed.as_secs_f64() * 1_000.0), - ), - ( - "skippy.scheduler.execution_ms".to_string(), - json!(execution_elapsed.as_secs_f64() * 1_000.0), - ), - ( - "skippy.scheduler.overhead_ms".to_string(), - json!(elapsed.saturating_sub(execution_elapsed).as_secs_f64() * 1_000.0), - ), - ]); - if lifecycle_changed { - attrs.extend([ - ( - "skippy.scheduler.finished".to_string(), - json!(step.finished), - ), - ("skippy.scheduler.failed".to_string(), json!(step.failed)), - ( - "skippy.scheduler.cancelled".to_string(), - json!(step.cancelled), - ), - ( - "skippy.scheduler.rejected_overload".to_string(), - json!(step.rejected_overload), - ), - ]); - } - for (name, used) in &step.component_used_bytes { - attrs.insert( - format!("skippy.scheduler.component.{name}.used_bytes"), - json!(used), - ); - } - for (name, available) in &step.component_available_bytes { - attrs.insert( - format!("skippy.scheduler.component.{name}.available_bytes"), - json!(available), - ); - let used = step - .component_used_bytes - .iter() - .find_map(|(used_name, used)| (used_name == name).then_some(*used)) - .unwrap_or(0); - attrs.insert( - format!("skippy.scheduler.component.{name}.free_bytes"), - json!(available.saturating_sub(used)), - ); - } - telemetry.emit_debug("stage.scheduler_iteration", attrs); - } - fn prepare_runtime_sessions( &self, setup: &[(String, Option, Option, usize)], ) -> InferenceResult { - let mut runtime = lock_runtime(&self.runtime); + let mut runtime = self.lock_runtime_traced(); let mut configured = Vec::new(); let mut failures = Vec::new(); for (id, metadata, sampling, prompt_token_count) in setup { @@ -1499,15 +1421,28 @@ impl SchedulerWorker { Ok((configured, failures)) } + /// Take the runtime lock, its wait a debug span. + fn lock_runtime_traced(&self) -> std::sync::MutexGuard<'_, RuntimeState> { + let span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.runtime_lock_wait", + SpanLevel::Debug, + ); + let runtime = lock_runtime(&self.runtime); + span.end(); + runtime + } + fn record_compute(&self, elapsed: Duration) { self.compute_meter.record(elapsed); + resource_metrics::record_runtime_busy(elapsed); } fn execute_plan( &self, plan: &skippy_scheduler::IterationPlan, - ) -> InferenceResult> { - let mut runtime = lock_runtime(&self.runtime); + ) -> InferenceResult { + let mut runtime = self.lock_runtime_traced(); let hold_started = Instant::now(); let requests = plan .work @@ -1531,24 +1466,30 @@ impl SchedulerWorker { }) .collect::>(); let result = runtime.iteration_batch_sampled(&requests); + let hold = hold_started.elapsed(); + let kv_used_cells = plan.work.first().and_then(|work| { + sample_kv_used_cells(self.telemetry.as_ref(), &mut runtime, &work.sequence_id) + }); drop(runtime); - self.record_compute(hold_started.elapsed()); + self.record_compute(hold); let decode_steps = plan .work .iter() .filter(|work| work.phase == IterationPhase::Decode) .count(); self.compute_meter.record_decode_tokens(decode_steps as u64); + resource_metrics::record_decode_tokens(decode_steps as u64); result - .map(|outputs| { - outputs + .map(|outputs| ExecutedPlan { + predicted: outputs .samples .into_iter() .map(|sample| IterationPrediction { work_index: sample.request_index, token: sample.predicted_token, }) - .collect() + .collect(), + kv_used_cells, }) .map_err(openai_backend_error) } diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs new file mode 100644 index 0000000000..1dc7b091dc --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs @@ -0,0 +1,121 @@ +//! How the scheduler worker waits for commands: idle until work arrives, +//! briefly while a cache operation defers, while a direct batch coalesces, +//! and between iterations. Each wait is a debug span under `stage.scheduler`, +//! so time the runtime sits unused between native calls has a name. + +use super::*; + +impl SchedulerWorker { + /// Block for the next command while no work is queued; false once the + /// worker should stop. + pub(super) fn wait_idle(&mut self) -> bool { + let span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_idle", + SpanLevel::Debug, + ); + let command = self.commands.recv(); + span.end(); + match command { + Ok(SchedulerCommand::Shutdown) | Err(_) => false, + Ok(command) => { + self.handle_command(command); + true + } + } + } + + /// Wait up to `timeout` for one command, as the span `name`; false once + /// the worker should stop. + pub(super) fn wait_for_scheduler_command( + &mut self, + name: &'static str, + timeout: Duration, + ) -> bool { + let span = ActiveSpan::start(self.telemetry.as_ref(), name, SpanLevel::Debug); + let command = self.commands.recv_timeout(timeout); + span.end(); + match command { + Ok(SchedulerCommand::Shutdown) => { + self.fail_all(InferenceError::backend("iteration scheduler stopped")); + false + } + Ok(command) => { + self.handle_command(command); + true + } + Err(std_mpsc::RecvTimeoutError::Timeout) => true, + Err(std_mpsc::RecvTimeoutError::Disconnected) => false, + } + } + + /// Hold a direct batch open for up to the coalesce window while more + /// active sessions may still join it; false once the worker should stop. + pub(super) fn coalesce_direct_iterations(&mut self) -> bool { + let target = direct_coalesce_target( + self.active_runtime_sessions, + self.direct_iterations.len(), + self.direct_group_batch_size, + ); + let queued_before = self.direct_iterations.len(); + if target <= queued_before { + return true; + } + + let mut span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_coalesce", + SpanLevel::Debug, + ); + let deadline = Instant::now() + DIRECT_ITERATION_COALESCE_WINDOW; + let mut timed_out = false; + let mut running = true; + while running && self.direct_iterations.len() < target { + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + timed_out = true; + break; + }; + match self.commands.recv_timeout(remaining) { + Ok(SchedulerCommand::Shutdown) => { + self.fail_all(InferenceError::backend("iteration scheduler stopped")); + running = false; + } + Ok(command) => self.handle_command(command), + Err(std_mpsc::RecvTimeoutError::Timeout) => timed_out = true, + Err(std_mpsc::RecvTimeoutError::Disconnected) => running = false, + } + if timed_out { + break; + } + } + span.extend_attributes([ + ( + "skippy.scheduler.coalesce_target".to_string(), + json!(target), + ), + ( + "skippy.scheduler.coalesce_queued_before".to_string(), + json!(queued_before), + ), + ( + "skippy.scheduler.coalesce_queued_after".to_string(), + json!(self.direct_iterations.len()), + ), + ( + "skippy.scheduler.coalesce_timed_out".to_string(), + json!(timed_out), + ), + ]); + span.end(); + running + } + + /// The configured pause between iterations, open to commands; false once + /// the worker should stop. + pub(super) fn wait_iteration_interval(&mut self) -> bool { + if self.iteration_interval.is_zero() { + return true; + } + self.wait_for_scheduler_command("stage.scheduler_interval", self.iteration_interval) + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs index c041c135e8..f6d7dc270a 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs @@ -32,6 +32,8 @@ pub(super) fn direct_coalesce_target( #[cfg(test)] mod coalescing_tests; +#[cfg(test)] +mod selection_tests; /// Environment switch: split each coalesced decode wave into this many /// pipeline groups, so a pipelined split keeps more than one batch in flight @@ -132,6 +134,10 @@ pub(super) fn take_direct_iteration_batch( } deferred.append(queue); *queue = deferred; + // Selection stays FIFO and budget-driven. Only order the selected, distinct + // sessions for native execution so arrival timing cannot permute graph rows + // between otherwise identical waves. Each request keeps its own reply. + batch.sort_unstable_by(|left, right| left.session_id.cmp(&right.session_id)); batch } diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/selection_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/selection_tests.rs new file mode 100644 index 0000000000..e0111c9617 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/selection_tests.rs @@ -0,0 +1,182 @@ +use super::super::tests::direct_iteration; +use super::*; + +#[test] +fn selected_sessions_have_the_same_order_for_every_arrival_permutation() { + for arrival in [ + ["a", "b", "c"], + ["a", "c", "b"], + ["b", "a", "c"], + ["b", "c", "a"], + ["c", "a", "b"], + ["c", "b", "a"], + ] { + let mut queue = arrival.map(|session| direct_iteration(session, 1)).into(); + + let batch = take_direct_iteration_batch(&mut queue, 3, 3); + + assert_eq!(session_ids(&batch), ["a", "b", "c"]); + assert!(queue.is_empty()); + } +} + +#[test] +fn canonical_execution_order_does_not_change_fifo_admission_at_the_batch_cap() { + let mut queue = VecDeque::from([ + direct_iteration("z-oldest", 1), + direct_iteration("b-next", 1), + direct_iteration("a-later", 1), + ]); + + let batch = take_direct_iteration_batch(&mut queue, 2, 8); + + assert_eq!(session_ids(&batch), ["b-next", "z-oldest"]); + assert_eq!(queue.pop_front().unwrap().session_id, "a-later"); + assert!(queue.is_empty()); +} + +#[test] +fn canonical_execution_preserves_budget_and_deferred_session_fifo_across_waves() { + let mut queue = VecDeque::from([ + direct_iteration("z", 2), + direct_iteration("b", 4), + direct_iteration("z", 1), + direct_iteration("a", 1), + direct_iteration("c", 1), + ]); + + let first = take_direct_iteration_batch(&mut queue, 3, 3); + + assert_eq!(session_ids(&first), ["a", "z"]); + assert_eq!(first.iter().map(|r| r.token_ids.len()).sum::(), 3); + assert_eq!( + queue + .iter() + .map(|r| (r.session_id.as_str(), r.token_ids.len())) + .collect::>(), + [("b", 4), ("z", 1), ("c", 1)] + ); + let second = take_direct_iteration_batch(&mut queue, 3, 4); + assert_eq!(session_ids(&second), ["b"]); + let third = take_direct_iteration_batch(&mut queue, 3, 4); + assert_eq!(session_ids(&third), ["c", "z"]); + assert!(queue.is_empty()); +} + +fn session_ids(batch: &[DirectIteration]) -> Vec<&str> { + batch + .iter() + .map(|request| request.session_id.as_str()) + .collect() +} + +#[test] +fn direct_iteration_batch_defers_duplicate_sessions() { + let mut queue = VecDeque::from([ + direct_iteration("same", 1), + direct_iteration("same", 1), + direct_iteration("other", 1), + ]); + + let batch = take_direct_iteration_batch(&mut queue, 3, 8); + + assert_eq!( + batch + .iter() + .map(|request| request.session_id.as_str()) + .collect::>(), + ["other", "same"] + ); + assert_eq!(queue.len(), 1); + assert_eq!(queue.front().unwrap().session_id, "same"); +} + +#[test] +fn direct_prefill_wave_never_exceeds_configured_native_batch_tokens() { + let mut queue = (0..8) + .map(|index| direct_iteration(&format!("session-{index}"), 128)) + .collect::>(); + + let batch = take_direct_iteration_batch(&mut queue, 8, 512); + + assert_eq!(batch.len(), 4); + assert_eq!( + batch + .iter() + .map(|request| request.token_ids.len()) + .sum::(), + 512 + ); + assert_eq!(queue.len(), 4); +} + +#[test] +fn direct_wave_packs_decode_rows_queued_behind_an_oversized_prefill_chunk() { + let mut queue = VecDeque::from([ + direct_iteration("prefill-a", 384), + direct_iteration("prefill-b", 256), + direct_iteration("decode-a", 1), + direct_iteration("decode-b", 1), + direct_iteration("late-arrival", 1), + ]); + + let batch = take_direct_iteration_batch(&mut queue, 4, 512); + + assert_eq!( + batch + .iter() + .map(|request| request.session_id.as_str()) + .collect::>(), + ["decode-a", "decode-b", "late-arrival", "prefill-a"] + ); + assert_eq!(queue.len(), 1); + assert_eq!(queue.front().unwrap().session_id, "prefill-b"); +} + +#[test] +fn deferred_prefill_chunk_stays_ahead_of_requests_it_did_not_reach() { + let mut queue = VecDeque::from([ + direct_iteration("prefill-a", 384), + direct_iteration("prefill-b", 256), + direct_iteration("decode-a", 1), + direct_iteration("decode-b", 1), + ]); + + let batch = take_direct_iteration_batch(&mut queue, 2, 512); + + assert_eq!(batch.len(), 2); + assert_eq!( + queue + .iter() + .map(|request| request.session_id.as_str()) + .collect::>(), + ["prefill-b", "decode-b"] + ); +} + +#[test] +fn deferred_prefill_chunk_is_not_overtaken_by_its_own_session() { + let mut queue = VecDeque::from([ + direct_iteration("prefill-a", 384), + direct_iteration("same", 256), + direct_iteration("same", 1), + direct_iteration("decode-a", 1), + ]); + + let batch = take_direct_iteration_batch(&mut queue, 4, 512); + + assert_eq!( + batch + .iter() + .map(|request| request.session_id.as_str()) + .collect::>(), + ["decode-a", "prefill-a"] + ); + assert_eq!( + queue + .iter() + .map(|request| request.token_ids.len()) + .collect::>(), + [256, 1] + ); +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs index aa64de5abf..6b189b4eca 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs @@ -1,14 +1,19 @@ //! Execute admitted direct iterations under one native runtime lease. +use super::step_telemetry::{insert_kv_used_cells, sample_kv_used_cells}; use super::*; use skippy_runtime::IterationBatchOutput; +#[cfg(test)] +mod ordered_reply_tests; + type Runnable = (DirectIteration, Option); struct BatchTiming { wait: Vec, lock_wait_ms: f64, lock_hold_ms: f64, + kv_used_cells: Option, } impl SchedulerWorker { @@ -24,12 +29,29 @@ impl SchedulerWorker { if active.is_empty() { return; } + // The lease span covers lock request through release; native calls + // made under it nest beneath it. + let span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_feature_iteration", + SpanLevel::Debug, + ); + let entered = span.enter(); let lock_started = Instant::now(); - let mut runtime = lock_runtime(&self.runtime); + let mut runtime = self.lock_runtime_traced(); let lock_wait_ms = lock_started.elapsed().as_secs_f64() * 1_000.0; let hold_started = Instant::now(); + let align_span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_align", + SpanLevel::Debug, + ); let runnable = align_requests(&mut runtime, active); + align_span.end(); if runnable.is_empty() { + drop(entered); + // Its lock wait and alignment were exported beneath it. + span.end(); return; } let requests = runnable @@ -63,59 +85,86 @@ impl SchedulerWorker { .iteration_batch_scored(&requests, &selections) .map_err(openai_backend_error); let hold = hold_started.elapsed(); + let kv_used_cells = runnable.first().and_then(|(request, _)| { + sample_kv_used_cells(self.telemetry.as_ref(), &mut runtime, &request.session_id) + }); drop(runtime); + drop(entered); self.record_compute(hold); let timing = BatchTiming { wait, lock_wait_ms, lock_hold_ms: hold.as_secs_f64() * 1_000.0, + kv_used_cells, }; - self.record_direct_batch(&runnable, &timing); + self.record_direct_batch(&runnable, &timing, span); + let reply_span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_reply", + SpanLevel::Debug, + ); match result { Ok((output, scores)) => send_outputs(runnable, output, scores, timing), Err(error) => fail_requests(runnable, error), } + reply_span.end(); } - /// Record execution and timing evidence for one native direct batch. - fn record_direct_batch(&self, requests: &[Runnable], timing: &BatchTiming) { + /// Record execution and timing evidence for one native direct batch, and + /// end its lease span linked to every request it served. + fn record_direct_batch( + &self, + requests: &[Runnable], + timing: &BatchTiming, + mut span: ActiveSpan, + ) { let decode_steps = requests .iter() .filter(|(request, _)| request.phase == IterationBatchPhase::Decode) .count(); self.compute_meter.record_decode_tokens(decode_steps as u64); - if let Some(telemetry) = self.telemetry.as_ref() { - telemetry.emit_debug( - "stage.scheduler_feature_iteration", - BTreeMap::from([ - ( - "skippy.scheduler.batch_size".to_string(), - json!(requests.len()), - ), - ( - "skippy.scheduler.token_count".to_string(), - json!( - requests - .iter() - .map(|(r, _)| r.token_ids.len()) - .sum::() - ), - ), - ( - "skippy.scheduler.batch_wait_max_ms".to_string(), - json!(timing.wait.iter().copied().fold(0.0_f64, f64::max)), - ), - ( - "skippy.scheduler.runtime_lock_wait_ms".to_string(), - json!(timing.lock_wait_ms), - ), - ( - "skippy.scheduler.runtime_lock_hold_ms".to_string(), - json!(timing.lock_hold_ms), + resource_metrics::record_decode_tokens(decode_steps as u64); + resource_metrics::record_scheduler( + self.active_runtime_sessions, + self.direct_iterations.len(), + requests.len(), + ); + if self.telemetry.is_some() { + let mut attrs = BTreeMap::from([ + ( + "skippy.scheduler.batch_size".to_string(), + json!(requests.len()), + ), + ( + "skippy.scheduler.token_count".to_string(), + json!( + requests + .iter() + .map(|(r, _)| r.token_ids.len()) + .sum::() ), - ]), - ); + ), + ( + "skippy.scheduler.batch_wait_max_ms".to_string(), + json!(timing.wait.iter().copied().fold(0.0_f64, f64::max)), + ), + ( + "skippy.scheduler.runtime_lock_wait_ms".to_string(), + json!(timing.lock_wait_ms), + ), + ( + "skippy.scheduler.runtime_lock_hold_ms".to_string(), + json!(timing.lock_hold_ms), + ), + ]); + insert_kv_used_cells(&mut attrs, timing.kv_used_cells); + requests + .iter() + .filter_map(|(request, _)| trace_context::sequence_context(&request.session_id)) + .for_each(|context| span.link(context)); + span.extend_attributes(attrs); } + span.end(); } } diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution/ordered_reply_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution/ordered_reply_tests.rs new file mode 100644 index 0000000000..1ec9b57da2 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution/ordered_reply_tests.rs @@ -0,0 +1,97 @@ +use super::super::tests::direct_iteration; +use super::*; +use skippy_runtime::{ActivationDesc, IterationSample}; + +#[test] +fn canonical_batch_order_keeps_inputs_and_native_outputs_with_their_reply_owners() { + let mut queue = VecDeque::new(); + let mut replies = Vec::new(); + for (session, marker) in [("c", 3), ("a", 1), ("b", 2)] { + let (reply, result) = std_mpsc::sync_channel(1); + let mut request = direct_iteration(session, 1); + request.token_ids = vec![marker]; + request.positions = vec![marker + 10]; + request.selected_tokens = Some(vec![marker + 100]); + request.input = Some(frame(u8::try_from(marker).unwrap())); + request.reply = reply.into(); + queue.push_back(request); + replies.push((marker, result)); + } + + let batch = take_direct_iteration_batch(&mut queue, 3, 3); + assert_eq!( + batch + .iter() + .map(|r| r.session_id.as_str()) + .collect::>(), + ["a", "b", "c"] + ); + for (request, marker) in batch.iter().zip(1..=3) { + assert_eq!(request.token_ids, [marker]); + assert_eq!(request.positions, [marker + 10]); + assert_eq!( + request.selected_tokens.as_deref(), + Some([marker + 100].as_slice()) + ); + assert_eq!( + request.input.as_ref().unwrap().payload, + [u8::try_from(marker).unwrap()] + ); + } + let output = IterationBatchOutput { + request_outputs: batch.iter().map(|r| r.input.clone().unwrap()).collect(), + // Native samples need not arrive in request order. + samples: vec![sample(2, 3), sample(0, 1), sample(1, 2)], + }; + let timing = BatchTiming { + wait: vec![1.0, 2.0, 3.0], + lock_wait_ms: 4.0, + lock_hold_ms: 5.0, + kv_used_cells: None, + }; + send_outputs( + batch.into_iter().map(|r| (r, None)).collect(), + output, + vec![vec![1.0], vec![2.0], vec![3.0]], + timing, + ); + + for (marker, result) in replies { + let outcome = result.try_recv().unwrap().unwrap(); + assert_eq!(outcome.predicted, marker); + assert_eq!(outcome.output.payload, [u8::try_from(marker).unwrap()]); + assert_eq!( + outcome.log_probabilities, + [f32::from(u8::try_from(marker).unwrap())] + ); + assert_eq!(outcome.batch_wait_ms, f64::from(marker)); + assert_eq!(outcome.batch_size, 3); + assert_eq!(outcome.runtime_lock_wait_ms, 4.0); + assert_eq!(outcome.runtime_lock_hold_ms, 5.0); + } +} + +fn sample(request_index: usize, predicted_token: i32) -> IterationSample { + IterationSample { + request_index, + predicted_token, + } +} + +fn frame(marker: u8) -> ActivationFrame { + ActivationFrame { + desc: ActivationDesc { + version: 0, + producer_stage_index: 0, + layer_start: 0, + layer_end: 0, + token_count: 1, + sequence_count: 1, + part_count: 0, + payload_bytes: 1, + frontier_identity: Default::default(), + parts: Default::default(), + }, + payload: vec![marker], + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs new file mode 100644 index 0000000000..88eb523ea5 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs @@ -0,0 +1,261 @@ +//! Debug telemetry for executed scheduler iterations: one span per step, with +//! the shared KV pool occupancy observed under its lease and links to the +//! requests it served. + +use super::*; +use crate::telemetry::trace_context::SpanContext; +use serde_json::Value; + +const KV_USED_CELLS: &str = "skippy.kv.used_cells"; + +/// The span and evidence for one executed planned iteration. +pub(super) struct StepTiming { + pub(super) span: ActiveSpan, + pub(super) execution_elapsed: Duration, + pub(super) kv_used_cells: Option, + pub(super) links: Vec, +} + +impl SchedulerWorker { + pub(super) fn emit_step_telemetry( + &mut self, + step: &skippy_scheduler::IterationTelemetry, + timing: StepTiming, + ) { + let StepTiming { + mut span, + execution_elapsed, + kv_used_cells, + links, + } = timing; + if self.telemetry.is_none() { + return; + } + let elapsed = span.elapsed(); + let lifecycle_counters = ( + step.finished, + step.failed, + step.cancelled, + step.rejected_overload, + ); + let lifecycle_changed = lifecycle_counters != self.last_emitted_lifecycle_counters; + if lifecycle_changed { + self.last_emitted_lifecycle_counters = lifecycle_counters; + } + let mut attrs = BTreeMap::from([ + ( + "skippy.scheduler.iteration".to_string(), + json!(step.iteration), + ), + ( + "skippy.scheduler.running".to_string(), + json!(step.active_sequences), + ), + ( + "skippy.scheduler.waiting".to_string(), + json!(step.waiting_sequences), + ), + ( + "skippy.scheduler.admitted".to_string(), + json!(step.admitted), + ), + ( + "skippy.scheduler.preempted".to_string(), + json!(step.preempted), + ), + ( + "skippy.scheduler.prefill_tokens".to_string(), + json!(step.prefill_tokens), + ), + ( + "skippy.scheduler.recompute_tokens".to_string(), + json!(step.recompute_tokens), + ), + ( + "skippy.scheduler.decode_tokens".to_string(), + json!(step.decode_tokens), + ), + ( + "skippy.scheduler.prefix_hits".to_string(), + json!(step.prefix_hits), + ), + ( + "skippy.scheduler.prefix_misses".to_string(), + json!(step.prefix_misses), + ), + ( + "skippy.scheduler.step_ms".to_string(), + json!(elapsed.as_secs_f64() * 1_000.0), + ), + ( + "skippy.scheduler.execution_ms".to_string(), + json!(execution_elapsed.as_secs_f64() * 1_000.0), + ), + ( + "skippy.scheduler.overhead_ms".to_string(), + json!(elapsed.saturating_sub(execution_elapsed).as_secs_f64() * 1_000.0), + ), + ]); + if lifecycle_changed { + attrs.extend([ + ( + "skippy.scheduler.finished".to_string(), + json!(step.finished), + ), + ("skippy.scheduler.failed".to_string(), json!(step.failed)), + ( + "skippy.scheduler.cancelled".to_string(), + json!(step.cancelled), + ), + ( + "skippy.scheduler.rejected_overload".to_string(), + json!(step.rejected_overload), + ), + ]); + } + for (name, used) in &step.component_used_bytes { + attrs.insert( + format!("skippy.scheduler.component.{name}.used_bytes"), + json!(used), + ); + } + for (name, available) in &step.component_available_bytes { + attrs.insert( + format!("skippy.scheduler.component.{name}.available_bytes"), + json!(available), + ); + let used = step + .component_used_bytes + .iter() + .find_map(|(used_name, used)| (used_name == name).then_some(*used)) + .unwrap_or(0); + attrs.insert( + format!("skippy.scheduler.component.{name}.free_bytes"), + json!(available.saturating_sub(used)), + ); + } + insert_kv_used_cells(&mut attrs, kv_used_cells); + links.into_iter().for_each(|context| span.link(context)); + span.extend_attributes(attrs); + span.end(); + } +} + +/// Attention cells in use across the shared KV pool, read under the caller's +/// runtime lease only when debug telemetry will record it. +pub(super) fn sample_kv_used_cells( + telemetry: Option<&Telemetry>, + runtime: &mut RuntimeState, + session_id: &str, +) -> Option { + if !telemetry.is_some_and(Telemetry::is_debug_enabled) { + return None; + } + crate::telemetry::resource_metrics::kv_tiers::record_kv_pool_cells(u64::from( + runtime.kv_pool_tokens(), + )); + runtime.memory_used_cells(session_id).ok() +} + +pub(super) fn insert_kv_used_cells(attrs: &mut BTreeMap, used: Option) { + if let Some(used) = used { + crate::telemetry::resource_metrics::record_kv_used_cells(used); + attrs.insert(KV_USED_CELLS.to_string(), json!(used)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::telemetry::TelemetryLevel; + + fn stage_config() -> StageConfig { + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + })) + .expect("minimal stage config") + } + + fn worker_with(telemetry: Telemetry) -> SchedulerWorker { + let (_commands, receiver) = std_mpsc::channel(); + SchedulerWorker { + compute_meter: Arc::default(), + runtime: Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(1))), + scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), + requests: BTreeMap::new(), + direct_iterations: VecDeque::new(), + cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), + commands: receiver, + kv_capacity_tokens: 64, + max_direct_batch_size: 1, + direct_group_batch_size: 1, + max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, + max_commands_per_turn: 8, + iteration_interval: Duration::ZERO, + active_runtime_sessions: 0, + cache_wave_sessions: 0, + direct_wave_full: false, + telemetry: Some(telemetry), + last_served_direct: false, + last_served_cache_runtime: false, + last_emitted_lifecycle_counters: (0, 0, 0, 0), + } + } + + #[test] + fn planned_iteration_is_a_span_over_the_whole_step() { + let (telemetry, rx) = Telemetry::captured(stage_config(), TelemetryLevel::Debug); + let mut worker = worker_with(telemetry); + let span = ActiveSpan::start( + worker.telemetry.as_ref(), + "stage.scheduler_iteration", + SpanLevel::Debug, + ); + thread::sleep(Duration::from_millis(2)); + + worker.emit_step_telemetry( + &skippy_scheduler::IterationTelemetry::default(), + StepTiming { + span, + execution_elapsed: Duration::from_millis(1), + kv_used_cells: Some(512), + links: Vec::new(), + }, + ); + + let event = rx.try_recv().expect("iteration span captured"); + assert_eq!(event.event, "stage.scheduler_iteration"); + assert!(event.end_time_unix_nanos - event.start_time_unix_nanos >= 2_000_000); + assert_eq!(event.attributes["skippy.kv.used_cells"], json!(512)); + } + + #[test] + fn idle_iterations_are_not_exported() { + let (telemetry, rx) = Telemetry::captured(stage_config(), TelemetryLevel::Debug); + ActiveSpan::start( + Some(&telemetry), + "stage.scheduler_iteration", + SpanLevel::Debug, + ) + .discard(); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn kv_used_cells_is_recorded_only_when_observed() { + let mut attrs = BTreeMap::new(); + insert_kv_used_cells(&mut attrs, None); + assert!(attrs.is_empty()); + insert_kv_used_cells(&mut attrs, Some(23_499)); + assert_eq!(attrs["skippy.kv.used_cells"], json!(23_499)); + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index 62d0ebef08..e73a512950 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -361,117 +361,6 @@ fn feature_driver_iterations_enforce_the_native_batch_shape() { ); } -#[test] -fn direct_iteration_batch_defers_duplicate_sessions() { - let mut queue = VecDeque::from([ - direct_iteration("same", 1), - direct_iteration("same", 1), - direct_iteration("other", 1), - ]); - - let batch = take_direct_iteration_batch(&mut queue, 3, 8); - - assert_eq!( - batch - .iter() - .map(|request| request.session_id.as_str()) - .collect::>(), - ["same", "other"] - ); - assert_eq!(queue.len(), 1); - assert_eq!(queue.front().unwrap().session_id, "same"); -} - -#[test] -fn direct_prefill_wave_never_exceeds_configured_native_batch_tokens() { - let mut queue = (0..8) - .map(|index| direct_iteration(&format!("session-{index}"), 128)) - .collect::>(); - - let batch = take_direct_iteration_batch(&mut queue, 8, 512); - - assert_eq!(batch.len(), 4); - assert_eq!( - batch - .iter() - .map(|request| request.token_ids.len()) - .sum::(), - 512 - ); - assert_eq!(queue.len(), 4); -} - -#[test] -fn direct_wave_packs_decode_rows_queued_behind_an_oversized_prefill_chunk() { - let mut queue = VecDeque::from([ - direct_iteration("prefill-a", 384), - direct_iteration("prefill-b", 256), - direct_iteration("decode-a", 1), - direct_iteration("decode-b", 1), - direct_iteration("late-arrival", 1), - ]); - - let batch = take_direct_iteration_batch(&mut queue, 4, 512); - - assert_eq!( - batch - .iter() - .map(|request| request.session_id.as_str()) - .collect::>(), - ["prefill-a", "decode-a", "decode-b", "late-arrival"] - ); - assert_eq!(queue.len(), 1); - assert_eq!(queue.front().unwrap().session_id, "prefill-b"); -} - -#[test] -fn deferred_prefill_chunk_stays_ahead_of_requests_it_did_not_reach() { - let mut queue = VecDeque::from([ - direct_iteration("prefill-a", 384), - direct_iteration("prefill-b", 256), - direct_iteration("decode-a", 1), - direct_iteration("decode-b", 1), - ]); - - let batch = take_direct_iteration_batch(&mut queue, 2, 512); - - assert_eq!(batch.len(), 2); - assert_eq!( - queue - .iter() - .map(|request| request.session_id.as_str()) - .collect::>(), - ["prefill-b", "decode-b"] - ); -} - -#[test] -fn deferred_prefill_chunk_is_not_overtaken_by_its_own_session() { - let mut queue = VecDeque::from([ - direct_iteration("prefill-a", 384), - direct_iteration("same", 256), - direct_iteration("same", 1), - direct_iteration("decode-a", 1), - ]); - - let batch = take_direct_iteration_batch(&mut queue, 4, 512); - - assert_eq!( - batch - .iter() - .map(|request| request.session_id.as_str()) - .collect::>(), - ["prefill-a", "decode-a"] - ); - assert_eq!( - queue - .iter() - .map(|request| request.token_ids.len()) - .collect::>(), - [256, 1] - ); -} - #[test] fn token_control_is_applied_without_blocking_the_scheduler_iteration() { let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(1))); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs index c65fc0ce14..5a50482a92 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs @@ -467,6 +467,7 @@ mod tests { let request = LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 5, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index b8fe337fc6..f8fc605b59 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -299,6 +299,7 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &first_prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 2, sampling: &sampling, chat_sampling_metadata: None, @@ -360,6 +361,7 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &second_prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -737,6 +739,7 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -792,6 +795,7 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs index d617ede612..0f4f69a59f 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs @@ -56,6 +56,7 @@ fn prefill_only_resident_recurrent_request_retains_shared_grid_checkpoint() -> R LocalGeneration { prompt_token_ids: &tokens, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 0, sampling: &sampling, chat_sampling_metadata: None, @@ -136,6 +137,7 @@ fn resident_checkpoint_prefill_yields_to_decode_and_cancels_without_losing_check LocalGeneration { prompt_token_ids: &worker_prompt, recurrent_cache_prefix_token_ids: Some(&worker_prompt[..64]), + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index a4a62de004..4e6a73fd70 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -159,6 +159,7 @@ fn failed_long_l3_import_rolls_back_then_reuses_the_short_native_owner() -> Resu LocalGeneration { prompt_token_ids: &prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index d0856ee9e2..c4b988ca31 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -1,4 +1,5 @@ use super::*; +use crate::kv_integration::{ResidentPrefixRecord, ResidentRecordOutcome, ResidentRecordSkip}; /// Owns one unit of the test-only outstanding-capture counter for a single /// detached capture task. Construction increments the counter, so the unit is @@ -231,25 +232,14 @@ impl StageOpenAiBackend { let base = self.local_kv_message_base(session_id, ids); let identity = kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens); if kv.records_resident_prefixes() { - let recorded = match kv.record_resident_prefix( + let recorded = self.record_resident_checkpoint( runtime, session_id, + ids, &identity, checkpoint_tokens, - ) { - Ok(record) => record.is_some(), - Err(error) => { - let mut attrs = self.openai_attrs(ids); - attrs.insert( - "skippy.kv.decision".to_string(), - json!(format!("{decision_prefix}_error")), - ); - attrs.insert("skippy.kv.error".to_string(), json!(format!("{error:#}"))); - self.telemetry - .emit("stage.openai_kv_record_decision", attrs); - false - } - }; + decision_prefix, + ); #[cfg(test)] { if recorded && decision_prefix == "post_decode_checkpoint" { @@ -370,6 +360,110 @@ impl StageOpenAiBackend { } } } + + /// Keep a resident checkpoint and report whether it was kept, and why not. + fn record_resident_checkpoint( + &self, + runtime: &mut RuntimeState, + session_id: &str, + ids: &InferenceGenerationIds, + identity: &PrefillKvIdentity, + checkpoint_tokens: &[i32], + decision_prefix: &str, + ) -> bool { + let Some(kv) = self.kv.as_ref() else { + return false; + }; + let outcome = + kv.record_resident_prefix_outcome(runtime, session_id, identity, checkpoint_tokens); + let mut attrs = self.openai_attrs(ids); + attrs.insert( + "skippy.kv.checkpoint_token_count".to_string(), + json!(checkpoint_tokens.len()), + ); + let decision = match &outcome { + Ok(ResidentRecordOutcome::Recorded(record)) => { + insert_resident_record_attrs(&mut attrs, record); + if record.stored { + "recorded" + } else { + "already_cached" + } + } + Ok(ResidentRecordOutcome::Skipped(skip)) => { + insert_resident_skip_attrs(&mut attrs, *skip); + "skipped" + } + Err(error) => { + attrs.insert( + "skippy.kv.error_class".to_string(), + json!(crate::kv_integration::telemetry_error_class(error)), + ); + "error" + } + }; + attrs.insert( + "skippy.kv.decision".to_string(), + json!(format!("{decision_prefix}_{decision}")), + ); + self.telemetry + .emit("stage.openai_kv_record_decision", attrs); + matches!(outcome, Ok(ResidentRecordOutcome::Recorded(_))) + } +} + +fn insert_resident_record_attrs( + attrs: &mut BTreeMap, + record: &ResidentPrefixRecord, +) { + attrs.insert( + "skippy.kv.resident_entries".to_string(), + json!(record.entries), + ); + attrs.insert( + "skippy.kv.resident_tokens".to_string(), + json!(record.resident_tokens), + ); + attrs.insert( + "skippy.kv.evicted_entries".to_string(), + json!(record.evicted_entries), + ); + attrs.insert( + "skippy.kv.evicted_tokens".to_string(), + json!(record.evicted_tokens), + ); +} + +fn insert_resident_skip_attrs( + attrs: &mut BTreeMap, + skip: ResidentRecordSkip, +) { + attrs.insert("skippy.kv.skip_reason".to_string(), json!(skip.reason())); + match skip { + ResidentRecordSkip::RecordingOff => {} + ResidentRecordSkip::PositionMismatch { session_tokens } => { + attrs.insert( + "skippy.kv.runtime_token_count".to_string(), + json!(session_tokens), + ); + } + ResidentRecordSkip::BelowMinTokens { min_tokens } => { + attrs.insert("skippy.kv.min_tokens".to_string(), json!(min_tokens)); + } + ResidentRecordSkip::OverCheckpointBudget { + bytes, + budget_bytes, + } => { + attrs.insert("skippy.kv.checkpoint_bytes".to_string(), json!(bytes)); + attrs.insert( + "skippy.kv.checkpoint_budget_bytes".to_string(), + json!(budget_bytes), + ); + } + ResidentRecordSkip::NoRoom { bytes } => { + attrs.insert("skippy.kv.checkpoint_bytes".to_string(), json!(bytes)); + } + } } #[cfg(test)] diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs index 769b028cf2..cf547833d6 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs @@ -1,4 +1,5 @@ use super::*; +use crate::kv_integration::{KvLifecycleEvent, ResidentMissDiagnosis, ResidentMissReason}; impl StageOpenAiBackend { #[allow(clippy::too_many_arguments)] @@ -153,12 +154,21 @@ impl StageOpenAiBackend { ); self.telemetry .emit("stage.openai_kv_lookup_decision", attrs); + kv.notify_kv_lifecycle(KvLifecycleEvent::CacheLookupHit { + matched_tokens: restored.token_count, + resident_entries: restored.entries, + }); } Ok(None) => { + let miss = kv.diagnose_resident_miss(prepared.identities()); let mut attrs = self.openai_attrs(ids); attrs.insert("skippy.kv.decision".to_string(), json!("miss")); + insert_resident_miss_attrs(&mut attrs, prefill_tokens.len(), miss); self.telemetry .emit("stage.openai_kv_lookup_decision", attrs); + if miss.reason != ResidentMissReason::LookupOff { + kv.notify_kv_lifecycle(KvLifecycleEvent::CacheLookupMiss); + } } Err(error) => { let mut attrs = self.openai_attrs(ids); @@ -370,3 +380,31 @@ impl StageOpenAiBackend { .emit("stage.openai_kv_lookup_decision", attrs); } } + +fn insert_resident_miss_attrs( + attrs: &mut BTreeMap, + prompt_tokens: usize, + miss: ResidentMissDiagnosis, +) { + attrs.insert( + "skippy.kv.miss_reason".to_string(), + json!(miss.reason.as_str()), + ); + attrs.insert("skippy.kv.prompt_tokens".to_string(), json!(prompt_tokens)); + attrs.insert( + "skippy.kv.resident_entries".to_string(), + json!(miss.resident_entries), + ); + attrs.insert( + "skippy.kv.shared_prefix_tokens".to_string(), + json!(miss.shared_prefix_tokens), + ); + attrs.insert( + "skippy.kv.stored_prefix_tokens".to_string(), + json!(miss.stored_prefix_tokens), + ); + attrs.insert( + "skippy.kv.checkpoint_prefix_tokens".to_string(), + json!(miss.checkpoint_prefix_tokens), + ); +} diff --git a/skippy/crates/skippy-serving/src/frontend/speculative.rs b/skippy/crates/skippy-serving/src/frontend/speculative.rs index 55f5cd86b9..ae6f3915ba 100644 --- a/skippy/crates/skippy-serving/src/frontend/speculative.rs +++ b/skippy/crates/skippy-serving/src/frontend/speculative.rs @@ -11,6 +11,7 @@ use std::time::Instant; use crate::frontend::util::openai_backend_error; mod dflash; +mod recurrent_rollback; mod standalone; mod suffix; diff --git a/skippy/crates/skippy-serving/src/frontend/speculative/recurrent_rollback.rs b/skippy/crates/skippy-serving/src/frontend/speculative/recurrent_rollback.rs new file mode 100644 index 0000000000..fd7a83e4c7 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/speculative/recurrent_rollback.rs @@ -0,0 +1,148 @@ +use super::SpeculativeDecodeConfig; + +impl SpeculativeDecodeConfig { + /// Native recurrent snapshots needed by the enabled verification routes. + /// + /// `native_mtp_max_tokens` also covers callers using the legacy MTP options; + /// `draft_window` describes the embedded serial draft-model route and is + /// present only when that proposal model is attached. Dynamic local hook + /// proposals have no pre-open width contract and use checkpoint fallback. + /// Zero disables snapshots for ordinary decoding. This is a per-window bound, + /// not retention for every in-flight window: native limits and older pipeline + /// checkpoints continue to use the existing checkpoint/replay fallback. + pub fn recurrent_rollback_tokens( + &self, + native_mtp_max_tokens: Option, + draft_window: Option, + ) -> u32 { + let mut depth = self + .dflash + .as_ref() + .map_or(0, super::DFlashProposalConfig::recurrent_rollback_tokens); + let mtp_tokens = native_mtp_max_tokens + .into_iter() + .chain( + self.native_mtp + .enabled + .then_some(self.native_mtp.max_draft_tokens), + ) + .max(); + if let Some(tokens) = mtp_tokens { + // Local MTP verifies current + all drafts. Embedded MTP can take + // the configured verify width, also with an initial anchor. + depth = depth.max(with_anchor(tokens.max(self.verify_width()))); + } + if let Some(ngram) = &self.ngram { + let pipelined = self.verify_window.pipeline_depth > 1 + || self.verify_window.runahead_max_tokens > 0 + || self.verify_window.runahead_auto; + let tokens = if pipelined || self.extension.is_some() { + // An epoch's first pipelined/composite window has an anchor; + // continuation windows can be shorter. + with_anchor(self.verify_width()) + } else { + // Classic serial verification replaces the final proposal + // with current, so its input length is the proposal length. + bounded_depth(ngram.max_proposal_tokens.max(1)) + }; + depth = depth.max(tokens); + } + if let Some(window) = draft_window { + depth = depth.max(bounded_depth(window.max(1))); + } + depth + } + + fn verify_width(&self) -> usize { + self.verify_window + .max_tokens + .max(self.verify_window.min_tokens) + .max(1) + } +} + +fn with_anchor(tokens: usize) -> u32 { + bounded_depth(tokens.saturating_add(1)) +} + +fn bounded_depth(tokens: usize) -> u32 { + u32::try_from(tokens).unwrap_or(u32::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::frontend::speculative::{ + NgramExtensionConfig, NgramProposalConfig, NgramProposerKind, + }; + + fn ngram() -> SpeculativeDecodeConfig { + SpeculativeDecodeConfig { + ngram: Some(NgramProposalConfig { + kind: NgramProposerKind::Cache, + min_ngram: 2, + max_ngram: 4, + max_proposal_tokens: 7, + }), + ..SpeculativeDecodeConfig::default() + } + } + + #[test] + fn ordinary_decode_does_not_enable_default_verify_window() { + let plan = SpeculativeDecodeConfig::default(); + assert_eq!(plan.verify_window.max_tokens, 4); + assert_eq!(plan.recurrent_rollback_tokens(None, None), 0); + } + + #[test] + fn mtp_local_and_embedded_routes_include_one_anchor() { + let mut plan = SpeculativeDecodeConfig::default(); + plan.native_mtp.enabled = true; + plan.native_mtp.max_draft_tokens = 7; + assert_eq!(plan.recurrent_rollback_tokens(None, None), 8); + plan.verify_window.max_tokens = 12; + assert_eq!(plan.recurrent_rollback_tokens(None, None), 13); + plan.native_mtp.enabled = false; + assert_eq!(plan.recurrent_rollback_tokens(Some(20), None), 21); + } + + #[test] + fn classic_ngram_and_draft_have_no_extra_anchor() { + assert_eq!(ngram().recurrent_rollback_tokens(None, None), 7); + assert_eq!(ngram().recurrent_rollback_tokens(None, Some(11)), 11); + assert_eq!( + SpeculativeDecodeConfig::default().recurrent_rollback_tokens(None, Some(9)), + 9 + ); + } + + #[test] + fn composite_and_pipeline_epoch_start_include_one_anchor() { + let mut plan = ngram(); + plan.verify_window.max_tokens = 10; + plan.native_mtp.enabled = true; + plan.native_mtp.max_draft_tokens = 2; + plan.extension = Some(NgramExtensionConfig { max_tokens: 40 }); + plan.validate().unwrap(); + // The buffered composite can exceed one verify window; dispatch + // selects at most verify_width proposals before adding its anchor. + assert_eq!(plan.recurrent_rollback_tokens(None, None), 11); + plan.extension = None; + plan.native_mtp.enabled = false; + plan.verify_window.pipeline_depth = 2; + plan.ngram_fallback_draft = true; + assert_eq!(plan.recurrent_rollback_tokens(None, Some(7)), 11); + plan.verify_window.pipeline_depth = 1; + plan.verify_window.runahead_max_tokens = 20; + assert_eq!(plan.recurrent_rollback_tokens(None, None), 11); + } + + #[test] + fn oversized_windows_remain_explicit_for_native_fallback() { + let mut plan = ngram(); + plan.verify_window.pipeline_depth = 3; + plan.verify_window.max_tokens = 100; + assert_eq!(plan.recurrent_rollback_tokens(None, None), 101); + } +} diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs b/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs index 845312a234..d600bacd79 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/causal.rs @@ -73,29 +73,32 @@ impl StageOpenAiBackend { super::validate_request_fields(&request, &self.model_id)?; let decision = super::decision_request(&request)?; let scheduler = self.iteration_scheduler.clone(); - let plan = tokio::task::spawn_blocking(move || { - let reader = scheduler.execute_runtime("decision-plan", |runtime| { - Ok(runtime - .model - .supports_causal_readout() - .then(|| runtime.model.reader())) - })?; - let Some(reader) = reader else { - return Ok(None); - }; - // Vocabulary reads must not occupy the scheduler worker or runtime - // lock: a request may tokenize up to 64 prompts and 1,664 labels. - DecisionPlan::for_reader(&reader, &decision) - .map(Some) - .map_err(|error| InferenceError::invalid_request(error.to_string())) - }) - .await - .map_err(|error| openai_backend_error(error.into()))??; + let plan = + tokio::task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { + let reader = scheduler.execute_runtime("decision-plan", |runtime| { + Ok(runtime + .model + .supports_causal_readout() + .then(|| runtime.model.reader())) + })?; + let Some(reader) = reader else { + return Ok(None); + }; + // Vocabulary reads must not occupy the scheduler worker or runtime + // lock: a request may tokenize up to 64 prompts and 1,664 labels. + DecisionPlan::for_reader(&reader, &decision) + .map(Some) + .map_err(|error| InferenceError::invalid_request(error.to_string())) + })) + .await + .map_err(|error| openai_backend_error(error.into()))??; let Some(plan) = plan else { let backend = self.clone(); - return tokio::task::spawn_blocking(move || backend.run_system_one(request)) - .await - .map_err(|error| openai_backend_error(error.into()))?; + return tokio::task::spawn_blocking(crate::telemetry::trace_context::propagate( + move || backend.run_system_one(request), + )) + .await + .map_err(|error| openai_backend_error(error.into()))?; }; validate_context(&plan, self.ctx_size)?; let guard = CancelOnDrop(CancellationToken::new()); @@ -163,10 +166,10 @@ impl StageOpenAiBackend { .await?; let backend = self.clone(); let cancellation = cancellation.clone(); - tokio::task::spawn_blocking(move || { + tokio::task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { let _permit = permit; sequence::execute(&backend, &job, &ids, &cancellation) - }) + })) .await .map_err(|error| ReadoutFailure::from(openai_backend_error(error.into())))? } diff --git a/skippy/crates/skippy-serving/src/frontend/system_one/laya.rs b/skippy/crates/skippy-serving/src/frontend/system_one/laya.rs index 34cbc73ed2..da35f15aec 100644 --- a/skippy/crates/skippy-serving/src/frontend/system_one/laya.rs +++ b/skippy/crates/skippy-serving/src/frontend/system_one/laya.rs @@ -38,9 +38,9 @@ impl InferenceBackend for LayaSystemOneBackend { async fn system_one(&self, request: SystemOneRequest) -> InferenceResult { let backend = self.clone(); - task::spawn_blocking(move || { + task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { run_on_model(backend.model.as_ref(), &backend.model_id, request) - }) + })) .await .map_err(|error| { InferenceError::backend(format!("System One execution task failed: {error}")) diff --git a/skippy/crates/skippy-serving/src/frontend/token_counting.rs b/skippy/crates/skippy-serving/src/frontend/token_counting.rs index 4df3dd3860..286f9cbd54 100644 --- a/skippy/crates/skippy-serving/src/frontend/token_counting.rs +++ b/skippy/crates/skippy-serving/src/frontend/token_counting.rs @@ -26,11 +26,11 @@ impl StageOpenAiBackend { )); } let backend = self.clone(); - tokio::task::spawn_blocking(move || { + tokio::task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { let tokens = backend.tokenize(&prompt.text)?; u32::try_from(tokens.len()) .map_err(|_| InferenceError::internal("token count overflow")) - }) + })) .await .map_err(|error| InferenceError::backend(error.to_string()))? } diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index f747198f91..245db5f63d 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -352,7 +352,7 @@ impl KvStageIntegration { durable_spill_task, durable_spill_tx, )); - Ok(Some(Self { + let integration = Self { loaded_model_content, mode, payload, @@ -406,7 +406,9 @@ impl KvStageIntegration { inflight_fills, dense_without_recurrent, resident_checkpoint_max_bytes, - })) + }; + super::tier_metrics::register(&integration); + Ok(Some(integration)) } #[cfg(test)] diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs index 7d4fb9a32a..af1dcf1662 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -47,9 +47,15 @@ impl KvStageIntegration { }; // Corrupt/unavailable storage remains a cache miss. The // prepared None must never trigger a retry under runtime lock. - l3.locate_longest(&identity.namespace, tokens, MAX_PREFIX_PROBES) + let location = l3 + .locate_longest(&identity.namespace, tokens, MAX_PREFIX_PROBES) .ok() - .flatten() + .flatten(); + super::super::tier_metrics::record_lookup( + crate::telemetry::log_events::KvTier::L3, + location.as_ref().map(|location| location.token_count), + ); + location }) .collect(); PreparedExactStateRestore { diff --git a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs index b4f47d9d35..3bb264da91 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -9,6 +9,7 @@ use skippy_cache::{L2Hit, L2Origin, L2Stats, L2Tier, l2_cache_key}; use skippy_runtime::RuntimeKvPageDesc; use crate::runtime_state::RuntimeState; +use crate::telemetry::log_events::KvTier; use super::{ ExactStateExtra, ExactStateRecordAdmission, ExactStateRestore, KvStageIntegration, @@ -50,6 +51,10 @@ impl StageL2 { } } + pub(super) fn tier(&self) -> &Arc { + &self.tier + } + pub(crate) fn get( &self, identity: &PrefillKvIdentity, @@ -190,8 +195,10 @@ impl KvStageIntegration { return Ok(None); }; let Some((key, hit)) = l2.get(identity, location) else { + super::tier_metrics::record_lookup(KvTier::L2, None); return Ok(None); }; + super::tier_metrics::record_lookup(KvTier::L2, Some(hit.token_count)); let token_count = hit.token_count; if token_count == 0 || token_count != location.token_count { l2.remove(&key); diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 67cdb0bf57..901ccc9a99 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -38,14 +38,16 @@ mod output_tokens; mod record_worker; mod records; mod resident_offload; +mod tier_metrics; use record_worker::ExactStateRecordWorker; mod resident_prefix; pub use lifecycle::{KvLifecycleEvent, KvLifecycleObserver}; pub use records::{ AttachedPage, ExactStateRecord, ExactStateRestore, LookupBatchOutcome, PrefillKvIdentity, - RecordPageOutcome, ResidentActivationRecord, ResidentActivationRestore, ResidentPrefixRecord, - ResidentPrefixRestore, + RecordPageOutcome, ResidentActivationRecord, ResidentActivationRestore, ResidentMissDiagnosis, + ResidentMissReason, ResidentPrefixRecord, ResidentPrefixRestore, ResidentRecordOutcome, + ResidentRecordSkip, }; pub use resident_prefix::{ResidentCapacityDecision, ResidentPrefixEviction}; @@ -634,6 +636,7 @@ impl KvStageIntegration { } pub(crate) fn notify_kv_lifecycle(&self, event: KvLifecycleEvent) { + tier_metrics::record_lifecycle(event); if let Some(observer) = self.kv_lifecycle_observer.as_ref() { observer.observe(event); } diff --git a/skippy/crates/skippy-serving/src/kv_integration/records.rs b/skippy/crates/skippy-serving/src/kv_integration/records.rs index 8b8f113ed3..4354a05dd3 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/records.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/records.rs @@ -50,6 +50,146 @@ pub struct ResidentPrefixRecord { pub resident_tokens: u64, } +/// Why the resident cache kept no entry for a prefix. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResidentRecordSkip { + /// The cache does not record, or keeps no resident prefixes. + RecordingOff, + /// A recurrent checkpoint needs the session at its exact boundary. + PositionMismatch { + session_tokens: u64, + }, + BelowMinTokens { + min_tokens: u64, + }, + /// One checkpoint is larger than the whole checkpoint budget. + OverCheckpointBudget { + bytes: u64, + budget_bytes: u64, + }, + /// Nothing evictable would make room for the entry. + NoRoom { + bytes: u64, + }, +} + +impl ResidentRecordSkip { + pub fn reason(self) -> &'static str { + match self { + Self::RecordingOff => "recording_off", + Self::PositionMismatch { .. } => "position_mismatch", + Self::BelowMinTokens { .. } => "below_min_tokens", + Self::OverCheckpointBudget { .. } => "over_checkpoint_budget", + Self::NoRoom { .. } => "no_room", + } + } +} + +#[derive(Debug, Clone)] +pub enum ResidentRecordOutcome { + /// `stored` is false when an identical entry was already cached. + Recorded(ResidentPrefixRecord), + Skipped(ResidentRecordSkip), +} + +impl ResidentRecordOutcome { + pub fn into_record(self) -> Option { + match self { + Self::Recorded(record) => Some(record), + Self::Skipped(_) => None, + } + } +} + +/// Why a resident lookup restored nothing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResidentMissReason { + LookupOff, + EmptyCache, + /// No stored prefix shares even the prompt's first token. + NoSharedPrefix, + /// Stored prefixes share tokens with the prompt, but none ends on its + /// path. Recurrent state resumes only at a checkpoint that is a prefix of + /// the prompt, so the shared tokens cannot be reused. + NoCheckpointOnPath, + BelowMinTokens, + /// A checkpoint on the path matched but was not restored. + NotRestored, +} + +impl ResidentMissReason { + pub fn as_str(self) -> &'static str { + match self { + Self::LookupOff => "lookup_off", + Self::EmptyCache => "empty_cache", + Self::NoSharedPrefix => "no_shared_prefix", + Self::NoCheckpointOnPath => "no_checkpoint_on_path", + Self::BelowMinTokens => "below_min_tokens", + Self::NotRestored => "not_restored", + } + } + + pub(crate) fn classify( + resident_entries: usize, + shared_prefix_tokens: usize, + checkpoint_prefix_tokens: usize, + checkpoint_meets_min_tokens: bool, + ) -> Self { + match ( + resident_entries, + checkpoint_prefix_tokens, + shared_prefix_tokens, + ) { + (0, _, _) => Self::EmptyCache, + (_, 0, 0) => Self::NoSharedPrefix, + (_, 0, _) => Self::NoCheckpointOnPath, + _ if checkpoint_meets_min_tokens => Self::NotRestored, + _ => Self::BelowMinTokens, + } + } +} + +/// What the resident cache held for a prompt that missed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResidentMissDiagnosis { + pub reason: ResidentMissReason, + pub resident_entries: usize, + /// Longest prefix the prompt shares with any stored sequence. + pub shared_prefix_tokens: usize, + /// Length of the stored sequence that shares it. + pub stored_prefix_tokens: usize, + /// Longest stored checkpoint that is a whole prefix of the prompt. + pub checkpoint_prefix_tokens: usize, +} + +#[cfg(test)] +mod resident_miss_reason_tests { + use super::ResidentMissReason; + + #[test] + fn a_shared_prefix_without_a_checkpoint_on_the_path_is_named() { + assert_eq!( + ResidentMissReason::classify(3, 4_090, 0, false), + ResidentMissReason::NoCheckpointOnPath + ); + } + + #[test] + fn misses_name_their_cause() { + for (entries, shared, checkpoint, meets_min, reason) in [ + (0, 0, 0, false, ResidentMissReason::EmptyCache), + (2, 0, 0, false, ResidentMissReason::NoSharedPrefix), + (2, 64, 16, false, ResidentMissReason::BelowMinTokens), + (2, 64, 64, true, ResidentMissReason::NotRestored), + ] { + assert_eq!( + ResidentMissReason::classify(entries, shared, checkpoint, meets_min), + reason + ); + } + } +} + #[derive(Debug, Clone)] pub struct ResidentActivationRestore { pub identity: PrefillKvIdentity, diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs index b79c8bf69e..c385ad8822 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -15,7 +15,8 @@ use crate::runtime_state::RuntimeState; use super::{ KvLifecycleEvent, KvStageIntegration, PrefillKvIdentity, RadixResidentEntry, - ResidentPrefixRecord, ResidentPrefixRestore, ResidentSequencePool, StagePrefixCachePayload, + ResidentMissDiagnosis, ResidentMissReason, ResidentPrefixRecord, ResidentPrefixRestore, + ResidentRecordOutcome, ResidentRecordSkip, ResidentSequencePool, StagePrefixCachePayload, lock_resident_sequences, }; diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs index 900d77a647..4d3312fd16 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -8,11 +8,23 @@ impl KvStageIntegration { identity: &PrefillKvIdentity, token_ids: &[i32], ) -> Result> { - let Some((token_count, layers)) = - self.resident_capture_boundary(runtime, session_id, identity, token_ids)? - else { - return Ok(None); - }; + self.record_resident_prefix_outcome(runtime, session_id, identity, token_ids) + .map(ResidentRecordOutcome::into_record) + } + + /// Record a resident prefix, saying why when none is kept. + pub fn record_resident_prefix_outcome( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + ) -> Result { + let (token_count, layers) = + match self.resident_capture_boundary(runtime, session_id, identity, token_ids)? { + Ok(boundary) => boundary, + Err(skip) => return Ok(ResidentRecordOutcome::Skipped(skip)), + }; let tokens = &identity.token_ids[..token_count]; let mut radix = self .radix @@ -20,7 +32,7 @@ impl KvStageIntegration { .unwrap_or_else(std::sync::PoisonError::into_inner); let mut sequences = lock_resident_sequences(&self.resident_sequences); if let Some(existing) = radix.resident_exact(&identity.namespace, tokens) { - return Ok(Some(resident_record( + return Ok(ResidentRecordOutcome::Recorded(resident_record( existing.value, false, radix.stats(), @@ -36,17 +48,25 @@ impl KvStageIntegration { } else { 0 }; - if checkpoint_bytes > self.resident_checkpoint_max_bytes - || !make_record_room( - self.resident_config, - &mut radix, - &mut sequences, - checkpoint_bytes, - &mut evicted, - |victim| self.release_native_prefix(runtime, session_id, victim), - )? - { - return Ok(None); + if checkpoint_bytes > self.resident_checkpoint_max_bytes { + return Ok(ResidentRecordOutcome::Skipped( + ResidentRecordSkip::OverCheckpointBudget { + bytes: checkpoint_bytes, + budget_bytes: self.resident_checkpoint_max_bytes, + }, + )); + } + if !make_record_room( + self.resident_config, + &mut radix, + &mut sequences, + checkpoint_bytes, + &mut evicted, + |victim| self.release_native_prefix(runtime, session_id, victim), + )? { + return Ok(ResidentRecordOutcome::Skipped(ResidentRecordSkip::NoRoom { + bytes: checkpoint_bytes, + })); } let _host_reservation = if self.resident_requires_checkpoint() { let Some(reservation) = self.reserve_snapshot_host_memory( @@ -55,7 +75,9 @@ impl KvStageIntegration { StagePrefixCachePayload::ResidentKv, token_count as u64, ) else { - return Ok(None); + return Ok(ResidentRecordOutcome::Skipped(ResidentRecordSkip::NoRoom { + bytes: checkpoint_bytes, + })); }; reservation } else { @@ -104,8 +126,11 @@ impl KvStageIntegration { return Err(error); } }; - let room = if bytes > self.resident_checkpoint_max_bytes { - Ok(false) + let skip = if bytes > self.resident_checkpoint_max_bytes { + Ok(Some(ResidentRecordSkip::OverCheckpointBudget { + bytes, + budget_bytes: self.resident_checkpoint_max_bytes, + })) } else { make_record_room( self.resident_config, @@ -115,11 +140,11 @@ impl KvStageIntegration { &mut evicted, |victim| self.release_native_prefix(runtime, session_id, victim), ) + .map(|made| (!made).then_some(ResidentRecordSkip::NoRoom { bytes })) }; - if !matches!(room, Ok(true)) { + if let Some(skip) = skip.transpose() { self.release_unpublished_prefix(runtime, session_id, &mut sequences, &candidate)?; - room?; - return Ok(None); + return skip.map(ResidentRecordOutcome::Skipped); } let inserted = insert_saved_resident( &mut radix, @@ -143,7 +168,7 @@ impl KvStageIntegration { crate::frontend::capture_trace::log_stored_identity(&identity.namespace, tokens); } self.verify_resident_ownership(radix.stats().resident_entries, sequences.stats().0)?; - Ok(Some(resident_record( + Ok(ResidentRecordOutcome::Recorded(resident_record( entry, inserted, radix.stats(), @@ -157,9 +182,9 @@ impl KvStageIntegration { session_id: &str, identity: &PrefillKvIdentity, token_ids: &[i32], - ) -> Result> { + ) -> Result> { if !self.should_record() || self.payload != StagePrefixCachePayload::ResidentKv { - return Ok(None); + return Ok(Err(ResidentRecordSkip::RecordingOff)); } let requested = usize::try_from(identity.identity.token_count) .unwrap_or(usize::MAX) @@ -171,21 +196,24 @@ impl KvStageIntegration { .max(1); let checkpoint = self.resident_requires_checkpoint(); let count = if checkpoint { - if runtime.canonical_session_position(session_id)? != requested as u64 { - return Ok(None); + let session_tokens = runtime.canonical_session_position(session_id)?; + if session_tokens != requested as u64 { + return Ok(Err(ResidentRecordSkip::PositionMismatch { session_tokens })); } requested } else { recordable_token_count(self.resident_config, requested) }; if count == 0 || (count as u64) < self.checkpoint_policy.min_tokens { - return Ok(None); + return Ok(Err(ResidentRecordSkip::BelowMinTokens { + min_tokens: self.checkpoint_policy.min_tokens, + })); } anyhow::ensure!( identity.token_ids.get(..count) == token_ids.get(..count), "resident prefix identity does not match the session token path" ); - Ok(Some((count, layers))) + Ok(Ok((count, layers))) } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs index 1158bfb9e5..5fb56b1291 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix/selection.rs @@ -24,4 +24,52 @@ impl KvStageIntegration { radix.peek_resident(namespace, tokens) } } + + /// What the cache held for identities whose lookup restored nothing. + /// Reads without changing recency or references. + pub(crate) fn diagnose_resident_miss( + &self, + identities: &[PrefillKvIdentity], + ) -> ResidentMissDiagnosis { + if !self.should_lookup() || self.payload != StagePrefixCachePayload::ResidentKv { + return ResidentMissDiagnosis { + reason: ResidentMissReason::LookupOff, + resident_entries: 0, + shared_prefix_tokens: 0, + stored_prefix_tokens: 0, + checkpoint_prefix_tokens: 0, + }; + } + let radix = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let resident_entries = radix.stats().resident_entries; + let (shared_prefix_tokens, stored_prefix_tokens) = identities + .iter() + .filter_map(|identity| radix.peek_resident(&identity.namespace, &identity.token_ids)) + .map(|shared| (shared.matched_tokens, shared.stored_tokens.len())) + .max() + .unwrap_or_default(); + let checkpoint_prefix_tokens = identities + .iter() + .filter_map(|identity| { + self.peek_native_prefix(&radix, &identity.namespace, &identity.token_ids) + }) + .map(|checkpoint| checkpoint.matched_tokens) + .max() + .unwrap_or_default(); + ResidentMissDiagnosis { + reason: ResidentMissReason::classify( + resident_entries, + shared_prefix_tokens, + checkpoint_prefix_tokens, + self.meets_shared_prefix_min_tokens(checkpoint_prefix_tokens), + ), + resident_entries, + shared_prefix_tokens, + stored_prefix_tokens, + checkpoint_prefix_tokens, + } + } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs new file mode 100644 index 0000000000..326296918c --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs @@ -0,0 +1,242 @@ +//! This stage's cache tiers as the resource sampler reads them: weak handles, +//! so the sampler never keeps a stage alive, and a non-blocking radix lock, +//! so it never waits behind the scheduler. Cache decisions also become the +//! `skippy.kv.*` events. + +use std::sync::{ + Arc, Mutex, PoisonError, Weak, + atomic::{AtomicU64, AtomicUsize, Ordering}, +}; + +use skippy_cache::{L2Tier, L3Tier, UnifiedRadixCache, UnifiedRadixCacheStats}; + +use super::{KvLifecycleEvent, KvStageIntegration, RadixExactEntry, RadixResidentEntry}; +use crate::telemetry::log_events::{self, KvAdmissionShortfall, KvEviction, KvLookup, KvTier}; +use crate::telemetry::resource_metrics::kv_tiers::{ + self, KvTierReading, KvTierSource, L1Reading, L2Reading, L3Reading, RecordQueueReading, +}; + +type Radix = Mutex>; + +struct StageTierSource { + radix: Weak, + recurrent_limit_bytes: u64, + l2: Option>, + l3: Option>, + records_pending: Weak, + record_queue_bytes: Weak, + records_dropped: Weak, + /// The latest L1 reading, reused while the radix lock is held elsewhere. + last_l1: Mutex, +} + +/// Make `integration`'s tiers visible to the resource sampler. +pub(super) fn register(integration: &KvStageIntegration) { + kv_tiers::register(Box::new(StageTierSource { + radix: Arc::downgrade(&integration.radix), + recurrent_limit_bytes: integration.resident_checkpoint_max_bytes, + l2: integration.l2.as_ref().map(|l2| Arc::downgrade(l2.tier())), + l3: integration.l3.as_ref().map(Arc::downgrade), + records_pending: Arc::downgrade(&integration.exact_state_records_pending), + record_queue_bytes: Arc::downgrade(&integration.exact_state_record_queue_bytes), + records_dropped: Arc::downgrade(&integration.exact_state_records_dropped), + last_l1: Mutex::new(L1Reading::default()), + })); +} + +/// Count an L1 decision for the tier gauges. +pub(super) fn record_lifecycle(event: KvLifecycleEvent) { + match event { + KvLifecycleEvent::CacheLookupHit { matched_tokens, .. } => { + kv_tiers::record_l1_hit(matched_tokens as u64); + log_events::record(&KvLookup { + tier: KvTier::L1, + matched_tokens: Some(matched_tokens as u64), + }); + } + KvLifecycleEvent::CacheLookupMiss => { + kv_tiers::record_l1_miss(); + log_events::record(&KvLookup { + tier: KvTier::L1, + matched_tokens: None, + }); + } + KvLifecycleEvent::PrefixRestored { + restored_tokens, .. + } => kv_tiers::record_l1_restore(restored_tokens as u64), + KvLifecycleEvent::CacheEviction { + evicted_entries, + evicted_tokens, + } => { + kv_tiers::record_l1_eviction(evicted_tokens); + log_events::record(&KvEviction { + tier: KvTier::L1, + entries: evicted_entries as u64, + tokens: evicted_tokens, + }); + } + KvLifecycleEvent::CapacityApproachingLimit { + admission_deficit_tokens, + } => { + kv_tiers::record_l1_admission_shortfall(); + log_events::record(&KvAdmissionShortfall { + deficit_tokens: admission_deficit_tokens, + }); + } + _ => {} + } +} + +/// A lookup in L2 or L3, which serving decides outside the L1 lifecycle. +pub(super) fn record_lookup(tier: KvTier, matched_tokens: Option) { + log_events::record(&KvLookup { + tier, + matched_tokens, + }); +} + +impl KvTierSource for StageTierSource { + fn read(&self) -> Option { + let radix = self.radix.upgrade()?; + Some(KvTierReading { + l1: self.l1(&radix), + l2: self + .l2 + .as_ref() + .and_then(Weak::upgrade) + .map(|tier| l2(&tier)), + l3: self + .l3 + .as_ref() + .and_then(Weak::upgrade) + .map(|tier| l3(&tier)), + record_queue: RecordQueueReading { + records: self + .records_pending + .upgrade() + .map_or(0, |pending| pending.load(Ordering::Relaxed) as u64), + bytes: load(&self.record_queue_bytes), + dropped: load(&self.records_dropped), + }, + }) + } +} + +impl StageTierSource { + fn l1(&self, radix: &Radix) -> L1Reading { + let mut last = self.last_l1.lock().unwrap_or_else(PoisonError::into_inner); + if let Ok(radix) = radix.try_lock() { + *last = l1(&radix.stats(), self.recurrent_limit_bytes); + } + *last + } +} + +fn load(counter: &Weak) -> u64 { + counter + .upgrade() + .map_or(0, |counter| counter.load(Ordering::Relaxed)) +} + +fn l1(stats: &UnifiedRadixCacheStats, recurrent_limit_bytes: u64) -> L1Reading { + L1Reading { + entries: stats.resident_entries as u64, + tokens: stats.resident_tokens, + pinned_tokens: stats.resident_pinned_tokens, + recurrent_bytes: stats.recurrent_logical_bytes, + recurrent_limit_bytes, + attention_evictions: stats.resident_evictions, + recurrent_evictions: stats.recurrent_evictions, + } +} + +fn l2(tier: &L2Tier) -> L2Reading { + let stats = tier.stats(); + L2Reading { + entries: stats.entries, + bytes: stats.bytes, + budget_bytes: stats.budget_bytes, + hits: stats.hits, + misses: stats.misses, + inserts: stats.inserts, + evictions: stats.evictions, + refusals: stats.admission_rejects, + } +} + +fn l3(tier: &L3Tier) -> L3Reading { + let store = tier.store(); + let pressure = store.pressure(); + let activity = tier.manager().activity_without_inventory(); + L3Reading { + store: std::ptr::from_ref(store) as usize, + used_bytes: pressure.used_bytes, + budget_bytes: pressure.budget_bytes, + reserved_bytes: pressure.reserved_inflight_bytes, + filesystem_available_bytes: pressure.filesystem_available_bytes, + hits: activity.hits, + misses: activity.misses, + fills: activity.fills, + writes: activity.writes, + bytes_read: activity.bytes_read, + bytes_written: activity.bytes_written, + evictions: activity.evictions, + corrupt: activity.corrupt_entries, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn l1_readings_come_from_the_radix_stats_and_the_checkpoint_budget() { + let stats = UnifiedRadixCacheStats { + resident_entries: 3, + resident_tokens: 96, + resident_pinned_tokens: 32, + recurrent_logical_bytes: 512, + resident_evictions: 2, + recurrent_evictions: 1, + ..UnifiedRadixCacheStats::default() + }; + let reading = l1(&stats, 4096); + assert_eq!( + reading, + L1Reading { + entries: 3, + tokens: 96, + pinned_tokens: 32, + recurrent_bytes: 512, + recurrent_limit_bytes: 4096, + attention_evictions: 2, + recurrent_evictions: 1, + } + ); + } + + #[test] + fn a_dropped_stage_stops_reporting_and_a_held_lock_reuses_the_last_reading() { + let radix: Arc = Arc::new(Mutex::new(UnifiedRadixCache::new())); + let source = StageTierSource { + radix: Arc::downgrade(&radix), + recurrent_limit_bytes: 64, + l2: None, + l3: None, + records_pending: Weak::new(), + record_queue_bytes: Weak::new(), + records_dropped: Weak::new(), + last_l1: Mutex::new(L1Reading::default()), + }; + let first = source.read().expect("live stage"); + assert_eq!(first.l1.recurrent_limit_bytes, 64); + assert!(first.l2.is_none() && first.l3.is_none()); + + let held = radix.lock().expect("radix lock"); + assert_eq!(source.read().map(|reading| reading.l1), Some(first.l1)); + drop(held); + + drop(radix); + assert!(source.read().is_none()); + } +} diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index d121c27b32..8f2e7a2df1 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -41,8 +41,9 @@ pub struct RuntimeLaunchOverrides { pub n_threads: Option, pub n_threads_batch: Option, pub mtp_source: MtpSource, - /// Recurrent rollback depth the speculative plan needs; `0` keeps the - /// native default. + /// Recurrent rollback depth the speculative plan needs; `0` disables + /// snapshots for a known non-drafting runtime. An MTP source without an + /// explicit depth retains a two-input compatibility default. pub recurrent_rollback_tokens: u32, } @@ -622,7 +623,13 @@ pub(crate) fn runtime_config_from_stage_config( skippy_protocol::GlmDsaPolicy::V1 => RuntimeGlmDsaPolicy::V1, }, mtp_source: overrides.mtp_source, - recurrent_rollback_tokens: overrides.recurrent_rollback_tokens, + recurrent_rollback_tokens: if overrides.mtp_source != MtpSource::Disabled + && overrides.recurrent_rollback_tokens == 0 + { + 2 + } else { + overrides.recurrent_rollback_tokens + }, resident_tensor_names: config.resident_tensor_names.clone(), execution_contract: config.execution_contract.clone(), activation_import_identities: config.activation_import_identities.clone(), @@ -962,6 +969,24 @@ mod tests { assert_eq!(runtime_config.recurrent_rollback_tokens, 16); } + #[test] + fn runtime_config_rollback_distinguishes_nondraft_and_unknown_mtp() { + let config = StageConfig { + stage_id: "stage-0".into(), + layer_end: 1, + ..StageConfig::default() + }; + let mut overrides = RuntimeLaunchOverrides::default(); + let plain = runtime_config_from_stage_config(&config, &overrides).unwrap(); + assert_eq!(plain.recurrent_rollback_tokens, 0); + overrides.mtp_source = MtpSource::Integrated; + let mtp = runtime_config_from_stage_config(&config, &overrides).unwrap(); + assert_eq!(mtp.recurrent_rollback_tokens, 2); + overrides.recurrent_rollback_tokens = 1; + let explicit = runtime_config_from_stage_config(&config, &overrides).unwrap(); + assert_eq!(explicit.recurrent_rollback_tokens, 1); + } + #[test] fn runtime_config_parses_checkpoint_quantization() { let config = StageConfig { diff --git a/skippy/crates/skippy-serving/src/telemetry.rs b/skippy/crates/skippy-serving/src/telemetry.rs index d279850682..62dd43b26a 100644 --- a/skippy/crates/skippy-serving/src/telemetry.rs +++ b/skippy/crates/skippy-serving/src/telemetry.rs @@ -1,21 +1,17 @@ +#[cfg(test)] +use std::sync::mpsc as std_mpsc; use std::{ collections::{BTreeMap, VecDeque}, - env, - io::{BufWriter, Write}, sync::{ - Arc, OnceLock, + Arc, atomic::{AtomicU64, Ordering}, - mpsc as std_mpsc, }, - thread::{self, JoinHandle}, - time::{Duration, SystemTime, UNIX_EPOCH}, + thread, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; -use opentelemetry_proto::tonic::{ - collector::trace::v1::{ExportTraceServiceRequest, trace_service_client::TraceServiceClient}, - common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}, - resource::v1::Resource, - trace::v1::{ResourceSpans, ScopeSpans, Span, span}, +use opentelemetry_proto::tonic::collector::trace::v1::{ + ExportTraceServiceRequest, trace_service_client::TraceServiceClient, }; use serde::Serialize; use serde_json::{Value, json}; @@ -26,34 +22,36 @@ use tokio::{ time::{sleep, timeout}, }; -static EVENT_COUNTER: AtomicU64 = AtomicU64::new(1); -static STDERR_SINK: OnceLock = OnceLock::new(); - -/// Whether the stderr debug sink is enabled via `SKIPPY_TELEMETRY_STDERR`. -/// -/// Read once: this is consulted on the record and lookup paths, which run per -/// request. -fn stderr_sink_enabled() -> bool { - *STDERR_SINK.get_or_init(|| { - stderr_sink_enabled_from_value(env::var("SKIPPY_TELEMETRY_STDERR").ok().as_deref()) - }) -} - -fn stderr_sink_enabled_from_value(value: Option<&str>) -> bool { - value.is_some_and(|value| { - !matches!( - value.trim().to_ascii_lowercase().as_str(), - "" | "0" | "false" | "no" | "off" - ) - }) -} - -/// The stderr sink acts as a floor on the configured level. +pub(crate) mod active_span; +mod gpu_commands; +pub(crate) mod log_events; +mod native_calls; +mod native_spans; +mod otlp_encoding; +mod otlp_file; +mod resource_attrs; +pub(crate) mod resource_metrics; +mod resource_usage; +mod span_components; +mod stderr_sink; +pub(crate) mod trace_context; + +use otlp_encoding::{event_to_span, resource_spans_by_component}; +use stderr_sink::{StderrTelemetryEvent, StderrTelemetrySink, stderr_sink_enabled}; +use trace_context::{Frame, SpanContext, SpanEvent}; + +/// How long shutdown waits for queued spans to reach their sinks. +const FLUSH_TIMEOUT: Duration = Duration::from_secs(5); +/// Bound on delivering a span that ends after the process span. +const LATE_SPAN_FLUSH_TIMEOUT: Duration = Duration::from_millis(500); + +/// A local debug sink (stderr or OTLP file) acts as a floor on the configured +/// level. /// /// It never lowers an explicitly configured level, so a collector-backed /// `Summary` deployment is unaffected by the variable being set. -fn effective_level(configured: TelemetryLevel, stderr_sink: bool) -> TelemetryLevel { - if stderr_sink && configured == TelemetryLevel::Off { +fn effective_level(configured: TelemetryLevel, local_sink: bool) -> TelemetryLevel { + if local_sink && configured == TelemetryLevel::Off { TelemetryLevel::Debug } else { configured @@ -68,6 +66,7 @@ const RETRY_BACKOFF: Duration = Duration::from_millis(100); pub struct Telemetry { tx: Option>, stderr: Option>, + otlp_file: Option<&'static otlp_file::OtlpFileSink>, stats: Arc, config: Arc, level: TelemetryLevel, @@ -87,6 +86,8 @@ pub(crate) struct CapturedEvent { pub attributes: BTreeMap, pub start_time_unix_nanos: u64, pub end_time_unix_nanos: u64, + /// The exported span's identity and parent; `None` for a point event. + pub span: Option<(SpanContext, Option<[u8; 8]>)>, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -112,85 +113,36 @@ pub struct TelemetryStats { pub export_errors: u64, } +/// One finished span, placed in the process trace. #[derive(Clone)] struct TelemetryEvent { - id: u64, + context: SpanContext, + parent: Option<[u8; 8]>, name: String, attributes: BTreeMap, start_time_unix_nanos: u64, end_time_unix_nanos: u64, + links: Vec, + events: Vec, } -#[derive(Serialize)] -struct StderrTelemetryEvent { - event: String, - attributes: BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, -} - -struct StderrTelemetrySink { - tx: Option>, - worker: Option>, -} - -impl StderrTelemetrySink { - fn channel( - capacity: usize, - ) -> ( - std_mpsc::SyncSender, - std_mpsc::Receiver, - ) { - // Disabled telemetry supplies zero capacity. The stderr override can - // enable it later, so give that opt-in sink the same bounded default - // as debug telemetry instead of a one-event queue that loses bursts. - std_mpsc::sync_channel(if capacity == 0 { 1024 } else { capacity }) - } - - fn new(capacity: usize) -> Option { - let (tx, rx) = Self::channel(capacity); - let worker = thread::Builder::new() - .name("skippy-telemetry-stderr".to_string()) - .spawn(move || stderr_telemetry_loop(rx)) - .ok()?; - Some(Self { - tx: Some(tx), - worker: Some(worker), - }) - } - - fn try_send(&self, event: StderrTelemetryEvent) -> bool { - self.tx - .as_ref() - .is_some_and(|tx| tx.try_send(event).is_ok()) - } -} - -impl Drop for StderrTelemetrySink { - fn drop(&mut self) { - self.tx.take(); - if let Some(worker) = self.worker.take() { - let _ = worker.join(); - } - } -} - -fn stderr_telemetry_loop(rx: std_mpsc::Receiver) { - while let Ok(event) = rx.recv() { - let stderr = std::io::stderr(); - let mut writer = BufWriter::new(stderr.lock()); - if serde_json::to_writer(&mut writer, &event).is_err() || writer.write_all(b"\n").is_err() { - return; - } - while let Ok(event) = rx.try_recv() { - if serde_json::to_writer(&mut writer, &event).is_err() - || writer.write_all(b"\n").is_err() - { - return; - } - } - if writer.flush().is_err() { - return; +impl TelemetryEvent { + fn span( + frame: &Frame, + name: &str, + attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + ) -> Self { + Self { + context: frame.context(), + parent: frame.parent_span_id(), + name: name.to_string(), + attributes, + start_time_unix_nanos, + end_time_unix_nanos: end_time_unix_nanos.max(start_time_unix_nanos.saturating_add(1)), + links: Vec::new(), + events: Vec::new(), } } } @@ -207,10 +159,13 @@ impl Telemetry { // when the level was `Off` -- and the embedded runtime defaults to // `Off`. So the variable silently did nothing in exactly the // single-process case it exists for. Honour it as a level floor, and - // the existing level checks then work unchanged. - let level = effective_level(level, stderr_sink_enabled()); + // the existing level checks then work unchanged. The OTLP file sink + // is the same kind of local opt-in. + let otlp_file = otlp_file::configured(); + let level = effective_level(level, stderr_sink_enabled() || otlp_file.is_some()); let stats = Arc::new(TelemetryCounters::default()); let config = Arc::new(config); + let metrics_endpoint = endpoint.clone(); let tx = (level != TelemetryLevel::Off) .then_some(endpoint) .flatten() @@ -225,30 +180,68 @@ impl Telemetry { tx }); - Self { + let telemetry = Self { tx, stderr: stderr_sink_enabled() .then(|| StderrTelemetrySink::new(capacity)) .flatten() .map(Arc::new), + otlp_file, stats, config, level, #[cfg(test)] capture: None, + }; + log_events::start(&telemetry, metrics_endpoint.as_deref()); + if telemetry.is_debug_enabled() && telemetry.has_sink() { + native_calls::install(&telemetry); + resource_metrics::start(&telemetry, metrics_endpoint.as_deref()); } + telemetry + } + + fn has_sink(&self) -> bool { + self.tx.is_some() || self.stderr.is_some() || self.otlp_file.is_some() } + /// A point event. Trace sinks record it as an event on the active span; + /// stderr keeps its standalone line. pub fn emit(&self, name: &str, mut attributes: BTreeMap) { if self.level == TelemetryLevel::Off { return; } self.add_common_attributes(&mut attributes); - let now = now_unix_nanos() as u64; - self.enqueue(name, attributes, now, now + 1); + #[cfg(test)] + if self.capture(name, &attributes, now, now + 1, None) { + return; + } + self.send_stderr(name, &attributes, now, now + 1); + let frame = trace_context::current_frame_or_root(); + log_events::record_point_event(&frame, name, &attributes); + if !self.has_trace_sink() { + return; + } + let event = SpanEvent { + name: name.to_string(), + time_unix_nanos: now, + attributes, + }; + if let Err(event) = frame.record_event(event) { + // The active span already ended or is full: keep the event as an + // instant span beneath it instead of losing it. + self.export(TelemetryEvent::span( + &Frame::child(), + &event.name, + event.attributes, + now, + now + 1, + )); + } } + /// A span measured by the caller, placed under the active span. pub fn emit_span( &self, name: &str, @@ -260,12 +253,106 @@ impl Telemetry { return; } self.add_common_attributes(&mut attributes); - self.enqueue( + self.deliver(TelemetryEvent::span( + &Frame::child(), name, attributes, start_time_unix_nanos, - end_time_unix_nanos.max(start_time_unix_nanos + 1), + end_time_unix_nanos, + )); + } + + /// Export the span `frame` identifies, with the events recorded on it. + pub(crate) fn emit_frame_span( + &self, + frame: &Frame, + name: &str, + mut attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + links: Vec, + ) { + let events = frame.take_events(); + if self.level == TelemetryLevel::Off { + return; + } + self.add_common_attributes(&mut attributes); + let mut record = TelemetryEvent::span( + frame, + name, + attributes, + start_time_unix_nanos, + end_time_unix_nanos, ); + record.links = links; + record.events = events; + self.deliver(record); + } + + pub(crate) fn emit_debug_frame_span( + &self, + frame: &Frame, + name: &str, + attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + ) { + if self.level == TelemetryLevel::Debug { + self.emit_frame_span( + frame, + name, + attributes, + start_time_unix_nanos, + end_time_unix_nanos, + Vec::new(), + ); + } else { + frame.take_events(); + } + } + + /// End the process span and flush queued spans. Shutdown calls this; only + /// the first call in the process does anything. + pub fn finish_process(&self) { + let process = trace_context::process(); + if self.level == TelemetryLevel::Off || !process.begin_finish() { + return; + } + // Spans and GPU records still queued belong to calls that already ended. + native_spans::emit_pending(self); + gpu_commands::emit_pending(self); + self.record_resources("shutdown"); + resource_metrics::finish(); + log_events::finish(); + let mut attributes = lifecycle_attrs(&self.config); + attributes.insert("process.pid".to_string(), json!(std::process::id())); + self.emit_frame_span( + process.root(), + "skippy.process", + attributes, + process.start_unix_nanos(), + now_unix_nanos() as u64, + Vec::new(), + ); + self.flush(FLUSH_TIMEOUT); + } + + /// Wait, bounded by `timeout`, for queued spans to reach their sinks. + fn flush(&self, timeout: Duration) { + let deadline = Instant::now() + timeout; + if let Some(file) = self.otlp_file { + file.flush(timeout); + } + if self.tx.is_some() { + without_starving_runtime(|| { + while self.stats.sent.load(Ordering::Relaxed) + < self.stats.queued.load(Ordering::Relaxed) + && Instant::now() < deadline + { + thread::sleep(Duration::from_millis(20)); + } + }); + } } fn add_common_attributes(&self, attributes: &mut BTreeMap) { @@ -285,57 +372,66 @@ impl Telemetry { ); } - fn enqueue( + fn deliver(&self, record: TelemetryEvent) { + #[cfg(test)] + if self.capture( + &record.name, + &record.attributes, + record.start_time_unix_nanos, + record.end_time_unix_nanos, + Some((record.context, record.parent)), + ) { + return; + } + self.send_stderr( + &record.name, + &record.attributes, + record.start_time_unix_nanos, + record.end_time_unix_nanos, + ); + self.export(record); + // Components that stop after the process span (the scheduler worker, + // say) end their spans during exit; deliver each one immediately + // because the process will not wait for the exporters. + if trace_context::process().is_finished() { + self.flush(LATE_SPAN_FLUSH_TIMEOUT); + } + } + + fn has_trace_sink(&self) -> bool { + self.tx.is_some() || self.otlp_file.is_some() + } + + fn send_stderr( &self, name: &str, - attributes: BTreeMap, + attributes: &BTreeMap, start_time_unix_nanos: u64, end_time_unix_nanos: u64, ) { - // Test-only capture takes precedence so sibling tests observe exact - // emissions without a collector or the env-gated stderr sink. - #[cfg(test)] - if let Some(capture) = self.capture.as_ref() { - let _ = capture.try_send(CapturedEvent { - event: name.to_string(), - attributes, - start_time_unix_nanos, - end_time_unix_nanos, - }); - return; - } - if let (Some(stderr), None) = (self.stderr.as_ref(), self.tx.as_ref()) { - if !stderr.try_send(StderrTelemetryEvent { - event: name.to_string(), - attributes, - start_time_unix_nanos, - end_time_unix_nanos, - }) { - self.stats.dropped.fetch_add(1, Ordering::Relaxed); - } + let Some(stderr) = self.stderr.as_ref() else { return; + }; + if !stderr.try_send(StderrTelemetryEvent { + event: name.to_string(), + attributes: attributes.clone(), + start_time_unix_nanos, + end_time_unix_nanos, + }) { + self.stats.dropped.fetch_add(1, Ordering::Relaxed); } - if let Some(stderr) = self.stderr.as_ref() - && !stderr.try_send(StderrTelemetryEvent { - event: name.to_string(), - attributes: attributes.clone(), - start_time_unix_nanos, - end_time_unix_nanos, - }) + } + + fn export(&self, record: TelemetryEvent) { + if let Some(file) = self.otlp_file + && !file.try_send(&self.config, event_to_span(&record, &self.stats)) { self.stats.dropped.fetch_add(1, Ordering::Relaxed); } let Some(tx) = self.tx.as_ref() else { return; }; - let event = TelemetryEvent { - id: EVENT_COUNTER.fetch_add(1, Ordering::Relaxed), - name: name.to_string(), - attributes, - start_time_unix_nanos, - end_time_unix_nanos, - }; - match tx.try_send(event) { + match tx.try_send(record) { Ok(()) => { self.stats.queued.fetch_add(1, Ordering::Relaxed); } @@ -345,6 +441,30 @@ impl Telemetry { } } + /// Test-only capture takes precedence so sibling tests observe exact + /// emissions without a collector or the env-gated stderr sink. + #[cfg(test)] + fn capture( + &self, + name: &str, + attributes: &BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + span: Option<(SpanContext, Option<[u8; 8]>)>, + ) -> bool { + let Some(capture) = self.capture.as_ref() else { + return false; + }; + let _ = capture.try_send(CapturedEvent { + event: name.to_string(), + attributes: attributes.clone(), + start_time_unix_nanos, + end_time_unix_nanos, + span, + }); + true + } + pub fn emit_debug(&self, name: &str, attributes: BTreeMap) { if self.level == TelemetryLevel::Debug { self.emit(name, attributes); @@ -363,6 +483,28 @@ impl Telemetry { } } + /// A debug span under `parent`, which may live on another thread. + pub(crate) fn emit_debug_span_under( + &self, + parent: SpanContext, + name: &str, + mut attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + ) { + if self.level != TelemetryLevel::Debug { + return; + } + self.add_common_attributes(&mut attributes); + self.deliver(TelemetryEvent::span( + &Frame::under(parent), + name, + attributes, + start_time_unix_nanos, + end_time_unix_nanos, + )); + } + pub fn is_enabled(&self) -> bool { self.level != TelemetryLevel::Off } @@ -398,6 +540,7 @@ impl Telemetry { Self { tx: None, stderr: None, + otlp_file: None, stats: Arc::new(TelemetryCounters::default()), config: Arc::new(config), level, @@ -409,27 +552,29 @@ impl Telemetry { } } +/// Test-only: the smallest stage config a captured `Telemetry` accepts. +#[cfg(test)] +pub(crate) fn capture_stage_config() -> StageConfig { + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + })) + .expect("minimal stage config for telemetry capture") +} + #[cfg(test)] mod capture_tests { - use super::{BTreeMap, StageConfig, Telemetry, TelemetryLevel}; + use super::{BTreeMap, Telemetry, TelemetryLevel, capture_stage_config as capture_config}; use serde_json::json; - fn capture_config() -> StageConfig { - serde_json::from_value(json!({ - "run_id": "run", - "topology_id": "topology", - "model_id": "org/model:Q4_K_M", - "stage_id": "stage-0", - "stage_index": 0, - "layer_start": 0, - "layer_end": 4, - "load_mode": "runtime-slice", - "execution_contract": "", - "bind_addr": "127.0.0.1:0", - })) - .expect("minimal stage config for telemetry capture") - } - #[test] fn captured_sink_reports_normal_events_with_common_attributes_at_summary_level() { let (telemetry, rx) = Telemetry::captured(capture_config(), TelemetryLevel::Summary); @@ -465,6 +610,20 @@ mod capture_tests { } } +/// Run a blocking `wait` for the gRPC exporter, a task on the caller's +/// runtime. Blocking a runtime worker in place can starve that task: woken +/// from this worker, it sits in the worker's LIFO slot, which other workers +/// never steal. `block_in_place` hands the worker's queue to another thread +/// first. A current-thread runtime cannot run the exporter while blocked, so +/// waiting there would only stall. +fn without_starving_runtime(wait: impl FnOnce()) { + match tokio::runtime::Handle::try_current().map(|handle| handle.runtime_flavor()) { + Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(wait), + Ok(_) => {} + Err(_) => wait(), + } +} + pub fn lifecycle_attrs(config: &StageConfig) -> BTreeMap { BTreeMap::from([ (attr::RUN_ID.to_string(), json!(config.run_id)), @@ -570,27 +729,13 @@ async fn export_batch( } let request = ExportTraceServiceRequest { - resource_spans: vec![ResourceSpans { - resource: Some(Resource { - attributes: resource_attributes(config), - dropped_attributes_count: 0, - entity_refs: vec![], - }), - scope_spans: vec![ScopeSpans { - scope: Some(InstrumentationScope { - name: "skippy-serving".to_string(), - version: env!("CARGO_PKG_VERSION").to_string(), - attributes: vec![], - dropped_attributes_count: 0, - }), - spans: events - .iter() - .map(|event| event_to_span(event, stats)) - .collect(), - schema_url: String::new(), - }], - schema_url: String::new(), - }], + resource_spans: resource_spans_by_component( + config, + events + .iter() + .map(|event| event_to_span(event, stats)) + .collect(), + ), }; let export = client @@ -623,145 +768,69 @@ fn requeue_failed_batch( overflow } -fn event_to_span(event: &TelemetryEvent, stats: &TelemetryCounters) -> Span { - let mut attributes = event.attributes.clone(); - attributes.insert( - metric::OTEL_DROPPED_EVENTS.to_string(), - json!(stats.dropped.load(Ordering::Relaxed)), - ); - attributes.insert( - metric::OTEL_EXPORT_ERRORS.to_string(), - json!(stats.export_errors.load(Ordering::Relaxed)), - ); - Span { - trace_id: trace_id(event.start_time_unix_nanos, event.id), - span_id: span_id(event.id), - trace_state: String::new(), - parent_span_id: vec![], - flags: 1, - name: event.name.clone(), - kind: span::SpanKind::Internal as i32, - start_time_unix_nano: event.start_time_unix_nanos, - end_time_unix_nano: event.end_time_unix_nanos, - attributes: attributes - .into_iter() - .map(|(key, value)| KeyValue { - key, - value: Some(json_to_any_value(value)), - ..Default::default() +#[cfg(test)] +mod tests { + use super::{TelemetryLevel, effective_level, without_starving_runtime}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + /// Block on a one-worker runtime until a task spawned from that worker + /// runs, or `patience` passes; true when the task ran. + fn spawned_task_runs_while_waiting( + patience: Duration, + wait: fn(Box), + ) -> bool { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .build() + .unwrap(); + runtime.block_on(async move { + tokio::spawn(async move { + let ran = Arc::new(AtomicBool::new(false)); + let task_ran = Arc::clone(&ran); + tokio::spawn(async move { task_ran.store(true, Ordering::SeqCst) }); + let deadline = Instant::now() + patience; + wait(Box::new(|| { + while !ran.load(Ordering::SeqCst) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + })); + ran.load(Ordering::SeqCst) }) - .collect(), - dropped_attributes_count: 0, - events: vec![], - dropped_events_count: 0, - links: vec![], - dropped_links_count: 0, - status: None, - } -} - -fn resource_attributes(config: &StageConfig) -> Vec { - lifecycle_attrs(config) - .into_iter() - .map(|(key, value)| KeyValue { - key, - value: Some(json_to_any_value(value)), - ..Default::default() + .await + .unwrap() }) - .collect() -} - -fn json_to_any_value(value: Value) -> AnyValue { - let value = match value { - Value::String(value) => any_value::Value::StringValue(value), - Value::Bool(value) => any_value::Value::BoolValue(value), - Value::Number(value) => { - if let Some(value) = value.as_i64() { - any_value::Value::IntValue(value) - } else { - any_value::Value::DoubleValue(value.as_f64().unwrap_or_default()) - } - } - Value::Array(values) => { - any_value::Value::ArrayValue(opentelemetry_proto::tonic::common::v1::ArrayValue { - values: values.into_iter().map(json_to_any_value).collect(), - }) - } - Value::Object(values) => { - any_value::Value::KvlistValue(opentelemetry_proto::tonic::common::v1::KeyValueList { - values: values - .into_iter() - .map(|(key, value)| KeyValue { - key, - value: Some(json_to_any_value(value)), - ..Default::default() - }) - .collect(), - }) - } - Value::Null => any_value::Value::StringValue(String::new()), - }; - AnyValue { value: Some(value) } -} - -fn trace_id(start_time_unix_nanos: u64, event_id: u64) -> Vec { - let mut id = [0_u8; 16]; - id[..8].copy_from_slice(&start_time_unix_nanos.to_be_bytes()); - id[8..].copy_from_slice(&event_id.to_be_bytes()); - id.to_vec() -} - -fn span_id(counter: u64) -> Vec { - counter.to_be_bytes().to_vec() -} + } -#[cfg(test)] -mod tests { - use super::{TelemetryLevel, effective_level, stderr_sink_enabled_from_value}; + #[test] + fn waiting_on_a_runtime_worker_lets_the_workers_tasks_run() { + assert!(spawned_task_runs_while_waiting( + Duration::from_secs(5), + |wait| without_starving_runtime(wait) + )); + } #[test] - fn stderr_queue_buffers_disabled_config_bursts_and_respects_explicit_bounds() { - for (configured, expected) in [(0, 1024), (1, 1), (8, 8)] { - let (tx, rx) = super::StderrTelemetrySink::channel(configured); - let event = || super::StderrTelemetryEvent { - event: "stage.binary_request_summary".into(), - attributes: Default::default(), - start_time_unix_nanos: 1, - end_time_unix_nanos: 2, - }; - for _ in 0..expected { - tx.try_send(event()).expect("burst fits configured buffer"); - } - assert!(matches!( - tx.try_send(event()), - Err(std::sync::mpsc::TrySendError::Full(_)) - )); - assert_eq!(rx.try_iter().count(), expected); - tx.try_send(event()).expect("drained buffer accepts events"); - } + fn waiting_in_place_on_a_runtime_worker_starves_its_tasks() { + // The failure the helper exists for; if this ever passes, tokio has + // made the LIFO slot stealable. + assert!(!spawned_task_runs_while_waiting( + Duration::from_millis(200), + |wait| wait() + )); } #[test] - fn stderr_sink_false_values_do_not_enable_debug_telemetry() { - for value in [ - None, - Some(""), - Some("0"), - Some("false"), - Some("no"), - Some("off"), - ] { - assert!(!stderr_sink_enabled_from_value(value), "value={value:?}"); - } - for value in [ - Some("1"), - Some("true"), - Some("yes"), - Some("on"), - Some("debug"), - ] { - assert!(stderr_sink_enabled_from_value(value), "value={value:?}"); - } + fn a_current_thread_runtime_does_not_stall_waiting() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let started = Instant::now(); + runtime.block_on(async { + without_starving_runtime(|| std::thread::sleep(Duration::from_secs(5))); + }); + assert!(started.elapsed() < Duration::from_secs(1)); } /// `SKIPPY_TELEMETRY_STDERR` is the only way to see record/lookup diff --git a/skippy/crates/skippy-serving/src/telemetry/active_span.rs b/skippy/crates/skippy-serving/src/telemetry/active_span.rs new file mode 100644 index 0000000000..af0887fc0d --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/active_span.rs @@ -0,0 +1,239 @@ +//! A span owned by the section of code it measures. Child spans and events +//! attach to it while it is entered; it is exported when it ends or drops. + +use std::{ + collections::BTreeMap, + time::{Duration, Instant}, +}; + +use serde_json::Value; + +use super::{ + Telemetry, TelemetryLevel, now_unix_nanos, + trace_context::{self, Entered, Frame, SpanContext}, +}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum SpanLevel { + Summary, + Debug, +} + +impl SpanLevel { + fn recorded_at(self, level: TelemetryLevel) -> bool { + match self { + Self::Summary => level != TelemetryLevel::Off, + Self::Debug => level == TelemetryLevel::Debug, + } + } +} + +#[must_use = "a span is exported when it ends; dropping it immediately records nothing useful"] +pub(crate) struct ActiveSpan { + /// `None` when not recorded: the frame then passes the parent through, so + /// children never point at a span that is not exported. + telemetry: Option, + frame: Frame, + name: &'static str, + start_unix_nanos: u64, + started: Instant, + attributes: BTreeMap, + links: Vec, +} + +impl ActiveSpan { + /// Start a span under whatever is active here. + pub(crate) fn start( + telemetry: Option<&Telemetry>, + name: &'static str, + level: SpanLevel, + ) -> Self { + Self::start_under( + &trace_context::current_frame_or_root(), + telemetry, + name, + level, + ) + } + + /// Start a span directly under the process root, for a component that + /// outlives the section that creates it, such as a worker thread. + pub(crate) fn start_under_process( + telemetry: Option<&Telemetry>, + name: &'static str, + level: SpanLevel, + ) -> Self { + Self::start_under(trace_context::process().root(), telemetry, name, level) + } + + fn start_under( + parent: &Frame, + telemetry: Option<&Telemetry>, + name: &'static str, + level: SpanLevel, + ) -> Self { + let telemetry = telemetry + .filter(|telemetry| level.recorded_at(telemetry.level)) + .cloned(); + let frame = if telemetry.is_some() { + parent.new_child() + } else { + parent.clone() + }; + Self { + telemetry, + frame, + name, + start_unix_nanos: u64::try_from(now_unix_nanos()).unwrap_or_default(), + started: Instant::now(), + attributes: BTreeMap::new(), + links: Vec::new(), + } + } + + /// Make this the active span on this thread (synchronous code). + pub(crate) fn enter(&self) -> Entered { + self.frame.enter() + } + + pub(crate) fn frame(&self) -> &Frame { + &self.frame + } + + pub(crate) fn elapsed(&self) -> Duration { + self.started.elapsed() + } + + pub(crate) fn extend_attributes( + &mut self, + attributes: impl IntoIterator, + ) { + self.attributes.extend(attributes); + } + + /// Link to a span this one served, such as a request in a batch. + pub(crate) fn link(&mut self, context: SpanContext) { + if context != self.frame.context() && !self.links.contains(&context) { + self.links.push(context); + } + } + + pub(crate) fn end(mut self) { + self.finish(); + } + + /// Drop without exporting, for a section that turned out to do no work. + pub(crate) fn discard(mut self) { + self.telemetry = None; + } + + fn finish(&mut self) { + let Some(telemetry) = self.telemetry.take() else { + return; + }; + let elapsed = u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX); + telemetry.emit_frame_span( + &self.frame, + self.name, + std::mem::take(&mut self.attributes), + self.start_unix_nanos, + self.start_unix_nanos.saturating_add(elapsed), + std::mem::take(&mut self.links), + ); + } +} + +impl Drop for ActiveSpan { + fn drop(&mut self) { + self.finish(); + } +} + +#[cfg(test)] +mod tests { + use std::{collections::HashMap, sync::mpsc as std_mpsc, thread}; + + use super::*; + use crate::telemetry::{CapturedEvent, capture_stage_config as config}; + + /// Exported spans by name, as (context, parent span id). + fn spans( + rx: &std_mpsc::Receiver, + ) -> HashMap)> { + rx.try_iter() + .filter_map(|event| event.span.map(|span| (event.event, span))) + .collect() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn request_work_nests_under_its_request_across_threads() { + let (telemetry, rx) = Telemetry::captured(config(), TelemetryLevel::Debug); + let root = trace_context::process().root().context(); + let request = ActiveSpan::start( + Some(&telemetry), + "stage.openai_http_request", + SpanLevel::Summary, + ); + let handler_telemetry = telemetry.clone(); + trace_context::in_task(request.frame().clone(), async move { + let telemetry = handler_telemetry; + let phase = ActiveSpan::start( + Some(&telemetry), + "stage.openai_generation", + SpanLevel::Debug, + ); + let (blocking, origin) = { + let _phase = phase.enter(); + let native = telemetry.clone(); + let blocking = tokio::task::spawn_blocking(trace_context::propagate(move || { + native.emit_debug_span("native.skippy_prefill", BTreeMap::new(), 1, 2); + })); + (blocking, trace_context::current_frame()) + }; + blocking.await.expect("blocking work"); + let scheduler = telemetry.clone(); + thread::spawn(move || { + let _origin = origin.as_ref().map(Frame::enter); + scheduler.emit_debug_span("native.skippy_decode", BTreeMap::new(), 3, 4); + }) + .join() + .expect("scheduler thread"); + phase.end(); + }) + .await; + request.end(); + + let spans = spans(&rx); + let (request, request_parent) = spans["stage.openai_http_request"]; + let (phase, phase_parent) = spans["stage.openai_generation"]; + assert_eq!(request_parent, Some(root.span_id)); + assert_eq!(phase_parent, Some(request.span_id)); + assert_eq!(spans["native.skippy_prefill"].1, Some(phase.span_id)); + assert_eq!(spans["native.skippy_decode"].1, Some(phase.span_id)); + assert!( + spans + .values() + .all(|(context, _)| context.trace_id == root.trace_id) + ); + } + + #[test] + fn an_unrecorded_span_passes_its_parent_through() { + let (telemetry, rx) = Telemetry::captured(config(), TelemetryLevel::Summary); + let outer = ActiveSpan::start(Some(&telemetry), "stage.outer", SpanLevel::Summary); + let entered = outer.enter(); + let skipped = ActiveSpan::start(Some(&telemetry), "stage.debug_only", SpanLevel::Debug); + let inner = { + let _skipped = skipped.enter(); + ActiveSpan::start(Some(&telemetry), "stage.inner", SpanLevel::Summary) + }; + inner.end(); + skipped.end(); + drop(entered); + outer.end(); + + let spans = spans(&rx); + assert!(!spans.contains_key("stage.debug_only")); + assert_eq!(spans["stage.inner"].1, Some(spans["stage.outer"].0.span_id)); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/gpu_commands.rs b/skippy/crates/skippy-serving/src/telemetry/gpu_commands.rs new file mode 100644 index 0000000000..aa36abd0fb --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/gpu_commands.rs @@ -0,0 +1,471 @@ +//! GPU command buffers as debug spans, each under the native call that +//! submitted it. A command buffer's span runs from the start of its CPU +//! encode to the end of its GPU execution, split into `encode`, `queue` +//! (committed, waiting for the GPU) and `execute` children, which a graph +//! split by op class keeps as attributes instead; `idle` spans +//! mark the gaps where the GPU waited for the host. Runtimes that classify +//! graph nodes add what each command did: attention, mat-muls, recurrent +//! state, KV writes or other work, with the bytes each class's inputs span. + +use std::collections::BTreeMap; +use std::time::Duration; + +use serde_json::{Value, json}; +use skippy_runtime::native_tracing::gpu_commands::{ + GpuCommandTiming, GpuOpClass, GpuOpClasses, drain_gpu_command_timings, +}; + +use super::{ + Telemetry, resource_metrics, + trace_context::{self, Frame}, +}; + +mod attention_path; +mod idle_gaps; + +/// Emit every GPU record queued so far. +pub(super) fn emit_pending(telemetry: &Telemetry) { + if !telemetry.is_debug_enabled() { + return; + } + drain_gpu_command_timings(|timing| emit(telemetry, &timing)); +} + +fn emit(telemetry: &Telemetry, timing: &GpuCommandTiming) { + record_busy(timing); + let prefix = span_prefix(timing.backend); + let frame = Frame::under(trace_context::context_for_tag(timing.tag)); + idle_gaps::emit(telemetry, &prefix, frame.context(), timing); + attention_path::record(&frame, timing); + let (start, end) = span_window(timing); + telemetry.emit_debug_frame_span( + &frame, + &format!("{prefix}.command_buffer"), + attributes(timing), + start, + end, + ); + // A graph split by op class encodes hundreds of command buffers; their + // phases stay attributes so the exporter's queue keeps every command. + if split_by_class(timing) { + return; + } + for (phase, start, end) in phases(timing) { + telemetry.emit_debug_span_under( + frame.context(), + &format!("{prefix}.{phase}"), + BTreeMap::new(), + start, + end, + ); + } +} + +/// Feed the GPU busy and queue-wait gauges. +fn record_busy(timing: &GpuCommandTiming) { + let between = |start: u64, end: u64| { + Duration::from_nanos(if start > 0 && end > start { + end - start + } else { + 0 + }) + }; + let execute = between( + timing.execute_start_unix_nanos, + timing.execute_end_unix_nanos, + ); + resource_metrics::record_gpu_command( + execute, + between( + timing.encode_end_unix_nanos, + timing.execute_start_unix_nanos, + ), + ); + if let Some(classes) = timing.op_classes.as_ref() { + resource_metrics::gpu_op_classes::record(classes, execute); + } +} + +fn split_by_class(timing: &GpuCommandTiming) -> bool { + timing + .op_classes + .as_ref() + .is_some_and(|classes| classes.split_by_class) +} + +/// `mtl` for Metal's `MTL` registry; other backends get their own prefix. +fn span_prefix(backend: &str) -> String { + backend + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '_' + } + }) + .collect() +} + +/// Encode start to execute end, using whichever instants were observed. +fn span_window(timing: &GpuCommandTiming) -> (u64, u64) { + let instants = [ + timing.encode_start_unix_nanos, + timing.encode_end_unix_nanos, + timing.execute_start_unix_nanos, + timing.execute_end_unix_nanos, + ]; + let observed = instants.iter().copied().filter(|&instant| instant > 0); + let start = observed.clone().min().unwrap_or(0); + (start, observed.max().unwrap_or(start)) +} + +/// The observed, non-empty phases of one command buffer, in order. +fn phases(timing: &GpuCommandTiming) -> Vec<(&'static str, u64, u64)> { + [ + ( + "encode", + timing.encode_start_unix_nanos, + timing.encode_end_unix_nanos, + ), + ( + "queue", + timing.encode_end_unix_nanos, + timing.execute_start_unix_nanos, + ), + ( + "execute", + timing.execute_start_unix_nanos, + timing.execute_end_unix_nanos, + ), + ] + .into_iter() + .filter(|&(_, start, end)| start > 0 && end > start) + .collect() +} + +fn millis_between(start: u64, end: u64) -> Option { + (start > 0 && end > 0).then(|| (end as f64 - start as f64) / 1_000_000.0) +} + +fn attributes(timing: &GpuCommandTiming) -> BTreeMap { + let mut attrs = BTreeMap::from([ + ("skippy.gpu.backend".to_string(), json!(timing.backend)), + ( + "skippy.gpu.context_id".to_string(), + json!(timing.context_id), + ), + ( + "skippy.gpu.compute_index".to_string(), + json!(timing.compute_index), + ), + ( + "skippy.gpu.command_index".to_string(), + json!(timing.command_index), + ), + ( + "skippy.gpu.command_count".to_string(), + json!(timing.command_count), + ), + ( + "skippy.gpu.node_count".to_string(), + json!(timing.node_count), + ), + ]); + let durations = [ + ( + "skippy.gpu.encode_ms", + millis_between(timing.encode_start_unix_nanos, timing.encode_end_unix_nanos), + ), + ( + "skippy.gpu.queue_ms", + millis_between( + timing.encode_end_unix_nanos, + timing.execute_start_unix_nanos, + ), + ), + ( + "skippy.gpu.execute_ms", + millis_between( + timing.execute_start_unix_nanos, + timing.execute_end_unix_nanos, + ), + ), + ]; + for (key, value) in durations { + if let Some(value) = value { + attrs.insert(key.to_string(), json!(value)); + } + } + if timing.status != 0 { + attrs.insert("skippy.gpu.status".to_string(), json!(timing.status)); + } + if let Some(classes) = timing.op_classes.as_ref() { + insert_op_classes(&mut attrs, classes); + } + attrs +} + +/// `skippy.gpu.op_class` and, for every class the command holds, its node +/// count and the bytes its inputs span; attention adds its KV shape. +fn insert_op_classes(attrs: &mut BTreeMap, classes: &GpuOpClasses) { + attrs.insert( + "skippy.gpu.op_class".to_string(), + json!(classes.single.map_or("mixed", GpuOpClass::name)), + ); + if let Some(layer) = classes.layer { + attrs.insert("skippy.gpu.layer".to_string(), json!(layer)); + } + if classes.split_by_class { + attrs.insert("skippy.gpu.split_by_class".to_string(), json!(true)); + } + for class in GpuOpClass::ALL { + let nodes = classes.nodes.get(class); + if nodes == 0 { + continue; + } + attrs.insert(format!("skippy.gpu.nodes.{}", class.name()), json!(nodes)); + attrs.insert( + format!("skippy.gpu.input_bytes.{}", class.name()), + json!(classes.bytes.get(class)), + ); + } + if classes.nodes.attention > 0 && classes.attention_kv_cells > 0 { + attrs.extend([ + ( + "skippy.attention.kv_cells".to_string(), + json!(classes.attention_kv_cells), + ), + ( + "skippy.attention.queries".to_string(), + json!(classes.attention_queries), + ), + ( + "skippy.attention.row_list_nodes".to_string(), + json!(classes.attention_row_list_nodes), + ), + ( + "skippy.attention.flash_nodes".to_string(), + json!(classes.attention_flash_nodes), + ), + ]); + } + if let Some(path) = classes.attention_path() { + attrs.insert("skippy.attention.path".to_string(), json!(path.name())); + } + if let Some(states) = classes + .recurrent_states + .filter(|states| states.gathered > 0) + { + attrs.extend([ + ( + "skippy.recurrent.states".to_string(), + json!(states.gathered), + ), + ( + "skippy.recurrent.states_carried".to_string(), + json!(states.carried), + ), + ]); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::telemetry::{TelemetryLevel, capture_stage_config}; + use skippy_runtime::native_tracing::gpu_commands::{PerOpClass, RecurrentStates}; + + fn timing() -> GpuCommandTiming { + GpuCommandTiming { + tag: 0, + backend: "MTL", + context_id: 1, + compute_index: 12, + command_index: 0, + command_count: 3, + node_count: 64, + status: 0, + encode_start_unix_nanos: 1_000_000, + encode_end_unix_nanos: 3_000_000, + execute_start_unix_nanos: 3_500_000, + execute_end_unix_nanos: 9_500_000, + op_classes: None, + } + } + + #[test] + fn a_classified_command_says_what_its_nodes_did() { + let timing = GpuCommandTiming { + op_classes: Some(GpuOpClasses { + single: None, + layer: Some(5), + split_by_class: false, + attention_kv_cells: 4096, + attention_queries: 4, + attention_row_list_nodes: 0, + attention_flash_nodes: 1, + nodes: PerOpClass { + attention: 1, + matmul: 3, + ..PerOpClass::default() + }, + bytes: PerOpClass { + attention: 1 << 20, + matmul: 1 << 24, + ..PerOpClass::default() + }, + recurrent_states: Some(RecurrentStates::default()), + }), + ..timing() + }; + let attrs = attributes(&timing); + assert_eq!(attrs["skippy.gpu.op_class"], json!("mixed")); + assert_eq!(attrs["skippy.gpu.layer"], json!(5)); + assert_eq!(attrs["skippy.gpu.nodes.matmul"], json!(3)); + assert_eq!(attrs["skippy.gpu.input_bytes.attention"], json!(1 << 20)); + assert_eq!(attrs["skippy.attention.kv_cells"], json!(4096)); + assert_eq!(attrs["skippy.attention.row_list_nodes"], json!(0)); + assert_eq!(attrs["skippy.attention.path"], json!("flash")); + assert!(!attrs.contains_key("skippy.gpu.nodes.recurrent")); + assert!(!attrs.contains_key("skippy.gpu.split_by_class")); + assert!(!attrs.contains_key("skippy.recurrent.states")); + } + + #[test] + fn a_command_with_recurrent_state_says_how_many_states_it_moved() { + let mut timing = timing(); + timing.op_classes = Some(GpuOpClasses { + single: Some(GpuOpClass::Recurrent), + layer: Some(1), + split_by_class: false, + attention_kv_cells: 0, + attention_queries: 0, + attention_row_list_nodes: 0, + attention_flash_nodes: 0, + nodes: PerOpClass::default(), + bytes: PerOpClass::default(), + recurrent_states: Some(RecurrentStates { + gathered: 9, + carried: 5, + }), + }); + let attrs = attributes(&timing); + assert_eq!(attrs["skippy.recurrent.states"], json!(9)); + assert_eq!(attrs["skippy.recurrent.states_carried"], json!(5)); + } + + #[test] + fn spans_are_named_after_the_backend() { + assert_eq!(span_prefix("MTL"), "mtl"); + assert_eq!(span_prefix("Vulkan 1"), "vulkan_1"); + } + + #[test] + fn a_command_buffer_covers_its_encode_queue_and_execution() { + let timing = timing(); + assert_eq!(span_window(&timing), (1_000_000, 9_500_000)); + assert_eq!( + phases(&timing), + vec![ + ("encode", 1_000_000, 3_000_000), + ("queue", 3_000_000, 3_500_000), + ("execute", 3_500_000, 9_500_000), + ] + ); + let attrs = attributes(&timing); + assert_eq!(attrs["skippy.gpu.encode_ms"], json!(2.0)); + assert_eq!(attrs["skippy.gpu.queue_ms"], json!(0.5)); + assert_eq!(attrs["skippy.gpu.execute_ms"], json!(6.0)); + assert_eq!(attrs["skippy.gpu.compute_index"], json!(12)); + assert!(!attrs.contains_key("skippy.gpu.status")); + } + + #[test] + fn a_failed_buffer_keeps_only_its_encode() { + let timing = GpuCommandTiming { + status: 5, + execute_start_unix_nanos: 0, + execute_end_unix_nanos: 0, + ..timing() + }; + assert_eq!(span_window(&timing), (1_000_000, 3_000_000)); + assert_eq!(phases(&timing), vec![("encode", 1_000_000, 3_000_000)]); + let attrs = attributes(&timing); + assert_eq!(attrs["skippy.gpu.status"], json!(5)); + assert!(!attrs.contains_key("skippy.gpu.execute_ms")); + } + + #[test] + fn phases_nest_under_the_command_buffer_under_the_call() { + let (telemetry, rx) = Telemetry::captured(capture_stage_config(), TelemetryLevel::Debug); + let call = Frame::child(); + emit( + &telemetry, + &GpuCommandTiming { + tag: call.tag(), + ..timing() + }, + ); + let spans = rx + .try_iter() + .map(|event| (event.event, event.span.expect("a span"))) + .collect::>(); + let names = spans + .iter() + .map(|(name, _)| name.as_str()) + .collect::>(); + assert_eq!( + names, + [ + "mtl.command_buffer", + "mtl.encode", + "mtl.queue", + "mtl.execute" + ] + ); + let (buffer, buffer_parent) = spans[0].1; + assert_eq!(buffer_parent, Some(call.context().span_id)); + for (_, (_, parent)) in &spans[1..] { + assert_eq!(*parent, Some(buffer.span_id)); + } + } + + #[test] + fn a_command_split_by_class_keeps_its_phases_as_attributes() { + let (telemetry, rx) = Telemetry::captured(capture_stage_config(), TelemetryLevel::Debug); + emit( + &telemetry, + &GpuCommandTiming { + op_classes: Some(GpuOpClasses { + single: Some(GpuOpClass::Matmul), + layer: Some(3), + split_by_class: true, + attention_kv_cells: 0, + attention_queries: 0, + attention_row_list_nodes: 0, + attention_flash_nodes: 0, + nodes: PerOpClass { + matmul: 2, + ..PerOpClass::default() + }, + bytes: PerOpClass { + matmul: 1 << 20, + ..PerOpClass::default() + }, + recurrent_states: None, + }), + ..timing() + }, + ); + let events = rx.try_iter().collect::>(); + assert_eq!( + events + .iter() + .map(|event| event.event.as_str()) + .collect::>(), + ["mtl.command_buffer"] + ); + assert_eq!(events[0].attributes["skippy.gpu.execute_ms"], json!(6.0)); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/gpu_commands/attention_path.rs b/skippy/crates/skippy-serving/src/telemetry/gpu_commands/attention_path.rs new file mode 100644 index 0000000000..4569824b50 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/gpu_commands/attention_path.rs @@ -0,0 +1,157 @@ +//! Events from what GPU commands report about their graph nodes: +//! `skippy.attention.path` when a backend's attention is first seen and +//! whenever it switches between row lists, flash attention over the whole +//! K/V span and unfused attention, and `skippy.gpu.op_profiling` once per +//! backend that splits graphs by op class. + +use std::sync::{Mutex, PoisonError}; + +use skippy_runtime::native_tracing::gpu_commands::{AttentionPath, GpuCommandTiming}; + +use super::super::{ + log_events::{self, AttentionPathSeen, GpuOpProfiling}, + trace_context::Frame, +}; + +#[derive(Debug, Default)] +struct PathTracker { + /// Each backend's latest attention path. + attention: Vec<(&'static str, AttentionPath)>, + profiling: Vec<&'static str>, +} + +impl PathTracker { + fn observe( + &mut self, + timing: &GpuCommandTiming, + ) -> (Option, Option) { + let Some(classes) = timing.op_classes else { + return (None, None); + }; + let profiling = + (classes.split_by_class && !self.profiling.contains(&timing.backend)).then(|| { + self.profiling.push(timing.backend); + GpuOpProfiling { + backend: timing.backend, + } + }); + let Some(path) = classes + .attention_path() + .filter(|_| classes.attention_kv_cells > 0) + else { + return (None, profiling); + }; + let changed = match self + .attention + .iter_mut() + .find(|(backend, _)| *backend == timing.backend) + { + Some((_, seen)) if *seen == path => false, + Some((_, seen)) => { + *seen = path; + true + } + None => { + self.attention.push((timing.backend, path)); + true + } + }; + let seen = AttentionPathSeen { + backend: timing.backend, + path, + kv_cells: classes.attention_kv_cells, + queries: classes.attention_queries, + }; + (changed.then_some(seen), profiling) + } +} + +static TRACKER: Mutex = Mutex::new(PathTracker { + attention: Vec::new(), + profiling: Vec::new(), +}); + +/// Record the events `timing` implies, under `frame`: the call that +/// submitted its work. +pub(super) fn record(frame: &Frame, timing: &GpuCommandTiming) { + if !log_events::enabled() { + return; + } + let (path, profiling) = TRACKER + .lock() + .unwrap_or_else(PoisonError::into_inner) + .observe(timing); + if let Some(profiling) = profiling { + log_events::record_under(frame, &profiling); + } + if let Some(path) = path { + log_events::record_under(frame, &path); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_runtime::native_tracing::gpu_commands::{GpuOpClass, GpuOpClasses, PerOpClass}; + + fn command( + row_list_nodes: u32, + flash_nodes: u32, + kv_cells: u32, + split: bool, + ) -> GpuCommandTiming { + GpuCommandTiming { + tag: 0, + backend: "MTL", + context_id: 1, + compute_index: 1, + command_index: 0, + command_count: 1, + node_count: 4, + status: 0, + encode_start_unix_nanos: 0, + encode_end_unix_nanos: 0, + execute_start_unix_nanos: 1, + execute_end_unix_nanos: 2, + op_classes: Some(GpuOpClasses { + single: Some(GpuOpClass::Attention), + layer: Some(3), + split_by_class: split, + attention_kv_cells: kv_cells, + attention_queries: 4, + attention_row_list_nodes: row_list_nodes, + attention_flash_nodes: flash_nodes, + nodes: PerOpClass { + attention: 1, + ..PerOpClass::default() + }, + bytes: PerOpClass::default(), + recurrent_states: None, + }), + } + } + + #[test] + fn the_path_is_reported_when_first_seen_and_when_it_switches() { + let mut tracker = PathTracker::default(); + let (first, _) = tracker.observe(&command(1, 1, 512, false)); + assert_eq!(first.map(|seen| seen.path), Some(AttentionPath::RowLists)); + assert_eq!(tracker.observe(&command(1, 1, 600, false)).0, None); + let (flash, _) = tracker.observe(&command(0, 1, 4096, false)); + assert_eq!( + flash.map(|seen| (seen.path, seen.kv_cells)), + Some((AttentionPath::Flash, 4096)) + ); + let (unfused, _) = tracker.observe(&command(0, 0, 4096, false)); + assert_eq!(unfused.map(|seen| seen.path), Some(AttentionPath::Unfused)); + assert_eq!(tracker.observe(&command(0, 0, 0, false)).0, None); + } + + #[test] + fn profiling_is_reported_once_per_backend() { + let mut tracker = PathTracker::default(); + assert!(tracker.observe(&command(1, 1, 512, true)).1.is_some()); + assert!(tracker.observe(&command(1, 1, 512, true)).1.is_none()); + assert!(tracker.observe(&command(1, 1, 512, false)).1.is_none()); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/gpu_commands/idle_gaps.rs b/skippy/crates/skippy-serving/src/telemetry/gpu_commands/idle_gaps.rs new file mode 100644 index 0000000000..8e0746f215 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/gpu_commands/idle_gaps.rs @@ -0,0 +1,175 @@ +//! The GPU's idle stretches between command buffers, as `.idle` +//! spans under the call whose work ended the wait. An idle stretch inside +//! one graph compute means the host encoded slower than the GPU ran; one +//! between graph computes is host work between steps, such as sampling, +//! scheduling or building the next graph. + +use std::collections::BTreeMap; +use std::sync::{Mutex, PoisonError}; + +use serde_json::{Value, json}; +use skippy_runtime::native_tracing::gpu_commands::GpuCommandTiming; + +use super::super::{Telemetry, trace_context::SpanContext}; + +/// Shorter gaps are command scheduling, not the GPU waiting for the host. +const MIN_IDLE_NANOS: u64 = 50_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct LastCommand { + backend: &'static str, + context_id: u32, + compute_index: u32, + execute_end: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct IdleGap { + start: u64, + end: u64, + within_graph: bool, + previous_compute_index: u32, +} + +/// The latest execution end on each backend. Every context on a backend +/// shares its device, so the device is idle only between all of them. +#[derive(Debug, Default)] +struct IdleTracker { + last: Vec, +} + +impl IdleTracker { + /// The idle stretch that ended when `timing` started executing, if long + /// enough to report. Records arrive as the device completes them. + fn observe(&mut self, timing: &GpuCommandTiming) -> Option { + let (start, end) = ( + timing.execute_start_unix_nanos, + timing.execute_end_unix_nanos, + ); + if start == 0 || end < start { + return None; + } + let this = LastCommand { + backend: timing.backend, + context_id: timing.context_id, + compute_index: timing.compute_index, + execute_end: end, + }; + let Some(last) = self + .last + .iter_mut() + .find(|last| last.backend == timing.backend) + else { + self.last.push(this); + return None; + }; + let previous = *last; + if end > previous.execute_end { + *last = this; + } + (start >= previous.execute_end.saturating_add(MIN_IDLE_NANOS)).then_some(IdleGap { + start: previous.execute_end, + end: start, + within_graph: previous.context_id == timing.context_id + && previous.compute_index == timing.compute_index, + previous_compute_index: previous.compute_index, + }) + } +} + +static TRACKER: Mutex = Mutex::new(IdleTracker { last: Vec::new() }); + +/// Emit the idle span `timing` ended, under `parent`. +pub(super) fn emit( + telemetry: &Telemetry, + prefix: &str, + parent: SpanContext, + timing: &GpuCommandTiming, +) { + let gap = TRACKER + .lock() + .unwrap_or_else(PoisonError::into_inner) + .observe(timing); + if let Some(gap) = gap { + telemetry.emit_debug_span_under( + parent, + &format!("{prefix}.idle"), + attributes(&gap, timing), + gap.start, + gap.end, + ); + } +} + +fn attributes(gap: &IdleGap, timing: &GpuCommandTiming) -> BTreeMap { + BTreeMap::from([ + ( + "skippy.gpu.idle_ms".to_string(), + json!((gap.end - gap.start) as f64 / 1e6), + ), + ( + "skippy.gpu.idle_kind".to_string(), + json!(if gap.within_graph { + "within_graph" + } else { + "between_graphs" + }), + ), + ( + "skippy.gpu.compute_index".to_string(), + json!(timing.compute_index), + ), + ( + "skippy.gpu.previous_compute_index".to_string(), + json!(gap.previous_compute_index), + ), + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn command(compute_index: u32, start: u64, end: u64) -> GpuCommandTiming { + GpuCommandTiming { + tag: 0, + backend: "MTL", + context_id: 1, + compute_index, + command_index: 0, + command_count: 2, + node_count: 10, + status: 0, + encode_start_unix_nanos: 0, + encode_end_unix_nanos: 0, + execute_start_unix_nanos: start, + execute_end_unix_nanos: end, + op_classes: None, + } + } + + #[test] + fn gaps_between_and_within_graphs_are_told_apart() { + let mut tracker = IdleTracker::default(); + assert_eq!(tracker.observe(&command(1, 1_000_000, 2_000_000)), None); + let within = tracker + .observe(&command(1, 2_400_000, 3_000_000)) + .expect("within"); + assert!(within.within_graph); + assert_eq!((within.start, within.end), (2_000_000, 2_400_000)); + let between = tracker + .observe(&command(2, 5_000_000, 6_000_000)) + .expect("between"); + assert!(!between.within_graph); + assert_eq!(between.previous_compute_index, 1); + } + + #[test] + fn short_and_overlapping_gaps_are_not_idle() { + let mut tracker = IdleTracker::default(); + tracker.observe(&command(1, 1_000_000, 2_000_000)); + assert_eq!(tracker.observe(&command(1, 2_010_000, 3_000_000)), None); + assert_eq!(tracker.observe(&command(1, 2_500_000, 2_900_000)), None); + assert_eq!(tracker.observe(&command(1, 0, 0)), None); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/log_events.rs b/skippy/crates/skippy-serving/src/telemetry/log_events.rs new file mode 100644 index 0000000000..645b319127 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/log_events.rs @@ -0,0 +1,192 @@ +//! Log-based events: OTLP log records with an event name, correlated with the +//! span active when they happen, as OpenTelemetry's event conventions define +//! them. An event marks a moment: a checkpoint, a state change or an outcome +//! inside a longer operation. Work with a duration stays a span, and facts +//! about a whole operation stay span attributes. +//! +//! [`Event`] types defined here carry their name, default severity and +//! attributes together, so one name always means one structure. The point +//! events [`Telemetry::emit`] records on spans are also sent here, under +//! their existing names. Events go to the OTLP endpoint traces use and, when +//! `SKIPPY_TELEMETRY_OTLP_LOGS_FILE` names a file, to that file as OTLP/JSON +//! lines. With neither, nothing is collected. + +use std::{ + collections::BTreeMap, + env, + sync::{ + Arc, OnceLock, + atomic::{AtomicBool, Ordering}, + }, +}; + +use serde_json::Value; +use skippy_protocol::StageConfig; + +use super::{ + Telemetry, TelemetryLevel, now_unix_nanos, + trace_context::{self, Frame}, +}; + +mod catalogue; +mod otlp_logs; + +pub(crate) use catalogue::*; +use otlp_logs::LogSinks; + +/// Where events are appended, one OTLP/JSON request per line. +pub(super) const LOGS_FILE_ENV: &str = "SKIPPY_TELEMETRY_OTLP_LOGS_FILE"; + +/// OpenTelemetry severity numbers; semantic conventions define no severity +/// text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Severity { + Info, + Warn, + Error, +} + +impl Severity { + fn number(self) -> i32 { + match self { + Self::Info => 9, + Self::Warn => 13, + Self::Error => 17, + } + } +} + +/// An event this crate defines. The name identifies the attributes, which +/// [`Event::attributes`] builds from the type's fields. +pub(crate) trait Event { + const NAME: &'static str; + const SEVERITY: Severity; + fn attributes(&self) -> BTreeMap; +} + +struct EventLog { + config: Arc, + sinks: LogSinks, +} + +static LOG: OnceLock = OnceLock::new(); + +/// Start collecting events for the process, if there is anywhere to send +/// them. The first handle with a destination serves the whole process. +pub(super) fn start(telemetry: &Telemetry, endpoint: Option<&str>) { + if telemetry.level == TelemetryLevel::Off || LOG.get().is_some() { + return; + } + let Some(sinks) = LogSinks::open( + env::var_os(LOGS_FILE_ENV).filter(|path| !path.is_empty()), + endpoint, + ) else { + return; + }; + let _ = LOG.set(EventLog { + config: telemetry.config.clone(), + sinks, + }); +} + +pub(super) fn finish() { + if let Some(log) = LOG.get() { + log.sinks.flush(); + } +} + +/// Whether events reach anything; callers skip building attributes when not. +pub(crate) fn enabled() -> bool { + LOG.get().is_some() +} + +static SERVING: AtomicBool = AtomicBool::new(false); + +/// The model is loaded and requests may run: native work from here on +/// stalls serving rather than startup. +pub(crate) fn mark_serving() { + SERVING.store(true, Ordering::Release); +} + +pub(crate) fn serving() -> bool { + SERVING.load(Ordering::Acquire) +} + +/// Record `event` under the span active on this thread or task. +pub(crate) fn record(event: &E) { + if enabled() { + record_under(&trace_context::current_frame_or_root(), event); + } +} + +/// Record `event` under `frame`, which need not be active: work reported +/// after the fact, such as a GPU command, belongs to the call that caused it. +pub(crate) fn record_under(frame: &Frame, event: &E) { + if let Some(log) = LOG.get() { + log.send(frame, E::NAME, E::SEVERITY, event.attributes()); + } +} + +impl EventLog { + fn send( + &self, + frame: &Frame, + name: &str, + severity: Severity, + attributes: BTreeMap, + ) { + let time = u64::try_from(now_unix_nanos()).unwrap_or_default(); + self.sinks.send( + &self.config, + otlp_logs::record(frame.context(), name, severity, attributes, time), + ); + } +} + +/// Send a point event recorded through [`Telemetry::emit`] as a log-based +/// event too, under the frame it was recorded on. +pub(super) fn record_point_event(frame: &Frame, name: &str, attributes: &BTreeMap) { + if let Some(log) = LOG.get() { + log.send(frame, name, point_event_severity(name), attributes.clone()); + } +} + +/// Point events report outcomes at info, except the failures among them. +fn point_event_severity(name: &str) -> Severity { + match name { + "stage.scheduler_worker_panic" | "stage.connection_worker_panic" => Severity::Error, + "stage.binary_connection_error" + | "stage.connection_admission_rejected" + | "stage.openai_downstream_lane_return_failed" + | "stage.openai_linear_proposal_discard_failed" => Severity::Warn, + _ => Severity::Info, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn severities_are_opentelemetry_numbers() { + assert_eq!(Severity::Info.number(), 9); + assert_eq!(Severity::Warn.number(), 13); + assert_eq!(Severity::Error.number(), 17); + } + + #[test] + fn failures_among_point_events_are_not_info() { + assert_eq!( + point_event_severity("stage.scheduler_worker_panic"), + Severity::Error + ); + assert_eq!( + point_event_severity("stage.binary_connection_error"), + Severity::Warn + ); + assert_eq!( + point_event_severity("stage.openai_server_start"), + Severity::Info + ); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/log_events/catalogue.rs b/skippy/crates/skippy-serving/src/telemetry/log_events/catalogue.rs new file mode 100644 index 0000000000..d51bd0cd03 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/log_events/catalogue.rs @@ -0,0 +1,238 @@ +//! The events skippy defines. Each type fixes its event name, its default +//! severity and its attributes, as OpenTelemetry's event conventions +//! require: one name, one structure. `skippy/docs/TELEMETRY_EVENTS.md` +//! describes each event and when it fires. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use skippy_runtime::native_tracing::gpu_commands::AttentionPath; + +use super::{Event, Severity}; + +/// A tier of the KV prefix cache: L1 is the resident radix cache, L2 the +/// host-RAM mirror of L3 fills, L3 the durable store. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum KvTier { + L1, + L2, + L3, +} + +impl KvTier { + fn name(self) -> &'static str { + match self { + Self::L1 => "l1", + Self::L2 => "l2", + Self::L3 => "l3", + } + } +} + +fn attrs(pairs: [(&str, Value); N]) -> BTreeMap { + pairs + .into_iter() + .map(|(key, value)| (key.to_string(), value)) + .collect() +} + +/// `skippy.kv.lookup`: a prefix lookup at one tier found reusable state or +/// did not. A hit carries how many prompt tokens it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct KvLookup { + pub(crate) tier: KvTier, + /// `Some(tokens)` for a hit; `None` for a miss. + pub(crate) matched_tokens: Option, +} + +impl Event for KvLookup { + const NAME: &'static str = "skippy.kv.lookup"; + const SEVERITY: Severity = Severity::Info; + + fn attributes(&self) -> BTreeMap { + let mut attributes = attrs([ + ("skippy.kv.tier", json!(self.tier.name())), + ( + "skippy.kv.result", + json!(if self.matched_tokens.is_some() { + "hit" + } else { + "miss" + }), + ), + ]); + if let Some(tokens) = self.matched_tokens { + attributes.insert("skippy.kv.matched_tokens".to_string(), json!(tokens)); + } + attributes + } +} + +/// `skippy.kv.eviction`: a tier released cached prefixes to make room. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct KvEviction { + pub(crate) tier: KvTier, + pub(crate) entries: u64, + pub(crate) tokens: u64, +} + +impl Event for KvEviction { + const NAME: &'static str = "skippy.kv.eviction"; + const SEVERITY: Severity = Severity::Info; + + fn attributes(&self) -> BTreeMap { + attrs([ + ("skippy.kv.tier", json!(self.tier.name())), + ("skippy.kv.evicted_entries", json!(self.entries)), + ("skippy.kv.evicted_tokens", json!(self.tokens)), + ]) + } +} + +/// `skippy.kv.admission_shortfall`: a request was admitted below the KV +/// pool's free-space watermark, after every releasable prefix was evicted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct KvAdmissionShortfall { + pub(crate) deficit_tokens: u64, +} + +impl Event for KvAdmissionShortfall { + const NAME: &'static str = "skippy.kv.admission_shortfall"; + const SEVERITY: Severity = Severity::Warn; + + fn attributes(&self) -> BTreeMap { + attrs([("skippy.kv.shortfall_tokens", json!(self.deficit_tokens))]) + } +} + +/// Native work that stalls serving when it happens after the model is +/// ready: each event names one kind, with what it worked on and how long +/// it took. +macro_rules! native_stall_event { + ($(#[$doc:meta])* $type:ident, $name:literal) => { + $(#[$doc])* + #[derive(Clone, Debug, PartialEq)] + pub(crate) struct $type { + pub(crate) detail: Option, + pub(crate) duration_ms: f64, + } + + impl Event for $type { + const NAME: &'static str = $name; + const SEVERITY: Severity = Severity::Warn; + + fn attributes(&self) -> BTreeMap { + let mut attributes = attrs([("skippy.native.duration_ms", json!(self.duration_ms))]); + if let Some(detail) = &self.detail { + attributes.insert("skippy.native.detail".to_string(), json!(detail)); + } + attributes + } + } + }; +} + +native_stall_event!( + /// `skippy.graph.reserved`: the backend scheduler reserved compute + /// buffers again while serving (`llama.sched_reserve`), which blocks + /// the next graph. + GraphReserved, + "skippy.graph.reserved" +); +native_stall_event!( + /// `skippy.gpu.pipeline_compiled`: a GPU kernel pipeline was compiled + /// on first use while serving (`mtl.pipeline_compile`). + PipelineCompiled, + "skippy.gpu.pipeline_compiled" +); +native_stall_event!( + /// `skippy.gpu.buffer_allocated`: a device buffer was allocated while + /// serving (`mtl.buffer_alloc`), such as a grown compute buffer. + BufferAllocated, + "skippy.gpu.buffer_allocated" +); + +/// `skippy.attention.path`: how attention reads the KV cache, when first +/// seen on a backend and whenever it changes: flash attention over each +/// sequence's row list, flash attention over the whole masked K/V span, or +/// unfused attention over the whole span. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct AttentionPathSeen { + pub(crate) backend: &'static str, + pub(crate) path: AttentionPath, + pub(crate) kv_cells: u32, + pub(crate) queries: u32, +} + +impl Event for AttentionPathSeen { + const NAME: &'static str = "skippy.attention.path"; + const SEVERITY: Severity = Severity::Info; + + fn attributes(&self) -> BTreeMap { + attrs([ + ("skippy.gpu.backend", json!(self.backend)), + ("skippy.attention.path", json!(self.path.name())), + ("skippy.attention.kv_cells", json!(self.kv_cells)), + ("skippy.attention.queries", json!(self.queries)), + ]) + } +} + +/// `skippy.gpu.op_profiling`: a backend splits graphs at op class +/// boundaries, so command buffers time each class alone. Totals are +/// inflated; shares are what such a trace measures. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct GpuOpProfiling { + pub(crate) backend: &'static str, +} + +impl Event for GpuOpProfiling { + const NAME: &'static str = "skippy.gpu.op_profiling"; + const SEVERITY: Severity = Severity::Warn; + + fn attributes(&self) -> BTreeMap { + attrs([("skippy.gpu.backend", json!(self.backend))]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_lookup_says_its_tier_result_and_coverage() { + let hit = KvLookup { + tier: KvTier::L3, + matched_tokens: Some(512), + } + .attributes(); + assert_eq!(hit["skippy.kv.tier"], json!("l3")); + assert_eq!(hit["skippy.kv.result"], json!("hit")); + assert_eq!(hit["skippy.kv.matched_tokens"], json!(512)); + let miss = KvLookup { + tier: KvTier::L1, + matched_tokens: None, + } + .attributes(); + assert_eq!(miss["skippy.kv.result"], json!("miss")); + assert!(!miss.contains_key("skippy.kv.matched_tokens")); + } + + #[test] + fn native_stalls_carry_their_detail_when_there_is_one() { + let event = GraphReserved { + detail: Some("ubatch 4".to_string()), + duration_ms: 250.5, + }; + assert_eq!(GraphReserved::NAME, "skippy.graph.reserved"); + assert_eq!( + event.attributes()["skippy.native.detail"], + json!("ubatch 4") + ); + let bare = PipelineCompiled { + detail: None, + duration_ms: 1.0, + }; + assert!(!bare.attributes().contains_key("skippy.native.detail")); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/log_events/otlp_logs.rs b/skippy/crates/skippy-serving/src/telemetry/log_events/otlp_logs.rs new file mode 100644 index 0000000000..f001c674d3 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/log_events/otlp_logs.rs @@ -0,0 +1,228 @@ +//! OTLP encoding of events and their two destinations: a JSON-lines file in +//! the OpenTelemetry file-exporter format, and the OTLP gRPC endpoint traces +//! go to. The gRPC exporter batches whatever is queued into one request. + +use std::{ + collections::BTreeMap, + ffi::OsString, + fs::{File, OpenOptions}, + io::{BufWriter, Write}, + sync::{Mutex, PoisonError}, + time::Duration, +}; + +use opentelemetry_proto::tonic::{ + collector::logs::v1::{ExportLogsServiceRequest, logs_service_client::LogsServiceClient}, + common::v1::InstrumentationScope, + logs::v1::{LogRecord, ResourceLogs, ScopeLogs}, + resource::v1::Resource, +}; +use serde_json::Value; +use skippy_protocol::StageConfig; +use tokio::{sync::mpsc, time::timeout}; + +use super::super::{ + otlp_encoding::key_values, resource_attrs::resource_attrs, trace_context::SpanContext, +}; +use super::Severity; + +const EXPORT_TIMEOUT: Duration = Duration::from_secs(5); +/// Events queued for the gRPC exporter before new ones are dropped. +const GRPC_QUEUE: usize = 1024; +/// Events one gRPC request carries at most. +const GRPC_BATCH: usize = 256; +/// W3C trace flags: sampled. +const SAMPLED: u32 = 1; + +/// One event as an OTLP log record correlated with `context`. +pub(super) fn record( + context: SpanContext, + name: &str, + severity: Severity, + attributes: BTreeMap, + time_unix_nano: u64, +) -> LogRecord { + LogRecord { + time_unix_nano, + observed_time_unix_nano: time_unix_nano, + severity_number: severity.number(), + attributes: key_values(attributes), + flags: SAMPLED, + trace_id: context.trace_id.to_vec(), + span_id: context.span_id.to_vec(), + event_name: name.to_string(), + ..Default::default() + } +} + +fn export_request(config: &StageConfig, records: Vec) -> ExportLogsServiceRequest { + let attributes = resource_attrs(config, "skippy"); + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(Resource { + attributes: key_values(attributes), + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + name: "skippy-serving".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + ..Default::default() + }), + log_records: records, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +pub(super) struct LogSinks { + file: Option>>, + grpc: Option, LogRecord)>>, +} + +impl LogSinks { + /// The configured destinations; `None` when there are none. + pub(super) fn open(path: Option, endpoint: Option<&str>) -> Option { + let file = + path.and_then( + |path| match OpenOptions::new().create(true).append(true).open(&path) { + Ok(file) => Some(Mutex::new(BufWriter::new(file))), + Err(error) => { + tracing::warn!("telemetry events file {path:?} not opened: {error}"); + None + } + }, + ); + let grpc = endpoint.and_then(|endpoint| { + let handle = tokio::runtime::Handle::try_current().ok()?; + let (tx, rx) = mpsc::channel(GRPC_QUEUE); + handle.spawn(export_loop(endpoint.to_string(), rx)); + Some(tx) + }); + (file.is_some() || grpc.is_some()).then_some(Self { file, grpc }) + } + + pub(super) fn send(&self, config: &std::sync::Arc, record: LogRecord) { + if let Some(grpc) = self.grpc.as_ref() { + // A full queue means the endpoint is not keeping up; drop the event. + let _ = grpc.try_send((config.clone(), record.clone())); + } + if let Some(file) = self.file.as_ref() { + let request = export_request(config, vec![record]); + let mut file = file.lock().unwrap_or_else(PoisonError::into_inner); + let written = serde_json::to_writer(&mut *file, &request) + .map_err(std::io::Error::from) + .and_then(|()| file.write_all(b"\n")) + .and_then(|()| file.flush()); + if let Err(error) = written { + tracing::warn!("telemetry events file write failed: {error}"); + } + } + } + + pub(super) fn flush(&self) { + if let Some(file) = self.file.as_ref() { + let _ = file.lock().unwrap_or_else(PoisonError::into_inner).flush(); + } + } +} + +/// Export queued events in batches, reconnecting after a failure; a batch +/// that fails is dropped rather than retried. +async fn export_loop( + endpoint: String, + mut rx: mpsc::Receiver<(std::sync::Arc, LogRecord)>, +) { + let mut client = None; + while let Some((config, first)) = rx.recv().await { + let mut records = vec![first]; + while records.len() < GRPC_BATCH { + match rx.try_recv() { + Ok((_, record)) => records.push(record), + Err(_) => break, + } + } + if client.is_none() { + client = timeout(EXPORT_TIMEOUT, LogsServiceClient::connect(endpoint.clone())) + .await + .ok() + .and_then(Result::ok); + } + let Some(connected) = client.as_mut() else { + continue; + }; + let request = export_request(&config, records); + if !matches!( + timeout(EXPORT_TIMEOUT, connected.export(request)).await, + Ok(Ok(_)) + ) { + client = None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + + fn stage_config() -> std::sync::Arc { + std::sync::Arc::new( + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + })) + .expect("minimal stage config"), + ) + } + + #[test] + fn an_event_is_a_named_log_record_on_its_span() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("events.jsonl"); + let sinks = LogSinks::open(Some(path.clone().into_os_string()), None).expect("file sink"); + let context = SpanContext { + trace_id: [0xab; 16], + span_id: [0xcd; 8], + }; + sinks.send( + &stage_config(), + record( + context, + "skippy.kv.eviction", + Severity::Warn, + BTreeMap::from([("skippy.kv.tier".to_string(), json!("l1"))]), + 42, + ), + ); + sinks.flush(); + + let text = std::fs::read_to_string(&path).expect("events file"); + let request: Value = + serde_json::from_str(text.lines().next().expect("a line")).expect("json"); + let record = &request["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]; + assert_eq!(record["eventName"], "skippy.kv.eviction"); + assert_eq!(record["severityNumber"], json!(13)); + assert_eq!(record["timeUnixNano"], json!("42")); + assert_eq!(record["traceId"], json!("ab".repeat(16))); + assert_eq!(record["spanId"], json!("cd".repeat(8))); + assert_eq!(record["attributes"][0]["key"], "skippy.kv.tier"); + assert_eq!(record["attributes"][0]["value"]["stringValue"], "l1"); + assert!(record.get("body").is_none() || record["body"].is_null()); + } + + #[test] + fn no_destination_means_no_sinks() { + assert!(LogSinks::open(None, None).is_none()); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/native_calls.rs b/skippy/crates/skippy-serving/src/telemetry/native_calls.rs new file mode 100644 index 0000000000..c30e693a37 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/native_calls.rs @@ -0,0 +1,101 @@ +//! Native ABI call timings as debug spans, separating time spent inside the +//! patched llama.cpp runtime from Skippy's own scheduling and bookkeeping. +//! Each call's span id doubles as its native trace tag, so the native spans +//! and GPU command buffers the call causes land under it. + +use std::cell::RefCell; +use std::collections::BTreeMap; + +use serde_json::json; +use skippy_runtime::native_timing::{NativeCall, NativeCallObserver, set_native_call_observer}; +use skippy_runtime::native_tracing::request_native_tracing; + +use super::{Telemetry, gpu_commands, native_spans, trace_context::Frame}; + +thread_local! { + /// Calls begun on this thread and not yet observed, innermost last. + static OPEN_CALLS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +struct NativeCallSpans(Telemetry); + +impl NativeCallObserver for NativeCallSpans { + fn begin(&self, _symbol: &'static str) -> u64 { + let frame = Frame::child(); + let tag = frame.tag(); + OPEN_CALLS.with(|open| open.borrow_mut().push(frame)); + tag + } + + fn observe(&self, call: NativeCall) { + let frame = OPEN_CALLS + .with(|open| { + let mut open = open.borrow_mut(); + let index = open.iter().rposition(|frame| frame.tag() == call.id)?; + Some(open.remove(index)) + }) + .unwrap_or_else(Frame::child); + self.0.emit_debug_frame_span( + &frame, + &span_name(call.symbol), + BTreeMap::from([ + ("skippy.native.symbol".to_string(), json!(call.symbol)), + ( + "thread.name".to_string(), + json!(std::thread::current().name().unwrap_or("unnamed")), + ), + ]), + call.start_unix_nanos, + call.end_unix_nanos, + ); + // The call's native spans have all ended; its GPU work arrives later. + native_spans::emit_pending(&self.0); + gpu_commands::emit_pending(&self.0); + } +} + +fn span_name(symbol: &str) -> String { + format!("native.{symbol}") +} + +/// Report native call timings, and the native spans and GPU work each call +/// causes, through `telemetry`. The first debug handle with a sink serves the +/// whole process. +pub(super) fn install(telemetry: &Telemetry) { + if set_native_call_observer(Box::new(NativeCallSpans(telemetry.clone()))) { + request_native_tracing(); + } +} + +#[cfg(test)] +mod tests { + use super::{NativeCallSpans, span_name}; + use crate::telemetry::{Telemetry, TelemetryLevel, capture_stage_config}; + use skippy_runtime::native_timing::{NativeCall, NativeCallObserver}; + + #[test] + fn spans_are_named_after_the_native_symbol() { + assert_eq!( + span_name("skippy_iteration_batch_sampled"), + "native.skippy_iteration_batch_sampled" + ); + } + + #[test] + fn a_call_span_takes_the_id_its_gpu_work_is_tagged_with() { + let (telemetry, rx) = Telemetry::captured(capture_stage_config(), TelemetryLevel::Debug); + let observer = NativeCallSpans(telemetry); + let tag = observer.begin("skippy_iteration_batch_sampled"); + observer.observe(NativeCall { + symbol: "skippy_iteration_batch_sampled", + id: tag, + start_unix_nanos: 10, + end_unix_nanos: 20, + }); + + let span = rx.try_recv().expect("native span captured"); + assert_eq!(span.event, "native.skippy_iteration_batch_sampled"); + let (context, _) = span.span.expect("an exported span"); + assert_eq!(u64::from_be_bytes(context.span_id), tag); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/native_spans.rs b/skippy/crates/skippy-serving/src/telemetry/native_spans.rs new file mode 100644 index 0000000000..3348ec939f --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/native_spans.rs @@ -0,0 +1,146 @@ +//! Native spans as debug spans: the phases of host work inside each native +//! call (llama graph build, encode, synchronize, sampling, Metal library and +//! pipeline compilation), so a native call's span has no unexplained time. +//! +//! A native span keeps the id the runtime gave it, so its children, which +//! end and arrive first, can already name it as their parent. A span with no +//! native parent sits under the call whose tag it carries, or under the +//! process root when it ran before anything was tagged. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use skippy_runtime::native_tracing::spans::{NativeSpan, drain_native_spans}; + +use super::{ + Telemetry, + log_events::{self, BufferAllocated, GraphReserved, PipelineCompiled}, + trace_context::{self, Frame}, +}; + +/// Emit every native span queued so far. +pub(super) fn emit_pending(telemetry: &Telemetry) { + if !telemetry.is_debug_enabled() { + return; + } + drain_native_spans(|span| { + let frame = frame(&span); + record_stall(&frame, &span); + telemetry.emit_debug_frame_span( + &frame, + span.name, + attributes(&span), + span.start_unix_nanos, + span.end_unix_nanos, + ); + }); +} + +/// Native work that, once the model is serving, stalls the graph behind it +/// also becomes an event on its span. +fn record_stall(frame: &Frame, span: &NativeSpan) { + if !log_events::serving() || !log_events::enabled() { + return; + } + let detail = span.detail.as_deref().map(str::to_string); + let duration_ms = span.end_unix_nanos.saturating_sub(span.start_unix_nanos) as f64 / 1e6; + match span.name { + "llama.sched_reserve" => { + log_events::record_under( + frame, + &GraphReserved { + detail, + duration_ms, + }, + ); + } + "mtl.pipeline_compile" => { + log_events::record_under( + frame, + &PipelineCompiled { + detail, + duration_ms, + }, + ); + } + "mtl.buffer_alloc" => { + log_events::record_under( + frame, + &BufferAllocated { + detail, + duration_ms, + }, + ); + } + _ => {} + } +} + +/// The span's own id, under its native parent or tagged call. +fn frame(span: &NativeSpan) -> Frame { + Frame::tagged_under(trace_context::context_for_tag(span.parent), span.id) +} + +fn attributes(span: &NativeSpan) -> BTreeMap { + let mut attrs = BTreeMap::new(); + if let Some(detail) = span.detail.as_deref() { + attrs.insert("skippy.native.detail".to_string(), json!(detail)); + } + if let Some((name, value)) = span.value { + attrs.insert(format!("skippy.native.{name}"), json!(value)); + } + attrs +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(detail: Option<&str>, value: Option<(&'static str, i64)>) -> NativeSpan { + NativeSpan { + id: (1 << 63) | 3, + parent: 17, + name: "mtl.pipeline_compile", + detail: detail.map(Into::into), + start_unix_nanos: 10, + end_unix_nanos: 20, + value, + } + } + + #[test] + fn a_native_span_keeps_its_id_under_the_call_it_names() { + let call = Frame::child(); + let span = NativeSpan { + parent: call.tag(), + ..sample(None, None) + }; + let native = frame(&span); + assert_eq!(native.tag(), span.id); + assert_eq!(native.parent_span_id(), Some(call.context().span_id)); + + let child = NativeSpan { + id: (1 << 63) | 4, + parent: span.id, + ..span.clone() + }; + assert_eq!( + frame(&child).parent_span_id(), + Some(native.context().span_id) + ); + + let untagged = NativeSpan { parent: 0, ..span }; + assert_eq!( + frame(&untagged).parent_span_id(), + Some(trace_context::process().root().context().span_id) + ); + } + + #[test] + fn attributes_carry_the_detail_and_the_measured_value() { + let attrs = attributes(&sample(Some("kernel_add_fuse_1"), Some(("nodes", 42)))); + assert_eq!(attrs["skippy.native.detail"], json!("kernel_add_fuse_1")); + assert_eq!(attrs["skippy.native.nodes"], json!(42)); + assert!(attributes(&sample(None, None)).is_empty()); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs b/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs new file mode 100644 index 0000000000..cffeac4953 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs @@ -0,0 +1,143 @@ +//! Encoding of Skippy telemetry records as OTLP trace messages. + +use std::{collections::BTreeMap, sync::atomic::Ordering}; + +use opentelemetry_proto::tonic::{ + common::v1::{AnyValue, ArrayValue, InstrumentationScope, KeyValue, KeyValueList, any_value}, + resource::v1::Resource, + trace::v1::{ResourceSpans, ScopeSpans, Span, span}, +}; +use serde_json::{Value, json}; +use skippy_metrics::metric; +use skippy_protocol::StageConfig; + +use super::{ + TelemetryCounters, TelemetryEvent, resource_attrs::resource_attrs, span_components::component, +}; + +/// One stage's spans, one resource per system component (see +/// [`super::span_components`]), so viewers that colour by service tell the +/// parts apart; the spans keep one trace. +pub(super) fn resource_spans_by_component( + config: &StageConfig, + spans: Vec, +) -> Vec { + let mut groups: BTreeMap<&'static str, Vec> = BTreeMap::new(); + for span in spans { + groups.entry(component(&span.name)).or_default().push(span); + } + groups + .into_iter() + .map(|(service, spans)| resource_spans(config, service, spans)) + .collect() +} + +/// Spans of one stage and component under their resource and the serving +/// instrumentation scope. +fn resource_spans(config: &StageConfig, service: &str, spans: Vec) -> ResourceSpans { + let attributes = resource_attrs(config, service); + ResourceSpans { + resource: Some(Resource { + attributes: key_values(attributes), + dropped_attributes_count: 0, + entity_refs: vec![], + }), + scope_spans: vec![ScopeSpans { + scope: Some(InstrumentationScope { + name: "skippy-serving".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + attributes: vec![], + dropped_attributes_count: 0, + }), + spans, + schema_url: String::new(), + }], + schema_url: String::new(), + } +} + +pub(super) fn event_to_span(event: &TelemetryEvent, stats: &TelemetryCounters) -> Span { + let mut attributes = event.attributes.clone(); + attributes.insert( + metric::OTEL_DROPPED_EVENTS.to_string(), + json!(stats.dropped.load(Ordering::Relaxed)), + ); + attributes.insert( + metric::OTEL_EXPORT_ERRORS.to_string(), + json!(stats.export_errors.load(Ordering::Relaxed)), + ); + Span { + trace_id: event.context.trace_id.to_vec(), + span_id: event.context.span_id.to_vec(), + trace_state: String::new(), + parent_span_id: event + .parent + .map(|parent| parent.to_vec()) + .unwrap_or_default(), + flags: 1, + name: event.name.clone(), + kind: span::SpanKind::Internal as i32, + start_time_unix_nano: event.start_time_unix_nanos, + end_time_unix_nano: event.end_time_unix_nanos, + attributes: key_values(attributes), + dropped_attributes_count: 0, + events: event + .events + .iter() + .map(|recorded| span::Event { + time_unix_nano: recorded.time_unix_nanos, + name: recorded.name.clone(), + attributes: key_values(recorded.attributes.clone()), + dropped_attributes_count: 0, + }) + .collect(), + dropped_events_count: 0, + links: event + .links + .iter() + .map(|linked| span::Link { + trace_id: linked.trace_id.to_vec(), + span_id: linked.span_id.to_vec(), + trace_state: String::new(), + attributes: vec![], + dropped_attributes_count: 0, + flags: 1, + }) + .collect(), + dropped_links_count: 0, + status: None, + } +} + +pub(super) fn key_values(attributes: BTreeMap) -> Vec { + attributes + .into_iter() + .map(|(key, value)| KeyValue { + key, + value: Some(json_to_any_value(value)), + ..Default::default() + }) + .collect() +} + +fn json_to_any_value(value: Value) -> AnyValue { + let value = match value { + Value::String(value) => any_value::Value::StringValue(value), + Value::Bool(value) => any_value::Value::BoolValue(value), + Value::Number(value) => { + if let Some(value) = value.as_i64() { + any_value::Value::IntValue(value) + } else { + any_value::Value::DoubleValue(value.as_f64().unwrap_or_default()) + } + } + Value::Array(values) => any_value::Value::ArrayValue(ArrayValue { + values: values.into_iter().map(json_to_any_value).collect(), + }), + Value::Object(values) => any_value::Value::KvlistValue(KeyValueList { + values: key_values(values.into_iter().collect()), + }), + Value::Null => any_value::Value::StringValue(String::new()), + }; + AnyValue { value: Some(value) } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs b/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs new file mode 100644 index 0000000000..05e1464251 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs @@ -0,0 +1,359 @@ +//! OTLP/JSON trace file for offline analysis without a collector. +//! +//! `SKIPPY_TELEMETRY_OTLP_FILE=` appends one `ExportTraceServiceRequest` +//! per line in the OTLP/JSON encoding, the OpenTelemetry file-exporter format +//! that collectors and trace tools ingest directly. One process-wide writer +//! keeps lines whole when several `Telemetry` handles share the file. + +use std::{ + ffi::OsString, + fs::OpenOptions, + io::{self, BufWriter, Write}, + path::{Path, PathBuf}, + sync::{Arc, OnceLock, mpsc as std_mpsc}, + thread::{self, JoinHandle}, + time::Duration, +}; + +use opentelemetry_proto::tonic::{ + collector::trace::v1::ExportTraceServiceRequest, trace::v1::Span, +}; +use skippy_protocol::StageConfig; + +use super::{EXPORT_BATCH_MAX, resource_spans_by_component}; + +const PATH_ENV: &str = "SKIPPY_TELEMETRY_OTLP_FILE"; +const QUEUE_CAPACITY: usize = 8192; + +static SINK: OnceLock> = OnceLock::new(); + +/// The process-wide sink named by `SKIPPY_TELEMETRY_OTLP_FILE`, opened once. +pub(super) fn configured() -> Option<&'static OtlpFileSink> { + SINK.get_or_init(|| { + let path = path_from_value(std::env::var_os(PATH_ENV))?; + OtlpFileSink::open(&path) + .inspect_err(|error| { + tracing::warn!( + "telemetry OTLP file {} is unavailable: {error}", + path.display() + ); + }) + .ok() + }) + .as_ref() +} + +fn path_from_value(value: Option) -> Option { + value.filter(|value| !value.is_empty()).map(PathBuf::from) +} + +pub(super) struct OtlpFileSink { + tx: Option>, + worker: Option>, +} + +struct FileSpan { + config: Arc, + span: Span, +} + +enum FileItem { + Span(Box), + /// Acknowledged once every span queued before it is on disk. + Flush(std_mpsc::SyncSender<()>), +} + +impl OtlpFileSink { + fn open(path: &Path) -> io::Result { + let file = OpenOptions::new().create(true).append(true).open(path)?; + let (tx, rx) = std_mpsc::sync_channel(QUEUE_CAPACITY); + let worker = thread::Builder::new() + .name("skippy-telemetry-otlp-file".to_string()) + .spawn(move || write_loop(&rx, BufWriter::new(file)))?; + Ok(Self { + tx: Some(tx), + worker: Some(worker), + }) + } + + /// Queue one span; false when the queue is full or the writer stopped. + pub(super) fn try_send(&self, config: &Arc, span: Span) -> bool { + self.tx.as_ref().is_some_and(|tx| { + tx.try_send(FileItem::Span(Box::new(FileSpan { + config: config.clone(), + span, + }))) + .is_ok() + }) + } + + /// Block until spans queued so far are written, or `timeout` passes. + pub(super) fn flush(&self, timeout: Duration) { + let Some(tx) = self.tx.as_ref() else { + return; + }; + let (ack, written) = std_mpsc::sync_channel(1); + if tx.send(FileItem::Flush(ack)).is_ok() { + let _ = written.recv_timeout(timeout); + } + } +} + +impl Drop for OtlpFileSink { + fn drop(&mut self) { + self.tx.take(); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +/// Write each drained batch as one flushed line, so a killed server leaves +/// only whole requests behind. +fn write_loop(rx: &std_mpsc::Receiver, mut out: impl Write) { + while let Ok(first) = rx.recv() { + let mut batch = Vec::new(); + let mut acks = Vec::new(); + for item in std::iter::once(first).chain(rx.try_iter().take(EXPORT_BATCH_MAX - 1)) { + match item { + FileItem::Span(span) => batch.push(*span), + FileItem::Flush(ack) => acks.push(ack), + } + } + if !batch.is_empty() + && let Err(error) = write_request(&mut out, &export_request(batch)) + { + tracing::warn!("telemetry OTLP file write failed; file sink stopped: {error}"); + return; + } + acks.into_iter().for_each(|ack| { + let _ = ack.send(()); + }); + } +} + +/// Group consecutive spans of the same stage, then split each group by +/// component, one resource each. +fn export_request(batch: Vec) -> ExportTraceServiceRequest { + let mut groups: Vec<(Arc, Vec)> = Vec::new(); + for FileSpan { config, span } in batch { + match groups.last_mut() { + Some((current, spans)) if Arc::ptr_eq(current, &config) => spans.push(span), + _ => groups.push((config, vec![span])), + } + } + ExportTraceServiceRequest { + resource_spans: groups + .into_iter() + .flat_map(|(config, spans)| resource_spans_by_component(&config, spans)) + .collect(), + } +} + +fn write_request(out: &mut impl Write, request: &ExportTraceServiceRequest) -> io::Result<()> { + serde_json::to_writer(&mut *out, request)?; + out.write_all(b"\n")?; + out.flush() +} + +#[cfg(test)] +mod tests { + use std::{collections::BTreeMap, ffi::OsString, sync::Arc, time::Duration}; + + use serde_json::{Value, json}; + use skippy_protocol::StageConfig; + + use super::{FileItem, FileSpan, OtlpFileSink, path_from_value, write_loop}; + use crate::telemetry::{ + TelemetryCounters, TelemetryEvent, event_to_span, + trace_context::{Frame, SpanEvent}, + }; + + fn config(stage_id: &str) -> Arc { + Arc::new( + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": stage_id, + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + })) + .expect("minimal stage config"), + ) + } + + fn record(frame: &Frame) -> TelemetryEvent { + let attributes = BTreeMap::from([("skippy.scheduler.step_ms".to_string(), json!(2.5))]); + TelemetryEvent::span( + frame, + "stage.scheduler_iteration", + attributes, + 1_000, + 3_500_000, + ) + } + + fn file_span(config: &Arc, record: &TelemetryEvent) -> FileSpan { + FileSpan { + config: config.clone(), + span: event_to_span(record, &TelemetryCounters::default()), + } + } + + fn written_lines(spans: Vec) -> Vec { + let (tx, rx) = std::sync::mpsc::sync_channel(spans.len()); + spans + .into_iter() + .for_each(|span| tx.send(FileItem::Span(Box::new(span))).expect("queue span")); + drop(tx); + let mut out = Vec::new(); + write_loop(&rx, &mut out); + String::from_utf8(out) + .expect("utf8 output") + .lines() + .map(|line| serde_json::from_str(line).expect("one JSON request per line")) + .collect() + } + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() + } + + #[test] + fn writes_otlp_json_with_hex_ids_and_string_nanos() { + let stage = config("stage-0"); + let frame = Frame::child(); + let lines = written_lines(vec![ + file_span(&stage, &record(&frame)), + file_span(&stage, &record(&Frame::child())), + ]); + + assert_eq!(lines.len(), 1); + let spans = &lines[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]; + assert_eq!(spans.as_array().map(Vec::len), Some(2)); + let span = &spans[0]; + assert_eq!(span["name"], "stage.scheduler_iteration"); + assert_eq!(span["spanId"], hex(&frame.context().span_id)); + assert_eq!(span["traceId"], hex(&frame.context().trace_id)); + assert_eq!(span["startTimeUnixNano"], "1000"); + assert_eq!(span["endTimeUnixNano"], "3500000"); + assert_eq!( + lines[0]["resourceSpans"][0]["scopeSpans"][0]["scope"]["name"], + "skippy-serving" + ); + } + + #[test] + fn parents_links_and_events_are_encoded() { + let parent = Frame::child(); + let _entered = parent.enter(); + let child = Frame::child(); + let linked = Frame::child(); + let mut traced = record(&child); + traced.links = vec![linked.context()]; + traced.events = vec![SpanEvent { + name: "stage.openai_kv_lookup_decision".to_string(), + time_unix_nanos: 2_000, + attributes: BTreeMap::from([("skippy.kv.decision".to_string(), json!("hit"))]), + }]; + + let lines = written_lines(vec![file_span(&config("stage-0"), &traced)]); + let span = &lines[0]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]; + assert_eq!(span["parentSpanId"], hex(&parent.context().span_id)); + assert_eq!(span["links"][0]["spanId"], hex(&linked.context().span_id)); + assert_eq!(span["events"][0]["name"], "stage.openai_kv_lookup_decision"); + assert_eq!(span["events"][0]["timeUnixNano"], "2000"); + } + + #[test] + fn separate_stages_keep_separate_resources() { + let (first, second) = (config("stage-0"), config("stage-1")); + let lines = written_lines(vec![ + file_span(&first, &record(&Frame::child())), + file_span(&second, &record(&Frame::child())), + file_span(&first, &record(&Frame::child())), + ]); + + assert_eq!(lines[0]["resourceSpans"].as_array().map(Vec::len), Some(3)); + } + + #[test] + fn each_component_gets_its_own_service() { + let stage = config("stage-0"); + let call = Frame::child(); + let mut native = record(&call); + native.name = "llama.graph_compute".to_string(); + let lines = written_lines(vec![ + file_span(&stage, &record(&Frame::child())), + file_span(&stage, &native), + ]); + + let resources = lines[0]["resourceSpans"].as_array().expect("resources"); + let services = resources + .iter() + .map(|resource| { + let attributes = resource["resource"]["attributes"] + .as_array() + .expect("attributes"); + let value = |key: &str| { + attributes + .iter() + .find(|attribute| attribute["key"] == key) + .map(|attribute| attribute["value"]["stringValue"].clone()) + }; + assert_eq!(value("service.namespace"), Some(json!("skippy"))); + ( + value("service.name").expect("service.name"), + resource["scopeSpans"][0]["spans"][0]["name"].clone(), + ) + }) + .collect::>(); + assert_eq!( + services, + [ + (json!("llama"), json!("llama.graph_compute")), + ( + json!("skippy-scheduler"), + json!("stage.scheduler_iteration") + ), + ] + ); + } + + #[test] + fn empty_path_disables_the_sink() { + assert_eq!(path_from_value(None), None); + assert_eq!(path_from_value(Some(OsString::new())), None); + assert_eq!( + path_from_value(Some(OsString::from("/tmp/trace.jsonl"))), + Some("/tmp/trace.jsonl".into()) + ); + } + + #[test] + fn flush_returns_once_queued_spans_are_on_disk() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("trace.otlp.jsonl"); + std::fs::write(&path, "{\"resourceSpans\":[]}\n").expect("seed existing line"); + let sink = OtlpFileSink::open(&path).expect("open sink"); + let frame = Frame::child(); + let FileSpan { config, span } = file_span(&config("stage-0"), &record(&frame)); + assert!(sink.try_send(&config, span)); + + sink.flush(Duration::from_secs(5)); + + let text = std::fs::read_to_string(&path).expect("read trace file"); + let lines = text.lines().collect::>(); + assert_eq!(lines.len(), 2, "appends after existing content"); + let request: Value = serde_json::from_str(lines[1]).expect("JSON request"); + assert_eq!( + request["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["spanId"], + hex(&frame.context().span_id) + ); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs new file mode 100644 index 0000000000..8e8a69a6b5 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs @@ -0,0 +1,163 @@ +//! The resource every signal carries: the stage's lifecycle attributes, the +//! serving configuration that changes what the GPU does (KV precision, flash +//! attention, context, lanes, batch sizes), and whatever the operator set in +//! `OTEL_RESOURCE_ATTRIBUTES`, so runs with different settings can be told +//! apart and compared from their telemetry alone. + +use std::{collections::BTreeMap, env, sync::OnceLock}; + +use serde_json::{Value, json}; +use skippy_protocol::StageConfig; + +use super::{lifecycle_attrs, span_components::SERVICE_NAMESPACE}; + +/// The standard OpenTelemetry variable for extra resource attributes. +const RESOURCE_ATTRIBUTES_ENV: &str = "OTEL_RESOURCE_ATTRIBUTES"; + +/// Resource attributes for `service`. Operator attributes come first, so the +/// stage's own identity and configuration win over a conflicting key. +pub(super) fn resource_attrs(config: &StageConfig, service: &str) -> BTreeMap { + let mut attributes = operator_attributes() + .iter() + .map(|(key, value)| (key.clone(), json!(value))) + .collect::>(); + attributes.extend(lifecycle_attrs(config)); + attributes.extend(serving_config_attrs(config)); + attributes.insert("service.name".to_string(), json!(service)); + attributes.insert("service.namespace".to_string(), json!(SERVICE_NAMESPACE)); + attributes +} + +/// The settings that decide which kernels run and how much KV they read. +fn serving_config_attrs(config: &StageConfig) -> BTreeMap { + let mut attributes = BTreeMap::from([ + ( + "skippy.kv.cache_type_k".to_string(), + json!(config.cache_type_k), + ), + ( + "skippy.kv.cache_type_v".to_string(), + json!(config.cache_type_v), + ), + ( + "skippy.attention.flash".to_string(), + serde_json::to_value(config.flash_attn_type).unwrap_or(Value::Null), + ), + ("skippy.kv.ctx_size".to_string(), json!(config.ctx_size)), + ( + "skippy.scheduler.lanes".to_string(), + json!(config.lane_count), + ), + ]); + let optional = [ + ("skippy.batch.size", config.n_batch.map(Value::from)), + ("skippy.batch.ubatch_size", config.n_ubatch.map(Value::from)), + ("skippy.kv.unified", config.kv_unified.map(Value::from)), + ("skippy.kv.offload", config.kv_offload.map(Value::from)), + ("skippy.kv.swa_full", config.swa_full.map(Value::from)), + ]; + attributes.extend( + optional + .into_iter() + .filter_map(|(key, value)| Some((key.to_string(), value?))), + ); + attributes +} + +fn operator_attributes() -> &'static [(String, String)] { + static PARSED: OnceLock> = OnceLock::new(); + PARSED.get_or_init(|| { + env::var(RESOURCE_ATTRIBUTES_ENV) + .map(|value| parse_resource_attributes(&value)) + .unwrap_or_default() + }) +} + +/// `key=value` pairs separated by commas, values percent-encoded, as the +/// OpenTelemetry SDK environment specification defines; malformed entries +/// are skipped. +fn parse_resource_attributes(value: &str) -> Vec<(String, String)> { + value + .split(',') + .filter_map(|entry| { + let (key, value) = entry.split_once('=')?; + let key = key.trim(); + (!key.is_empty()).then(|| (key.to_string(), percent_decode(value.trim()))) + }) + .collect() +} + +fn percent_decode(value: &str) -> String { + let bytes = value.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut rest = bytes; + while let Some((&first, tail)) = rest.split_first() { + let escaped = (first == b'%') + .then(|| tail.get(..2)) + .flatten() + .and_then(|hex| u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()); + match escaped { + Some(byte) => { + decoded.push(byte); + rest = &tail[2..]; + } + None => { + decoded.push(first); + rest = tail; + } + } + } + String::from_utf8_lossy(&decoded).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stage_config() -> StageConfig { + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + "cache_type_k": "q8_0", + "cache_type_v": "q8_0", + "flash_attn_type": "enabled", + "ctx_size": 16384, + "lane_count": 4, + "n_ubatch": 512, + })) + .expect("stage config") + } + + #[test] + fn the_resource_names_the_kv_and_attention_configuration() { + let attributes = resource_attrs(&stage_config(), "skippy"); + assert_eq!(attributes["skippy.kv.cache_type_k"], json!("q8_0")); + assert_eq!(attributes["skippy.attention.flash"], json!("enabled")); + assert_eq!(attributes["skippy.kv.ctx_size"], json!(16384)); + assert_eq!(attributes["skippy.scheduler.lanes"], json!(4)); + assert_eq!(attributes["skippy.batch.ubatch_size"], json!(512)); + assert!(!attributes.contains_key("skippy.batch.size")); + assert_eq!(attributes["service.name"], json!("skippy")); + } + + #[test] + fn operator_attributes_are_percent_decoded_pairs() { + assert_eq!( + parse_resource_attributes("skippy.run.label=q8%20fa, team=perf,=x,broken, empty="), + vec![ + ("skippy.run.label".to_string(), "q8 fa".to_string()), + ("team".to_string(), "perf".to_string()), + ("empty".to_string(), String::new()), + ] + ); + assert_eq!(percent_decode("50%25%2"), "50%%2"); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs new file mode 100644 index 0000000000..b31c28a0dc --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs @@ -0,0 +1,768 @@ +//! Resource gauges for debugging throughput: CPU, GPU and memory, sampled on +//! a timer and exported as OTLP metrics, plus snapshots attached to the trace +//! at chosen points (model ready, server start, each request, shutdown). +//! +//! The sampler runs only with debug telemetry and a metrics destination: the +//! OTLP endpoint traces already go to, and the JSON-lines file named by +//! `SKIPPY_TELEMETRY_OTLP_METRICS_FILE`. GPU gauges come from the command +//! buffer timings native tracing reports, and the device's own allocation +//! counters; runtime gauges come from counters the scheduler bumps as it +//! works, which cost one relaxed atomic each. + +use std::{ + collections::BTreeMap, + env, + sync::{ + Mutex, OnceLock, PoisonError, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; + +use opentelemetry_proto::tonic::metrics::v1::Metric; +use serde_json::{Value, json}; +use skippy_runtime::{BackendDeviceType, backend_devices_untraced}; + +use super::{ + Telemetry, TelemetryLevel, now_unix_nanos, + resource_usage::{Paging, ProcessUsage, SystemMemory, process_usage, system_memory}, + trace_context::{Frame, SpanEvent}, +}; + +pub(crate) mod gpu_op_classes; +pub(crate) mod kv_tiers; +mod otlp_metrics; + +use gpu_op_classes::{GraphShape, OpClassCounters}; +use kv_tiers::KvTiers; +use otlp_metrics::{MetricSinks, gauge, point}; + +/// Where sampled metrics are appended, one OTLP/JSON request per line. +pub(super) const METRICS_FILE_ENV: &str = "SKIPPY_TELEMETRY_OTLP_METRICS_FILE"; +/// Sampling period in milliseconds; 250 when unset. +pub(super) const METRICS_INTERVAL_ENV: &str = "SKIPPY_TELEMETRY_METRICS_INTERVAL_MS"; +const DEFAULT_INTERVAL: Duration = Duration::from_millis(250); +const MIN_INTERVAL: Duration = Duration::from_millis(20); +/// Marks a gauge with no reading yet. +const UNSET: u64 = u64::MAX; + +static GPU_EXECUTE_NANOS: AtomicU64 = AtomicU64::new(0); +static GPU_QUEUE_NANOS: AtomicU64 = AtomicU64::new(0); +static GPU_COMMANDS: AtomicU64 = AtomicU64::new(0); +static RUNTIME_BUSY_NANOS: AtomicU64 = AtomicU64::new(0); +static DECODE_TOKENS: AtomicU64 = AtomicU64::new(0); +static SCHEDULER_RUNNING: AtomicU64 = AtomicU64::new(UNSET); +static SCHEDULER_WAITING: AtomicU64 = AtomicU64::new(UNSET); +static SCHEDULER_BATCH: AtomicU64 = AtomicU64::new(UNSET); +static KV_USED_CELLS: AtomicU64 = AtomicU64::new(UNSET); + +/// One GPU command buffer: how long the GPU ran it, and how long it waited +/// between being committed and starting. +pub(crate) fn record_gpu_command(execute: Duration, queue: Duration) { + GPU_EXECUTE_NANOS.fetch_add(nanos(execute), Ordering::Relaxed); + GPU_QUEUE_NANOS.fetch_add(nanos(queue), Ordering::Relaxed); + GPU_COMMANDS.fetch_add(1, Ordering::Relaxed); +} + +/// Time the scheduler held the runtime doing native work. +pub(crate) fn record_runtime_busy(elapsed: Duration) { + RUNTIME_BUSY_NANOS.fetch_add(nanos(elapsed), Ordering::Relaxed); +} + +pub(crate) fn record_decode_tokens(tokens: u64) { + DECODE_TOKENS.fetch_add(tokens, Ordering::Relaxed); +} + +/// The scheduler's queue as of its latest step. +pub(crate) fn record_scheduler(running: usize, waiting: usize, batch: usize) { + SCHEDULER_RUNNING.store(running as u64, Ordering::Relaxed); + SCHEDULER_WAITING.store(waiting as u64, Ordering::Relaxed); + SCHEDULER_BATCH.store(batch as u64, Ordering::Relaxed); +} + +pub(crate) fn record_kv_used_cells(cells: u64) { + KV_USED_CELLS.store(cells, Ordering::Relaxed); +} + +fn nanos(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) +} + +fn current(gauge: &AtomicU64) -> Option { + let value = gauge.load(Ordering::Relaxed); + (value != UNSET).then_some(value) +} + +/// Monotonic counters at one instant. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Counters { + gpu_execute_nanos: u64, + gpu_queue_nanos: u64, + gpu_commands: u64, + runtime_busy_nanos: u64, + decode_tokens: u64, +} + +impl Counters { + fn now() -> Self { + Self { + gpu_execute_nanos: GPU_EXECUTE_NANOS.load(Ordering::Relaxed), + gpu_queue_nanos: GPU_QUEUE_NANOS.load(Ordering::Relaxed), + gpu_commands: GPU_COMMANDS.load(Ordering::Relaxed), + runtime_busy_nanos: RUNTIME_BUSY_NANOS.load(Ordering::Relaxed), + decode_tokens: DECODE_TOKENS.load(Ordering::Relaxed), + } + } +} + +/// Everything rates are computed from: two of these make one sample. +#[derive(Clone, Copy, Debug)] +struct Reading { + at: Instant, + process: Option, + paging: Option, + counters: Counters, + op_classes: OpClassCounters, + kv: KvTiers, +} + +impl Reading { + fn take(system: Option<&SystemMemory>) -> Self { + Self { + at: Instant::now(), + process: process_usage(), + paging: system.and_then(|system| system.paging), + counters: Counters::now(), + op_classes: OpClassCounters::now(), + kv: KvTiers::now(), + } + } +} + +/// Levels read at the sample instant. +#[derive(Clone, Debug, Default)] +struct Levels { + system: Option, + gpu_memory: Vec, + running: Option, + waiting: Option, + batch: Option, + kv_used_cells: Option, + graph_shape: GraphShape, + telemetry_dropped: u64, + native_spans_dropped: u64, + gpu_records_dropped: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct GpuMemory { + device: String, + used_bytes: u64, + limit_bytes: u64, +} + +/// GPU memory per device, once native tracing shows the runtime is loaded: +/// before that a device query could be the first native call. +fn gpu_memory() -> Vec { + if !skippy_runtime::native_tracing::native_tracing_active() { + return Vec::new(); + } + backend_devices_untraced() + .unwrap_or_default() + .into_iter() + .filter(|device| { + matches!( + device.device_type, + BackendDeviceType::Gpu | BackendDeviceType::IntegratedGpu + ) + }) + .map(|device| GpuMemory { + used_bytes: device.memory_total.saturating_sub(device.memory_free), + limit_bytes: device.memory_total, + device: device.name, + }) + .collect() +} + +fn levels(telemetry: &Telemetry, system: Option) -> Levels { + use skippy_runtime::native_tracing::{gpu_commands, spans}; + Levels { + system, + gpu_memory: gpu_memory(), + running: current(&SCHEDULER_RUNNING), + waiting: current(&SCHEDULER_WAITING), + batch: current(&SCHEDULER_BATCH), + kv_used_cells: current(&KV_USED_CELLS), + graph_shape: GraphShape::take(), + telemetry_dropped: telemetry.stats().dropped, + native_spans_dropped: spans::dropped_native_spans(), + gpu_records_dropped: gpu_commands::dropped_gpu_command_timings(), + } +} + +/// The gauges for the interval from `before` to `after`, stamped `time`. +fn gauges(before: &Reading, after: &Reading, levels: &Levels, time: u64) -> Vec { + let seconds = after.at.duration_since(before.at).as_secs_f64(); + if seconds <= 0.0 { + return Vec::new(); + } + let mut metrics = Vec::new(); + process_gauges(&mut metrics, before, after, seconds, time); + system_gauges(&mut metrics, before, after, levels, seconds, time); + gpu_gauges(&mut metrics, before, after, levels, seconds, time); + gpu_op_classes::gauges( + &mut metrics, + &before.op_classes, + &after.op_classes, + levels.graph_shape, + seconds, + time, + ); + runtime_gauges(&mut metrics, before, after, levels, seconds, time); + kv_tiers::gauges( + &mut metrics, + &before.kv, + &after.kv, + levels.kv_used_cells, + seconds, + time, + ); + metrics +} + +fn rate(before: u64, after: u64, seconds: f64) -> f64 { + after.saturating_sub(before) as f64 / seconds +} + +fn process_gauges( + metrics: &mut Vec, + before: &Reading, + after: &Reading, + seconds: f64, + time: u64, +) { + let (Some(was), Some(now)) = (before.process, after.process) else { + return; + }; + let busy = |was: Duration, now: Duration| now.saturating_sub(was).as_secs_f64() / seconds; + metrics.push(gauge( + "process.cpu.utilization", + "1", + "CPU time per second of wall time; 1 is one core", + vec![ + point(time, busy(was.user, now.user), &[("cpu.mode", "user")]), + point( + time, + busy(was.system, now.system), + &[("cpu.mode", "system")], + ), + ], + )); + metrics.push(gauge( + "process.memory.usage", + "By", + "Resident memory", + vec![point(time, now.resident_bytes as f64, &[])], + )); + metrics.push(gauge( + "skippy.process.memory.footprint", + "By", + "Memory charged to the process, Metal buffers included on macOS", + vec![point(time, now.footprint_bytes as f64, &[])], + )); + if let Some(wired) = now.wired_bytes { + metrics.push(gauge( + "skippy.process.memory.wired", + "By", + "Wired (unpageable) memory", + vec![point(time, wired as f64, &[])], + )); + } + metrics.push(gauge( + "skippy.process.pageins", + "{page}/s", + "Pages read in from disk, such as mapped weights", + vec![point(time, rate(was.pageins, now.pageins, seconds), &[])], + )); + if let (Some(was), Some(now)) = (was.disk_read_bytes, now.disk_read_bytes) { + metrics.push(gauge( + "skippy.process.disk.read", + "By/s", + "Bytes read from disk", + vec![point(time, rate(was, now, seconds), &[])], + )); + } +} + +fn system_gauges( + metrics: &mut Vec, + before: &Reading, + after: &Reading, + levels: &Levels, + seconds: f64, + time: u64, +) { + let Some(system) = levels.system.as_ref() else { + return; + }; + metrics.push(gauge( + "system.memory.usage", + "By", + "System memory by state", + system + .states + .iter() + .map(|(state, bytes)| point(time, *bytes as f64, &[("system.memory.state", state)])) + .collect(), + )); + metrics.push(gauge( + "system.memory.limit", + "By", + "Installed memory", + vec![point(time, system.total_bytes as f64, &[])], + )); + metrics.push(gauge( + "skippy.system.swap.used", + "By", + "Swap in use", + vec![point(time, system.swap_used_bytes as f64, &[])], + )); + if let Some(level) = system.pressure_level { + metrics.push(gauge( + "skippy.system.memory.pressure", + "1", + "macOS memory pressure: 1 normal, 2 warning, 4 critical", + vec![point(time, f64::from(level), &[])], + )); + } + if let (Some(was), Some(now)) = (before.paging, after.paging) { + let pages = |was: u64, now: u64, direction: &str| { + point(time, rate(was, now, seconds), &[("direction", direction)]) + }; + metrics.push(gauge( + "skippy.system.paging", + "{page}/s", + "System-wide paging and swapping", + vec![ + pages(was.pageins, now.pageins, "pagein"), + pages(was.pageouts, now.pageouts, "pageout"), + pages(was.swapins, now.swapins, "swapin"), + pages(was.swapouts, now.swapouts, "swapout"), + ], + )); + } +} + +fn gpu_gauges( + metrics: &mut Vec, + before: &Reading, + after: &Reading, + levels: &Levels, + seconds: f64, + time: u64, +) { + let (was, now) = (before.counters, after.counters); + let commands = now.gpu_commands.saturating_sub(was.gpu_commands); + let execute = now.gpu_execute_nanos.saturating_sub(was.gpu_execute_nanos); + metrics.push(gauge( + "skippy.gpu.busy", + "1", + "Fraction of wall time the GPU spent running this process's command buffers", + vec![point(time, execute as f64 / 1e9 / seconds, &[])], + )); + metrics.push(gauge( + "skippy.gpu.command_buffers", + "{command_buffer}/s", + "Command buffers completed", + vec![point(time, commands as f64 / seconds, &[])], + )); + if commands > 0 { + let queue = now.gpu_queue_nanos.saturating_sub(was.gpu_queue_nanos); + metrics.push(gauge( + "skippy.gpu.queue_wait", + "ms", + "Mean wait between committing a command buffer and the GPU starting it", + vec![point(time, queue as f64 / 1e6 / commands as f64, &[])], + )); + } + if levels.gpu_memory.is_empty() { + return; + } + let by_device = |value: fn(&GpuMemory) -> u64| { + levels + .gpu_memory + .iter() + .map(|memory| { + point( + time, + value(memory) as f64, + &[("device", memory.device.as_str())], + ) + }) + .collect() + }; + metrics.push(gauge( + "skippy.gpu.memory.usage", + "By", + "Memory the GPU device has allocated", + by_device(|memory| memory.used_bytes), + )); + metrics.push(gauge( + "skippy.gpu.memory.limit", + "By", + "The device's recommended working set", + by_device(|memory| memory.limit_bytes), + )); +} + +fn runtime_gauges( + metrics: &mut Vec, + before: &Reading, + after: &Reading, + levels: &Levels, + seconds: f64, + time: u64, +) { + let (was, now) = (before.counters, after.counters); + metrics.push(gauge( + "skippy.runtime.busy", + "1", + "Fraction of wall time the scheduler held the runtime for native work", + vec![point( + time, + now.runtime_busy_nanos + .saturating_sub(was.runtime_busy_nanos) as f64 + / 1e9 + / seconds, + &[], + )], + )); + metrics.push(gauge( + "skippy.decode.tokens", + "{token}/s", + "Decode tokens produced", + vec![point( + time, + rate(was.decode_tokens, now.decode_tokens, seconds), + &[], + )], + )); + let levels_now = [ + ( + "skippy.scheduler.running", + "{sequence}", + "Sequences running", + levels.running, + ), + ( + "skippy.scheduler.waiting", + "{sequence}", + "Sequences waiting", + levels.waiting, + ), + ( + "skippy.scheduler.batch_size", + "{sequence}", + "Sequences in the latest step", + levels.batch, + ), + ( + "skippy.kv.used_cells", + "{cell}", + "KV cells in use", + levels.kv_used_cells, + ), + ]; + for (name, unit, description, value) in levels_now { + if let Some(value) = value { + metrics.push(gauge( + name, + unit, + description, + vec![point(time, value as f64, &[])], + )); + } + } + metrics.push(gauge( + "skippy.telemetry.dropped", + "{item}", + "Telemetry lost to full queues since start", + vec![ + point( + time, + levels.telemetry_dropped as f64, + &[("source", "spans")], + ), + point( + time, + levels.native_spans_dropped as f64, + &[("source", "native_spans")], + ), + point( + time, + levels.gpu_records_dropped as f64, + &[("source", "gpu_commands")], + ), + ], + )); +} + +/// The running sampler: its sinks and the reading the next sample starts at. +struct Sampler { + telemetry: Telemetry, + sinks: MetricSinks, + last: Mutex, + stopped: AtomicBool, +} + +impl Sampler { + fn tick(&self) { + let system = system_memory(); + let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + let now = Reading::take(system.as_ref()); + let time = u64::try_from(now_unix_nanos()).unwrap_or_default(); + let metrics = gauges(&last, &now, &levels(&self.telemetry, system), time); + *last = now; + drop(last); + if !metrics.is_empty() { + self.sinks.send(&self.telemetry.config, metrics); + } + } +} + +static SAMPLER: OnceLock = OnceLock::new(); + +fn interval_from_value(value: Option<&str>) -> Duration { + value + .and_then(|value| value.trim().parse::().ok()) + .map_or(DEFAULT_INTERVAL, |millis| { + Duration::from_millis(millis).max(MIN_INTERVAL) + }) +} + +/// Start sampling for the process, if there is anywhere to send it. The first +/// debug handle with a destination serves the whole process. +pub(super) fn start(telemetry: &Telemetry, endpoint: Option<&str>) { + let Some(sinks) = MetricSinks::open( + env::var_os(METRICS_FILE_ENV).filter(|path| !path.is_empty()), + endpoint, + ) else { + return; + }; + let sampler = Sampler { + telemetry: telemetry.clone(), + sinks, + last: Mutex::new(Reading::take(None)), + stopped: AtomicBool::new(false), + }; + if SAMPLER.set(sampler).is_err() { + return; + } + let interval = interval_from_value(env::var(METRICS_INTERVAL_ENV).ok().as_deref()); + let spawned = thread::Builder::new() + .name("skippy-metrics".to_string()) + .spawn(move || { + let Some(sampler) = SAMPLER.get() else { + return; + }; + while !sampler.stopped.load(Ordering::Acquire) { + thread::sleep(interval); + sampler.tick(); + } + }); + if let Err(error) = spawned { + tracing::warn!("telemetry metrics sampler did not start: {error}"); + } +} + +/// Take a last sample and stop; called as the process span ends. +pub(super) fn finish() { + if let Some(sampler) = SAMPLER.get() + && !sampler.stopped.swap(true, Ordering::AcqRel) + { + sampler.tick(); + sampler.sinks.flush(); + } +} + +/// Resource readings for a span event, keyed `skippy.resources.*`. +fn snapshot(point: &str) -> BTreeMap { + let key = |name: &str| format!("skippy.resources.{name}"); + let mut attrs = BTreeMap::from([(key("point"), json!(point))]); + if let Some(process) = process_usage() { + attrs.extend([ + ( + key("process.footprint_bytes"), + json!(process.footprint_bytes), + ), + (key("process.resident_bytes"), json!(process.resident_bytes)), + (key("process.cpu_user_s"), json!(process.user.as_secs_f64())), + ( + key("process.cpu_system_s"), + json!(process.system.as_secs_f64()), + ), + (key("process.pageins"), json!(process.pageins)), + ]); + if let Some(wired) = process.wired_bytes { + attrs.insert(key("process.wired_bytes"), json!(wired)); + } + } + if let Some(system) = system_memory() { + attrs.insert(key("system.total_bytes"), json!(system.total_bytes)); + attrs.insert(key("system.swap_used_bytes"), json!(system.swap_used_bytes)); + for (state, bytes) in &system.states { + attrs.insert(key(&format!("system.{state}_bytes")), json!(bytes)); + } + if let Some(level) = system.pressure_level { + attrs.insert(key("system.pressure_level"), json!(level)); + } + } + for memory in gpu_memory() { + attrs.insert( + key(&format!("gpu.{}.used_bytes", memory.device)), + json!(memory.used_bytes), + ); + attrs.insert( + key(&format!("gpu.{}.limit_bytes", memory.device)), + json!(memory.limit_bytes), + ); + } + let gauges = [ + ("scheduler.running", current(&SCHEDULER_RUNNING)), + ("scheduler.waiting", current(&SCHEDULER_WAITING)), + ("kv.used_cells", current(&KV_USED_CELLS)), + ]; + for (name, value) in gauges { + if let Some(value) = value { + attrs.insert(key(name), json!(value)); + } + } + kv_tiers::snapshot(&mut attrs, key); + attrs +} + +impl Telemetry { + /// Record a resource snapshot, named `point`, on the active span. + pub(crate) fn record_resources(&self, point: &str) { + if self.level == TelemetryLevel::Debug { + self.emit("skippy.resources", snapshot(point)); + } + } + + /// Record a resource snapshot on `frame`, which need not be active. + pub(crate) fn record_resources_on(&self, frame: &Frame, point: &str) { + if self.level != TelemetryLevel::Debug || !self.has_trace_sink() { + return; + } + let mut attributes = snapshot(point); + self.add_common_attributes(&mut attributes); + let event = SpanEvent { + name: "skippy.resources".to_string(), + time_unix_nanos: u64::try_from(now_unix_nanos()).unwrap_or_default(), + attributes, + }; + if let Err(event) = frame.record_event(event) { + self.emit(&event.name, event.attributes); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point}; + + fn reading(at: Instant, cpu_ms: u64, counters: Counters) -> Reading { + Reading { + at, + process: Some(ProcessUsage { + user: Duration::from_millis(cpu_ms), + system: Duration::from_millis(cpu_ms / 2), + resident_bytes: 1 << 30, + footprint_bytes: 2 << 30, + wired_bytes: Some(1 << 20), + pageins: 100, + disk_read_bytes: None, + }), + paging: None, + counters, + op_classes: OpClassCounters::default(), + kv: KvTiers::default(), + } + } + + fn values(metrics: &[Metric], name: &str) -> Vec { + metrics + .iter() + .find(|metric| metric.name == name) + .map(|metric| match metric.data.as_ref() { + Some(Data::Gauge(gauge)) => gauge + .data_points + .iter() + .map(|point| match point.value { + Some(number_data_point::Value::AsDouble(value)) => value, + _ => f64::NAN, + }) + .collect(), + _ => Vec::new(), + }) + .unwrap_or_default() + } + + #[test] + fn rates_come_from_the_interval_between_readings() { + let start = Instant::now(); + let before = reading(start, 1_000, Counters::default()); + let after = reading( + start + Duration::from_millis(500), + 1_400, + Counters { + gpu_execute_nanos: 250_000_000, + gpu_queue_nanos: 2_000_000, + gpu_commands: 4, + runtime_busy_nanos: 400_000_000, + decode_tokens: 40, + }, + ); + let levels = Levels { + running: Some(4), + kv_used_cells: Some(2048), + ..Levels::default() + }; + let metrics = gauges(&before, &after, &levels, 7); + + let close = |got: &[f64], want: &[f64]| { + assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}"); + for (got, want) in got.iter().zip(want) { + assert!((got - want).abs() < 1e-9, "{got} vs {want}"); + } + }; + close(&values(&metrics, "process.cpu.utilization"), &[0.8, 0.4]); + close(&values(&metrics, "skippy.gpu.busy"), &[0.5]); + close(&values(&metrics, "skippy.gpu.command_buffers"), &[8.0]); + close(&values(&metrics, "skippy.gpu.queue_wait"), &[0.5]); + close(&values(&metrics, "skippy.runtime.busy"), &[0.8]); + close(&values(&metrics, "skippy.decode.tokens"), &[80.0]); + close(&values(&metrics, "skippy.scheduler.running"), &[4.0]); + close(&values(&metrics, "skippy.kv.used_cells"), &[2048.0]); + assert!(values(&metrics, "skippy.scheduler.waiting").is_empty()); + assert!(values(&metrics, "skippy.gpu.memory.usage").is_empty()); + } + + #[test] + fn the_sampling_interval_has_a_default_and_a_floor() { + assert_eq!(interval_from_value(None), DEFAULT_INTERVAL); + assert_eq!(interval_from_value(Some("x")), DEFAULT_INTERVAL); + assert_eq!(interval_from_value(Some(" 1000 ")), Duration::from_secs(1)); + assert_eq!(interval_from_value(Some("1")), MIN_INTERVAL); + } + + #[test] + fn a_snapshot_names_its_point_and_this_process() { + let attrs = snapshot("test_point"); + assert_eq!(attrs["skippy.resources.point"], json!("test_point")); + #[cfg(any(target_os = "macos", target_os = "linux"))] + assert!(attrs.contains_key("skippy.resources.process.resident_bytes")); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics/gpu_op_classes.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/gpu_op_classes.rs new file mode 100644 index 0000000000..4b2f18901d --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/gpu_op_classes.rs @@ -0,0 +1,268 @@ +//! GPU work by op class: the bytes each class reads per second (an estimate +//! of where memory traffic goes), and with op profiling, which splits graphs +//! so each command buffer holds one class, the GPU time each class takes. +//! Shape gauges give the largest value in each interval: the KV span one +//! attention query addressed (layers differ: sliding-window and full +//! attention, so the last command's value alone would be noise), and the +//! recurrent states one step gathered and carried back unchanged. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use opentelemetry_proto::tonic::metrics::v1::Metric; +use skippy_runtime::native_tracing::gpu_commands::{GpuOpClass, GpuOpClasses}; + +use super::{ + nanos, + otlp_metrics::{gauge, point}, + rate, +}; + +const CLASSES: usize = GpuOpClass::ALL.len(); + +static INPUT_BYTES: [AtomicU64; CLASSES] = [const { AtomicU64::new(0) }; CLASSES]; +static PROFILED_EXECUTE_NANOS: [AtomicU64; CLASSES] = [const { AtomicU64::new(0) }; CLASSES]; +/// Largest since the last sample; 0 is none. +static ATTENTION_KV_CELLS: AtomicU64 = AtomicU64::new(0); +static ATTENTION_QUERIES: AtomicU64 = AtomicU64::new(0); +static RECURRENT_STATES: AtomicU64 = AtomicU64::new(0); +static RECURRENT_STATES_CARRIED: AtomicU64 = AtomicU64::new(0); + +fn index(class: GpuOpClass) -> usize { + match class { + GpuOpClass::Attention => 0, + GpuOpClass::Matmul => 1, + GpuOpClass::Recurrent => 2, + GpuOpClass::KvWrite => 3, + GpuOpClass::Other => 4, + } +} + +/// One command buffer's classes and GPU execution time. +pub(crate) fn record(classes: &GpuOpClasses, execute: Duration) { + for class in GpuOpClass::ALL { + INPUT_BYTES[index(class)].fetch_add(classes.bytes.get(class), Ordering::Relaxed); + } + if classes.split_by_class + && let Some(class) = classes.single + { + PROFILED_EXECUTE_NANOS[index(class)].fetch_add(nanos(execute), Ordering::Relaxed); + } + if classes.nodes.attention > 0 && classes.attention_kv_cells > 0 { + ATTENTION_KV_CELLS.fetch_max(u64::from(classes.attention_kv_cells), Ordering::Relaxed); + ATTENTION_QUERIES.fetch_max(u64::from(classes.attention_queries), Ordering::Relaxed); + } + if let Some(states) = classes.recurrent_states { + RECURRENT_STATES.fetch_max(u64::from(states.gathered), Ordering::Relaxed); + RECURRENT_STATES_CARRIED.fetch_max(u64::from(states.carried), Ordering::Relaxed); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct OpClassCounters { + input_bytes: [u64; CLASSES], + profiled_execute_nanos: [u64; CLASSES], +} + +impl OpClassCounters { + pub(super) fn now() -> Self { + Self { + input_bytes: INPUT_BYTES + .each_ref() + .map(|bytes| bytes.load(Ordering::Relaxed)), + profiled_execute_nanos: PROFILED_EXECUTE_NANOS + .each_ref() + .map(|nanos| nanos.load(Ordering::Relaxed)), + } + } +} + +/// The largest graph shape since the last sample: KV cells one attention +/// query addressed, query rows one attention node processed, and recurrent +/// states one step gathered and, of those, carried back unchanged. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct GraphShape { + kv_cells: Option, + queries: Option, + recurrent: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct RecurrentShape { + states: u64, + /// 0 is a real value: every gathered state belonged to the batch. + carried: u64, +} + +impl GraphShape { + /// Takes the interval's maxima and starts the next interval. + pub(super) fn take() -> Self { + let take = + |max: &AtomicU64| Some(max.swap(0, Ordering::Relaxed)).filter(|&value| value > 0); + let carried = RECURRENT_STATES_CARRIED.swap(0, Ordering::Relaxed); + Self { + kv_cells: take(&ATTENTION_KV_CELLS), + queries: take(&ATTENTION_QUERIES), + recurrent: take(&RECURRENT_STATES).map(|states| RecurrentShape { states, carried }), + } + } +} + +/// Per-class gauges for the interval from `was` to `now`. +pub(super) fn gauges( + metrics: &mut Vec, + was: &OpClassCounters, + now: &OpClassCounters, + shape: GraphShape, + seconds: f64, + time: u64, +) { + let by_class = |values: &dyn Fn(usize) -> f64| { + GpuOpClass::ALL + .into_iter() + .map(|class| point(time, values(index(class)), &[("op_class", class.name())])) + .collect::>() + }; + if now.input_bytes.iter().any(|&bytes| bytes > 0) { + metrics.push(gauge( + "skippy.gpu.input_bytes", + "By/s", + "Bytes GPU commands read, by op_class: gathers and row writes count their rows, attention the K/V rows it addresses", + by_class(&|i| rate(was.input_bytes[i], now.input_bytes[i], seconds)), + )); + } + let profiled = + (0..CLASSES).any(|i| now.profiled_execute_nanos[i] > was.profiled_execute_nanos[i]); + if profiled { + metrics.push(gauge( + "skippy.gpu.class_busy", + "1", + "GPU execution time per wall second, by op_class, from graphs split by class (GGML_METAL_OP_PROFILE)", + by_class(&|i| { + now.profiled_execute_nanos[i].saturating_sub(was.profiled_execute_nanos[i]) as f64 + / 1e9 + / seconds + }), + )); + } + shape_gauges(metrics, shape, time); +} + +fn shape_gauges(metrics: &mut Vec, shape: GraphShape, time: u64) { + if let Some(cells) = shape.kv_cells { + metrics.push(gauge( + "skippy.attention.kv_cells", + "{cell}", + "The most KV cells one attention query addressed in the interval: its row list, or the whole K/V span", + vec![point(time, cells as f64, &[])], + )); + } + if let Some(queries) = shape.queries { + metrics.push(gauge( + "skippy.attention.queries", + "{query}", + "The most query rows one attention node processed in the interval", + vec![point(time, queries as f64, &[])], + )); + } + if let Some(recurrent) = shape.recurrent { + metrics.push(gauge( + "skippy.recurrent.states", + "{state}", + "The most recurrent states one step gathered in the interval: its sequences' and every state between them", + vec![point(time, recurrent.states as f64, &[])], + )); + metrics.push(gauge( + "skippy.recurrent.states_carried", + "{state}", + "The most gathered recurrent states one step copied back unchanged in the interval", + vec![point(time, recurrent.carried as f64, &[])], + )); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_runtime::native_tracing::gpu_commands::PerOpClass; + + fn values(metrics: &[Metric], name: &str) -> Vec { + use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point}; + metrics + .iter() + .find(|metric| metric.name == name) + .and_then(|metric| match metric.data.as_ref() { + Some(Data::Gauge(gauge)) => Some( + gauge + .data_points + .iter() + .map(|point| match point.value { + Some(number_data_point::Value::AsDouble(value)) => value, + _ => f64::NAN, + }) + .collect(), + ), + _ => None, + }) + .unwrap_or_default() + } + + #[test] + fn bytes_are_rates_and_profiled_time_is_a_share_of_wall_time() { + let was = OpClassCounters::default(); + let now = OpClassCounters { + input_bytes: [100, 400, 0, 0, 50], + profiled_execute_nanos: [250_000_000, 0, 0, 0, 0], + }; + let shape = GraphShape { + kv_cells: Some(4096), + queries: Some(4), + recurrent: Some(RecurrentShape { + states: 9, + carried: 0, + }), + }; + let mut metrics = Vec::new(); + gauges(&mut metrics, &was, &now, shape, 0.5, 1); + assert_eq!( + values(&metrics, "skippy.gpu.input_bytes"), + [200.0, 800.0, 0.0, 0.0, 100.0] + ); + assert_eq!(values(&metrics, "skippy.gpu.class_busy")[0], 0.5); + assert_eq!(values(&metrics, "skippy.attention.kv_cells"), [4096.0]); + assert_eq!(values(&metrics, "skippy.recurrent.states"), [9.0]); + assert_eq!( + values(&metrics, "skippy.recurrent.states_carried"), + [0.0], + "nothing carried is a reading, not an absence" + ); + + let mut unprofiled = Vec::new(); + gauges(&mut unprofiled, &now, &now, GraphShape::default(), 0.5, 1); + assert!(values(&unprofiled, "skippy.gpu.class_busy").is_empty()); + assert!(values(&unprofiled, "skippy.attention.kv_cells").is_empty()); + assert!(values(&unprofiled, "skippy.recurrent.states_carried").is_empty()); + } + + #[test] + fn classes_index_their_own_slot() { + let classes = GpuOpClasses { + single: Some(GpuOpClass::Matmul), + layer: None, + split_by_class: true, + attention_kv_cells: 0, + attention_queries: 0, + attention_row_list_nodes: 0, + attention_flash_nodes: 0, + nodes: PerOpClass::default(), + bytes: PerOpClass { + matmul: 7, + ..PerOpClass::default() + }, + recurrent_states: None, + }; + let indices = GpuOpClass::ALL.map(index); + assert_eq!(indices, [0, 1, 2, 3, 4]); + assert_eq!(classes.bytes.get(GpuOpClass::ALL[indices[1]]), 7); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics/kv_tiers.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/kv_tiers.rs new file mode 100644 index 0000000000..2bc6e38bb2 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/kv_tiers.rs @@ -0,0 +1,850 @@ +//! KV cache tier gauges. L1 is the resident radix cache: prefixes kept as +//! shared cells of the native attention pool, plus recurrent checkpoints in +//! host RAM. L2 is the optional host-RAM mirror of L3 fills. L3 is the +//! durable store. Each tier reports its pressure (how full it is against its +//! limit, and how often it evicts or refuses) and its lookups, split into +//! hits and misses. +//! +//! Each cache-enabled stage registers a source the sampler reads without +//! keeping the stage alive. L1 lookups are counted as the cache decides them; +//! the native pool's size comes from the scheduler's step sampling. + +use std::{ + collections::BTreeMap, + sync::{ + Mutex, PoisonError, + atomic::{AtomicU64, Ordering}, + }, +}; + +use opentelemetry_proto::tonic::metrics::v1::Metric; +use serde_json::{Value, json}; + +use super::{ + UNSET, current, + otlp_metrics::{gauge, point}, + rate, +}; + +static L1_HITS: AtomicU64 = AtomicU64::new(0); +static L1_MISSES: AtomicU64 = AtomicU64::new(0); +static L1_HIT_TOKENS: AtomicU64 = AtomicU64::new(0); +static L1_RESTORED_TOKENS: AtomicU64 = AtomicU64::new(0); +static L1_EVICTED_TOKENS: AtomicU64 = AtomicU64::new(0); +static L1_SHORTFALLS: AtomicU64 = AtomicU64::new(0); +static POOL_CELLS: AtomicU64 = AtomicU64::new(UNSET); + +/// An L1 lookup found a usable resident prefix of `matched_tokens`. +pub(crate) fn record_l1_hit(matched_tokens: u64) { + L1_HITS.fetch_add(1, Ordering::Relaxed); + L1_HIT_TOKENS.fetch_add(matched_tokens, Ordering::Relaxed); +} + +pub(crate) fn record_l1_miss() { + L1_MISSES.fetch_add(1, Ordering::Relaxed); +} + +pub(crate) fn record_l1_restore(tokens: u64) { + L1_RESTORED_TOKENS.fetch_add(tokens, Ordering::Relaxed); +} + +pub(crate) fn record_l1_eviction(tokens: u64) { + L1_EVICTED_TOKENS.fetch_add(tokens, Ordering::Relaxed); +} + +/// Admission could not keep the pool's free-space watermark even after +/// evicting every releasable prefix. Each shortfall's size belongs to its +/// `skippy.kv.admission_shortfall` event; the gauges count how often. +pub(crate) fn record_l1_admission_shortfall() { + L1_SHORTFALLS.fetch_add(1, Ordering::Relaxed); +} + +/// Cells in the shared native KV pool; zero is an unknown size. +pub(crate) fn record_kv_pool_cells(cells: u64) { + if cells > 0 { + POOL_CELLS.store(cells, Ordering::Relaxed); + } +} + +/// One stage's resident cache. Counters are cumulative since it started. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct L1Reading { + pub(crate) entries: u64, + /// Tokens of the retained prefixes, counting a shared prefix once per + /// entry that extends it; the pool's used cells count it once. + pub(crate) tokens: u64, + /// Retained tokens a restore holds, which eviction cannot release. + pub(crate) pinned_tokens: u64, + pub(crate) recurrent_bytes: u64, + pub(crate) recurrent_limit_bytes: u64, + pub(crate) attention_evictions: u64, + pub(crate) recurrent_evictions: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct L2Reading { + pub(crate) entries: u64, + pub(crate) bytes: u64, + pub(crate) budget_bytes: u64, + pub(crate) hits: u64, + pub(crate) misses: u64, + pub(crate) inserts: u64, + pub(crate) evictions: u64, + pub(crate) refusals: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct L3Reading { + /// Identifies the store. Stages on one node share it, so it counts once. + pub(crate) store: usize, + pub(crate) used_bytes: Option, + pub(crate) budget_bytes: u64, + pub(crate) reserved_bytes: u64, + pub(crate) filesystem_available_bytes: Option, + pub(crate) hits: u64, + pub(crate) misses: u64, + pub(crate) fills: u64, + pub(crate) writes: u64, + pub(crate) bytes_read: u64, + pub(crate) bytes_written: u64, + pub(crate) evictions: u64, + pub(crate) corrupt: u64, +} + +/// Exact-state records waiting for the worker that publishes them to L1 and +/// writes them through to L3. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct RecordQueueReading { + pub(crate) records: u64, + pub(crate) bytes: u64, + pub(crate) dropped: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct KvTierReading { + pub(crate) l1: L1Reading, + pub(crate) l2: Option, + pub(crate) l3: Option, + pub(crate) record_queue: RecordQueueReading, +} + +pub(crate) trait KvTierSource: Send + Sync { + /// The stage's tiers now; `None` once the stage is gone. + fn read(&self) -> Option; +} + +static SOURCES: Mutex>> = Mutex::new(Vec::new()); + +pub(crate) fn register(source: Box) { + SOURCES + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(source); +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct L1Lookups { + hits: u64, + misses: u64, + hit_tokens: u64, + restored_tokens: u64, + evicted_tokens: u64, + shortfalls: u64, +} + +impl L1Lookups { + fn now() -> Self { + Self { + hits: L1_HITS.load(Ordering::Relaxed), + misses: L1_MISSES.load(Ordering::Relaxed), + hit_tokens: L1_HIT_TOKENS.load(Ordering::Relaxed), + restored_tokens: L1_RESTORED_TOKENS.load(Ordering::Relaxed), + evicted_tokens: L1_EVICTED_TOKENS.load(Ordering::Relaxed), + shortfalls: L1_SHORTFALLS.load(Ordering::Relaxed), + } + } +} + +/// Every stage's tiers summed, with the process-wide L1 lookup counters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct KvTiers { + stages: u64, + l1: L1Reading, + lookups: L1Lookups, + l2: Option, + l3: Option, + record_queue: RecordQueueReading, + pool_cells: Option, +} + +impl KvTiers { + pub(super) fn now() -> Self { + let mut readings = Vec::new(); + SOURCES + .lock() + .unwrap_or_else(PoisonError::into_inner) + .retain(|source| match source.read() { + Some(reading) => { + readings.push(reading); + true + } + None => false, + }); + Self { + lookups: L1Lookups::now(), + pool_cells: current(&POOL_CELLS), + ..Self::sum(readings) + } + } + + fn sum(readings: impl IntoIterator) -> Self { + readings + .into_iter() + .fold(Self::default(), |mut tiers, reading| { + tiers.stages += 1; + tiers.l1 = tiers.l1.plus(reading.l1); + if let Some(l2) = reading.l2 { + tiers.l2 = Some(tiers.l2.unwrap_or_default().plus(l2)); + } + if let Some(l3) = reading.l3 { + tiers.l3 = Some(match tiers.l3 { + Some(sum) if sum.store == l3.store => sum, + Some(sum) => sum.plus(l3), + None => l3, + }); + } + tiers.record_queue = tiers.record_queue.plus(reading.record_queue); + tiers + }) + } +} + +impl L1Reading { + fn plus(self, other: Self) -> Self { + Self { + entries: self.entries + other.entries, + tokens: self.tokens + other.tokens, + pinned_tokens: self.pinned_tokens + other.pinned_tokens, + recurrent_bytes: self.recurrent_bytes + other.recurrent_bytes, + recurrent_limit_bytes: self.recurrent_limit_bytes + other.recurrent_limit_bytes, + attention_evictions: self.attention_evictions + other.attention_evictions, + recurrent_evictions: self.recurrent_evictions + other.recurrent_evictions, + } + } +} + +impl L2Reading { + fn plus(self, other: Self) -> Self { + Self { + entries: self.entries + other.entries, + bytes: self.bytes + other.bytes, + budget_bytes: self.budget_bytes + other.budget_bytes, + hits: self.hits + other.hits, + misses: self.misses + other.misses, + inserts: self.inserts + other.inserts, + evictions: self.evictions + other.evictions, + refusals: self.refusals + other.refusals, + } + } +} + +impl L3Reading { + /// Two different stores; the free space is the tighter filesystem's. + fn plus(self, other: Self) -> Self { + Self { + store: self.store, + used_bytes: self.used_bytes.zip(other.used_bytes).map(|(a, b)| a + b), + budget_bytes: self.budget_bytes + other.budget_bytes, + reserved_bytes: self.reserved_bytes + other.reserved_bytes, + filesystem_available_bytes: match ( + self.filesystem_available_bytes, + other.filesystem_available_bytes, + ) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }, + hits: self.hits + other.hits, + misses: self.misses + other.misses, + fills: self.fills + other.fills, + writes: self.writes + other.writes, + bytes_read: self.bytes_read + other.bytes_read, + bytes_written: self.bytes_written + other.bytes_written, + evictions: self.evictions + other.evictions, + corrupt: self.corrupt + other.corrupt, + } + } +} + +impl RecordQueueReading { + fn plus(self, other: Self) -> Self { + Self { + records: self.records + other.records, + bytes: self.bytes + other.bytes, + dropped: self.dropped + other.dropped, + } + } +} + +/// Appends gauges for one sampling interval. +struct Gauges<'a> { + metrics: &'a mut Vec, + seconds: f64, + time: u64, +} + +impl Gauges<'_> { + fn level(&mut self, name: &str, unit: &str, description: &str, value: u64) { + self.metrics.push(gauge( + name, + unit, + description, + vec![point(self.time, value as f64, &[])], + )); + } + + /// `used / limit`, omitted for an unknown or unlimited `limit`. + fn utilization(&mut self, name: &str, description: &str, used: u64, limit: u64) { + if limit > 0 { + self.metrics.push(gauge( + name, + "1", + description, + vec![point(self.time, used as f64 / limit as f64, &[])], + )); + } + } + + fn per_second(&mut self, name: &str, unit: &str, description: &str, was: u64, now: u64) { + self.metrics.push(gauge( + name, + unit, + description, + vec![point(self.time, rate(was, now, self.seconds), &[])], + )); + } + + /// One rate per `(attribute value, was, now)`, under attribute `key`. + fn per_second_by( + &mut self, + name: &str, + unit: &str, + description: &str, + key: &str, + values: &[(&str, u64, u64)], + ) { + let points = values + .iter() + .map(|&(value, was, now)| { + point(self.time, rate(was, now, self.seconds), &[(key, value)]) + }) + .collect(); + self.metrics.push(gauge(name, unit, description, points)); + } + + /// Lookups per second split by result, and the share that missed when + /// there were any. + fn lookups(&mut self, tier: &str, hits: (u64, u64), misses: (u64, u64)) { + self.per_second_by( + &format!("skippy.kv.{tier}.lookups"), + "{lookup}/s", + "Cache lookups at this tier, by result", + "result", + &[("hit", hits.0, hits.1), ("miss", misses.0, misses.1)], + ); + let hit = hits.1.saturating_sub(hits.0); + let missed = misses.1.saturating_sub(misses.0); + if hit + missed > 0 { + self.metrics.push(gauge( + &format!("skippy.kv.{tier}.miss_ratio"), + "1", + "Share of this interval's lookups at this tier that missed", + vec![point(self.time, missed as f64 / (hit + missed) as f64, &[])], + )); + } + } +} + +/// The tier gauges for the interval from `before` to `after`. +pub(super) fn gauges( + metrics: &mut Vec, + before: &KvTiers, + after: &KvTiers, + kv_used_cells: Option, + seconds: f64, + time: u64, +) { + if after.stages == 0 { + return; + } + let mut out = Gauges { + metrics, + seconds, + time, + }; + l1_gauges(&mut out, before, after, kv_used_cells); + if let Some(l2) = after.l2 { + l2_gauges(&mut out, before.l2, l2); + } + if let Some(l3) = after.l3 { + l3_gauges(&mut out, before.l3, l3); + } + record_queue_gauges(&mut out, before.record_queue, after.record_queue); +} + +fn l1_gauges(out: &mut Gauges<'_>, before: &KvTiers, after: &KvTiers, kv_used_cells: Option) { + if let Some(limit) = after.pool_cells { + out.level( + "skippy.kv.l1.pool.limit", + "{cell}", + "Cells in the shared native KV pool", + limit, + ); + if let Some(used) = kv_used_cells { + out.utilization( + "skippy.kv.l1.pool.utilization", + "Share of the native KV pool in use by requests and retained prefixes", + used, + limit, + ); + } + } + let (was, now) = (before.l1, after.l1); + out.level( + "skippy.kv.l1.entries", + "{entry}", + "Prefixes the resident cache retains", + now.entries, + ); + out.level( + "skippy.kv.l1.tokens", + "{token}", + "Tokens of retained prefixes, a shared prefix once per entry", + now.tokens, + ); + out.level( + "skippy.kv.l1.pinned_tokens", + "{token}", + "Retained tokens a restore holds, which eviction cannot release", + now.pinned_tokens, + ); + out.level( + "skippy.kv.l1.recurrent.usage", + "By", + "Host RAM held by recurrent checkpoints", + now.recurrent_bytes, + ); + out.level( + "skippy.kv.l1.recurrent.limit", + "By", + "Recurrent checkpoint budget", + now.recurrent_limit_bytes, + ); + out.utilization( + "skippy.kv.l1.recurrent.utilization", + "Share of the recurrent checkpoint budget in use", + now.recurrent_bytes, + now.recurrent_limit_bytes, + ); + out.per_second_by( + "skippy.kv.l1.evictions", + "{entry}/s", + "Resident cache evictions, by component", + "component", + &[ + ( + "attention", + was.attention_evictions, + now.attention_evictions, + ), + ( + "recurrent", + was.recurrent_evictions, + now.recurrent_evictions, + ), + ], + ); + l1_lookup_gauges(out, before, after); +} + +fn l1_lookup_gauges(out: &mut Gauges<'_>, before: &KvTiers, after: &KvTiers) { + let (was, now) = (before.lookups, after.lookups); + out.lookups("l1", (was.hits, now.hits), (was.misses, now.misses)); + out.per_second( + "skippy.kv.l1.hit_tokens", + "{token}/s", + "Prompt tokens L1 hits matched", + was.hit_tokens, + now.hit_tokens, + ); + out.per_second( + "skippy.kv.l1.restored_tokens", + "{token}/s", + "Tokens restored from retained prefixes onto requests", + was.restored_tokens, + now.restored_tokens, + ); + out.per_second( + "skippy.kv.l1.evicted_tokens", + "{token}/s", + "Tokens released by resident cache evictions", + was.evicted_tokens, + now.evicted_tokens, + ); + out.per_second( + "skippy.kv.l1.admission_shortfalls", + "{request}/s", + "Admissions left below the pool's free-space watermark after evicting all it could", + was.shortfalls, + now.shortfalls, + ); +} + +fn l2_gauges(out: &mut Gauges<'_>, before: Option, now: L2Reading) { + out.level( + "skippy.kv.l2.entries", + "{entry}", + "Entries in host-RAM L2", + now.entries, + ); + out.level( + "skippy.kv.l2.usage", + "By", + "Distinct segment bytes held by L2", + now.bytes, + ); + out.level( + "skippy.kv.l2.limit", + "By", + "L2 byte budget", + now.budget_bytes, + ); + out.utilization( + "skippy.kv.l2.utilization", + "Share of the L2 budget in use", + now.bytes, + now.budget_bytes, + ); + let Some(was) = before else { + return; + }; + out.lookups("l2", (was.hits, now.hits), (was.misses, now.misses)); + out.per_second( + "skippy.kv.l2.inserts", + "{entry}/s", + "L2 admissions", + was.inserts, + now.inserts, + ); + out.per_second( + "skippy.kv.l2.evictions", + "{entry}/s", + "L2 evictions to stay within budget", + was.evictions, + now.evictions, + ); + out.per_second( + "skippy.kv.l2.refusals", + "{entry}/s", + "L2 admissions refused for failing verification", + was.refusals, + now.refusals, + ); +} + +fn l3_gauges(out: &mut Gauges<'_>, before: Option, now: L3Reading) { + if let Some(used) = now.used_bytes { + out.level( + "skippy.kv.l3.usage", + "By", + "Bytes the L3 store manages", + used, + ); + out.utilization( + "skippy.kv.l3.utilization", + "Share of the L3 budget in use", + used, + now.budget_bytes, + ); + } + out.level( + "skippy.kv.l3.limit", + "By", + "L3 byte budget; zero is unlimited", + now.budget_bytes, + ); + out.level( + "skippy.kv.l3.reserved", + "By", + "Bytes reserved by L3 writes in flight", + now.reserved_bytes, + ); + if let Some(available) = now.filesystem_available_bytes { + out.level( + "skippy.kv.l3.filesystem.available", + "By", + "Free space on the L3 store's filesystem", + available, + ); + } + let Some(was) = before else { + return; + }; + out.lookups("l3", (was.hits, now.hits), (was.misses, now.misses)); + out.per_second( + "skippy.kv.l3.fills", + "{fill}/s", + "Prefixes restored from L3", + was.fills, + now.fills, + ); + out.per_second( + "skippy.kv.l3.writes", + "{write}/s", + "Prefixes written to L3", + was.writes, + now.writes, + ); + out.per_second_by( + "skippy.kv.l3.io", + "By/s", + "L3 payload bytes, by direction", + "direction", + &[ + ("read", was.bytes_read, now.bytes_read), + ("write", was.bytes_written, now.bytes_written), + ], + ); + out.per_second( + "skippy.kv.l3.evictions", + "{manifest}/s", + "L3 entries removed to stay within budget", + was.evictions, + now.evictions, + ); + out.per_second( + "skippy.kv.l3.corrupt", + "{object}/s", + "L3 objects quarantined after failing verification", + was.corrupt, + now.corrupt, + ); +} + +fn record_queue_gauges(out: &mut Gauges<'_>, was: RecordQueueReading, now: RecordQueueReading) { + out.level( + "skippy.kv.record_queue.records", + "{record}", + "Exact-state records waiting to publish to L1 and write through to L3", + now.records, + ); + out.level( + "skippy.kv.record_queue.bytes", + "By", + "Payload bytes of waiting exact-state records", + now.bytes, + ); + out.per_second( + "skippy.kv.record_queue.dropped", + "{record}/s", + "Exact-state records dropped because the queue was full", + was.dropped, + now.dropped, + ); +} + +/// Tier readings for a resource snapshot, under `key`'s naming. +pub(super) fn snapshot(attrs: &mut BTreeMap, key: impl Fn(&str) -> String) { + let tiers = KvTiers::now(); + if tiers.stages == 0 { + return; + } + let mut put = |name: &str, value: u64| { + attrs.insert(key(name), json!(value)); + }; + put("kv.l1.entries", tiers.l1.entries); + put("kv.l1.tokens", tiers.l1.tokens); + put("kv.l1.recurrent_bytes", tiers.l1.recurrent_bytes); + put("kv.l1.hits", tiers.lookups.hits); + put("kv.l1.misses", tiers.lookups.misses); + if let Some(cells) = tiers.pool_cells { + put("kv.l1.pool_cells", cells); + } + if let Some(l2) = tiers.l2 { + put("kv.l2.bytes", l2.bytes); + put("kv.l2.hits", l2.hits); + put("kv.l2.misses", l2.misses); + } + if let Some(l3) = tiers.l3 { + if let Some(used) = l3.used_bytes { + put("kv.l3.used_bytes", used); + } + put("kv.l3.hits", l3.hits); + put("kv.l3.misses", l3.misses); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point}; + + fn values(metrics: &[Metric], name: &str) -> Vec<(Vec, f64)> { + let Some(Data::Gauge(gauge)) = metrics + .iter() + .find(|metric| metric.name == name) + .and_then(|metric| metric.data.clone()) + else { + return Vec::new(); + }; + gauge + .data_points + .iter() + .map(|point| { + let attributes = point + .attributes + .iter() + .filter_map(|attribute| attribute.value.as_ref()) + .map(|value| format!("{:?}", value.value)) + .collect(); + let value = match point.value { + Some(number_data_point::Value::AsDouble(value)) => value, + _ => f64::NAN, + }; + (attributes, value) + }) + .collect() + } + + fn only(metrics: &[Metric], name: &str) -> Option { + match values(metrics, name).as_slice() { + [(_, value)] => Some(*value), + _ => None, + } + } + + fn l3(store: usize, hits: u64) -> L3Reading { + L3Reading { + store, + used_bytes: Some(100), + budget_bytes: 1000, + filesystem_available_bytes: Some(store as u64 * 10), + hits, + ..L3Reading::default() + } + } + + #[test] + fn stages_sum_but_a_shared_l3_store_counts_once() { + let stage = |store, entries| KvTierReading { + l1: L1Reading { + entries, + ..L1Reading::default() + }, + l2: Some(L2Reading { + bytes: 10, + ..L2Reading::default() + }), + l3: Some(l3(store, 5)), + ..KvTierReading::default() + }; + let shared = KvTiers::sum([stage(1, 2), stage(1, 3)]); + assert_eq!(shared.stages, 2); + assert_eq!(shared.l1.entries, 5); + assert_eq!(shared.l2.map(|l2| l2.bytes), Some(20)); + assert_eq!(shared.l3.map(|l3| l3.hits), Some(5)); + + let separate = KvTiers::sum([stage(1, 2), stage(2, 3)]); + let l3 = separate.l3.expect("l3"); + assert_eq!((l3.hits, l3.used_bytes), (10, Some(200))); + assert_eq!(l3.filesystem_available_bytes, Some(10)); + } + + #[test] + fn pressure_and_misses_come_from_levels_and_the_interval() { + let before = KvTiers { + stages: 1, + lookups: L1Lookups { + hits: 10, + misses: 2, + ..L1Lookups::default() + }, + l2: Some(L2Reading { + hits: 1, + misses: 1, + ..L2Reading::default() + }), + l3: Some(l3(1, 4)), + ..KvTiers::default() + }; + let after = KvTiers { + l1: L1Reading { + recurrent_bytes: 256, + recurrent_limit_bytes: 1024, + attention_evictions: 3, + ..L1Reading::default() + }, + lookups: L1Lookups { + hits: 13, + misses: 3, + ..L1Lookups::default() + }, + l2: Some(L2Reading { + bytes: 50, + budget_bytes: 200, + hits: 1, + misses: 3, + ..L2Reading::default() + }), + l3: Some(L3Reading { + misses: 1, + ..l3(1, 4) + }), + pool_cells: Some(4096), + ..before + }; + let mut metrics = Vec::new(); + gauges(&mut metrics, &before, &after, Some(1024), 0.5, 9); + + assert_eq!(only(&metrics, "skippy.kv.l1.pool.utilization"), Some(0.25)); + assert_eq!( + only(&metrics, "skippy.kv.l1.recurrent.utilization"), + Some(0.25) + ); + assert_eq!(only(&metrics, "skippy.kv.l1.miss_ratio"), Some(0.25)); + let lookups = values(&metrics, "skippy.kv.l1.lookups"); + assert_eq!( + lookups.iter().map(|(_, rate)| *rate).collect::>(), + [6.0, 2.0] + ); + let evictions = values(&metrics, "skippy.kv.l1.evictions"); + assert_eq!(evictions[0].1, 6.0); + assert_eq!(only(&metrics, "skippy.kv.l2.utilization"), Some(0.25)); + assert_eq!(only(&metrics, "skippy.kv.l2.miss_ratio"), Some(1.0)); + assert_eq!(only(&metrics, "skippy.kv.l3.utilization"), Some(0.1)); + assert_eq!(only(&metrics, "skippy.kv.l3.miss_ratio"), Some(1.0)); + } + + #[test] + fn no_lookups_means_no_miss_ratio_and_no_stage_means_no_gauges() { + let tiers = KvTiers { + stages: 1, + ..KvTiers::default() + }; + let mut metrics = Vec::new(); + gauges(&mut metrics, &tiers, &tiers, None, 1.0, 1); + assert!(only(&metrics, "skippy.kv.l1.miss_ratio").is_none()); + assert!(only(&metrics, "skippy.kv.l1.pool.utilization").is_none()); + assert!(only(&metrics, "skippy.kv.l1.entries").is_some()); + + let mut metrics = Vec::new(); + gauges( + &mut metrics, + &KvTiers::default(), + &KvTiers::default(), + None, + 1.0, + 1, + ); + assert!(metrics.is_empty()); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs new file mode 100644 index 0000000000..23b6f5de70 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs @@ -0,0 +1,238 @@ +//! OTLP encoding of resource gauges and their two destinations: a JSON-lines +//! file in the OpenTelemetry file-exporter format, and the OTLP gRPC endpoint +//! traces go to. + +use std::{ + ffi::OsString, + fs::{File, OpenOptions}, + io::{BufWriter, Write}, + sync::{Mutex, PoisonError}, + time::Duration, +}; + +use opentelemetry_proto::tonic::{ + collector::metrics::v1::{ + ExportMetricsServiceRequest, metrics_service_client::MetricsServiceClient, + }, + common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}, + metrics::v1::{ + Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric, number_data_point, + }, + resource::v1::Resource, +}; +use skippy_protocol::StageConfig; +use tokio::{sync::mpsc, time::timeout}; + +use super::super::{otlp_encoding::key_values, resource_attrs::resource_attrs}; + +const EXPORT_TIMEOUT: Duration = Duration::from_secs(5); +/// Samples queued for the gRPC exporter before new ones are dropped. +const GRPC_QUEUE: usize = 64; + +pub(super) fn gauge( + name: &str, + unit: &str, + description: &str, + points: Vec, +) -> Metric { + Metric { + name: name.to_string(), + description: description.to_string(), + unit: unit.to_string(), + data: Some(metric::Data::Gauge(Gauge { + data_points: points, + })), + ..Default::default() + } +} + +pub(super) fn point( + time_unix_nano: u64, + value: f64, + attributes: &[(&str, &str)], +) -> NumberDataPoint { + NumberDataPoint { + attributes: attributes + .iter() + .map(|(key, value)| KeyValue { + key: (*key).to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue((*value).to_string())), + }), + ..Default::default() + }) + .collect(), + time_unix_nano, + value: Some(number_data_point::Value::AsDouble(value)), + ..Default::default() + } +} + +fn export_request(config: &StageConfig, metrics: Vec) -> ExportMetricsServiceRequest { + let attributes = resource_attrs(config, "skippy"); + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: Some(Resource { + attributes: key_values(attributes), + dropped_attributes_count: 0, + entity_refs: vec![], + }), + scope_metrics: vec![ScopeMetrics { + scope: Some(InstrumentationScope { + name: "skippy-serving".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + attributes: vec![], + dropped_attributes_count: 0, + }), + metrics, + schema_url: String::new(), + }], + schema_url: String::new(), + }], + } +} + +pub(super) struct MetricSinks { + file: Option>>, + grpc: Option>, +} + +impl MetricSinks { + /// The configured destinations; `None` when there are none. + pub(super) fn open(path: Option, endpoint: Option<&str>) -> Option { + let file = + path.and_then( + |path| match OpenOptions::new().create(true).append(true).open(&path) { + Ok(file) => Some(Mutex::new(BufWriter::new(file))), + Err(error) => { + tracing::warn!("telemetry metrics file {path:?} not opened: {error}"); + None + } + }, + ); + let grpc = endpoint.and_then(|endpoint| { + let handle = tokio::runtime::Handle::try_current().ok()?; + let (tx, rx) = mpsc::channel(GRPC_QUEUE); + handle.spawn(export_loop(endpoint.to_string(), rx)); + Some(tx) + }); + (file.is_some() || grpc.is_some()).then_some(Self { file, grpc }) + } + + pub(super) fn send(&self, config: &StageConfig, metrics: Vec) { + let request = export_request(config, metrics); + if let Some(file) = self.file.as_ref() { + let mut file = file.lock().unwrap_or_else(PoisonError::into_inner); + let written = serde_json::to_writer(&mut *file, &request) + .map_err(std::io::Error::from) + .and_then(|()| file.write_all(b"\n")) + .and_then(|()| file.flush()); + if let Err(error) = written { + tracing::warn!("telemetry metrics file write failed: {error}"); + } + } + if let Some(grpc) = self.grpc.as_ref() { + // A full queue means the endpoint is not keeping up; drop the sample. + let _ = grpc.try_send(request); + } + } + + pub(super) fn flush(&self) { + if let Some(file) = self.file.as_ref() { + let _ = file.lock().unwrap_or_else(PoisonError::into_inner).flush(); + } + } +} + +/// Export samples in order, reconnecting after a failure; a sample that +/// fails is dropped rather than retried, since the next one supersedes it. +async fn export_loop(endpoint: String, mut rx: mpsc::Receiver) { + let mut client = None; + while let Some(request) = rx.recv().await { + if client.is_none() { + client = timeout( + EXPORT_TIMEOUT, + MetricsServiceClient::connect(endpoint.clone()), + ) + .await + .ok() + .and_then(Result::ok); + } + let Some(connected) = client.as_mut() else { + continue; + }; + if !matches!( + timeout(EXPORT_TIMEOUT, connected.export(request)).await, + Ok(Ok(_)) + ) { + client = None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + + fn stage_config() -> StageConfig { + serde_json::from_value(json!({ + "run_id": "run", + "topology_id": "topology", + "model_id": "org/model:Q4_K_M", + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": 4, + "load_mode": "runtime-slice", + "execution_contract": "", + "bind_addr": "127.0.0.1:0", + })) + .expect("minimal stage config") + } + + #[test] + fn a_sample_is_one_otlp_json_line_under_the_skippy_service() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("metrics.jsonl"); + let sinks = + MetricSinks::open(Some(path.clone().into_os_string()), None).expect("file sink"); + sinks.send( + &stage_config(), + vec![gauge( + "skippy.gpu.busy", + "1", + "busy", + vec![point(5, 0.25, &[("device", "MTL0")])], + )], + ); + sinks.flush(); + + let text = std::fs::read_to_string(&path).expect("metrics file"); + let lines = text.lines().collect::>(); + assert_eq!(lines.len(), 1); + let request: Value = serde_json::from_str(lines[0]).expect("json line"); + let resource = &request["resourceMetrics"][0]; + let service = resource["resource"]["attributes"] + .as_array() + .expect("attributes") + .iter() + .find(|attribute| attribute["key"] == "service.name") + .map(|attribute| attribute["value"]["stringValue"].clone()); + assert_eq!(service, Some(json!("skippy"))); + let metric = &resource["scopeMetrics"][0]["metrics"][0]; + assert_eq!(metric["name"], "skippy.gpu.busy"); + let point = &metric["gauge"]["dataPoints"][0]; + assert_eq!(point["asDouble"], json!(0.25)); + assert_eq!(point["timeUnixNano"], json!("5")); + assert_eq!( + point["attributes"][0]["value"]["stringValue"], + json!("MTL0") + ); + } + + #[test] + fn no_destination_means_no_sinks() { + assert!(MetricSinks::open(None, None).is_none()); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_usage.rs b/skippy/crates/skippy-serving/src/telemetry/resource_usage.rs new file mode 100644 index 0000000000..490dde82b1 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/resource_usage.rs @@ -0,0 +1,310 @@ +//! Point-in-time readings of this process's and the system's CPU and memory +//! use, from the operating system. macOS reads Mach and libproc counters +//! (the footprint Activity Monitor shows, wired memory, page-ins, the memory +//! compressor and swap); Linux reads `getrusage` and `/proc`. Elsewhere there +//! are no readings. + +use std::time::Duration; + +/// Cumulative CPU time and current memory of this process. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct ProcessUsage { + pub(super) user: Duration, + pub(super) system: Duration, + pub(super) resident_bytes: u64, + /// Memory charged to the process; on macOS this includes Metal buffers. + pub(super) footprint_bytes: u64, + pub(super) wired_bytes: Option, + /// Pages read in from disk since start: mapped weights being faulted in. + pub(super) pageins: u64, + pub(super) disk_read_bytes: Option, +} + +/// Cumulative system paging, in pages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Paging { + pub(super) pageins: u64, + pub(super) pageouts: u64, + pub(super) swapins: u64, + pub(super) swapouts: u64, +} + +/// System memory, by state. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct SystemMemory { + pub(super) total_bytes: u64, + /// `(state, bytes)`, such as `("free", ..)` or `("compressed", ..)`. + pub(super) states: Vec<(&'static str, u64)>, + pub(super) swap_used_bytes: u64, + /// macOS memory pressure: 1 normal, 2 warning, 4 critical. + pub(super) pressure_level: Option, + pub(super) paging: Option, + pub(super) page_bytes: u64, +} + +pub(super) fn process_usage() -> Option { + platform::process_usage() +} + +pub(super) fn system_memory() -> Option { + platform::system_memory() +} + +/// User and system CPU time of this process, from `getrusage`. +#[cfg(unix)] +fn cpu_times() -> Option<(Duration, Duration)> { + let mut usage = std::mem::MaybeUninit::::zeroed(); + // SAFETY: getrusage fills the struct for RUSAGE_SELF. + if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } != 0 { + return None; + } + // SAFETY: initialised by the successful call above. + let usage = unsafe { usage.assume_init() }; + let time = |tv: libc::timeval| { + Duration::from_secs(u64::try_from(tv.tv_sec).unwrap_or(0)) + + Duration::from_micros(u64::try_from(tv.tv_usec).unwrap_or(0)) + }; + Some((time(usage.ru_utime), time(usage.ru_stime))) +} + +#[cfg(target_os = "macos")] +mod platform { + use std::ffi::{CStr, c_void}; + use std::mem::{MaybeUninit, size_of}; + use std::sync::OnceLock; + + use super::{Paging, ProcessUsage, SystemMemory, cpu_times}; + + pub(super) fn process_usage() -> Option { + let (user, system) = cpu_times()?; + let mut info = MaybeUninit::::zeroed(); + // SAFETY: proc_pid_rusage writes a rusage_info_v2 for RUSAGE_INFO_V2. + let status = unsafe { + libc::proc_pid_rusage( + libc::getpid(), + libc::RUSAGE_INFO_V2, + info.as_mut_ptr().cast(), + ) + }; + if status != 0 { + return Some(ProcessUsage { + user, + system, + ..ProcessUsage::default() + }); + } + // SAFETY: initialised by the successful call above. + let info = unsafe { info.assume_init() }; + Some(ProcessUsage { + user, + system, + resident_bytes: info.ri_resident_size, + footprint_bytes: info.ri_phys_footprint, + wired_bytes: Some(info.ri_wired_size), + pageins: info.ri_pageins, + disk_read_bytes: Some(info.ri_diskio_bytesread), + }) + } + + pub(super) fn system_memory() -> Option { + let page_bytes = page_bytes(); + let mut stats = MaybeUninit::::zeroed(); + let mut count = libc::HOST_VM_INFO64_COUNT; + // SAFETY: host_statistics64 writes at most `count` integers of stats. + let status = unsafe { + libc::host_statistics64( + host_port(), + libc::HOST_VM_INFO64, + stats.as_mut_ptr().cast(), + &mut count, + ) + }; + if status != libc::KERN_SUCCESS { + return None; + } + // SAFETY: initialised (up to what the kernel knows) by the call above. + let stats = unsafe { stats.assume_init() }; + let bytes = |pages: u64| pages.saturating_mul(page_bytes); + let swap = sysctl::(c"vm.swapusage"); + Some(SystemMemory { + total_bytes: sysctl::(c"hw.memsize").unwrap_or(0), + states: vec![ + ("free", bytes(u64::from(stats.free_count))), + ("active", bytes(u64::from(stats.active_count))), + ("inactive", bytes(u64::from(stats.inactive_count))), + ("wired", bytes(u64::from(stats.wire_count))), + ("compressed", bytes(u64::from(stats.compressor_page_count))), + ], + swap_used_bytes: swap.map_or(0, |swap| swap.xsu_used), + pressure_level: sysctl::(c"kern.memorystatus_vm_pressure_level"), + paging: Some(Paging { + pageins: stats.pageins, + pageouts: stats.pageouts, + swapins: stats.swapins, + swapouts: stats.swapouts, + }), + page_bytes, + }) + } + + unsafe extern "C" { + // libc deprecates its binding in favour of the mach2 crate. + fn mach_host_self() -> libc::mach_port_t; + } + + /// The host port, taken once: each `mach_host_self` adds a port reference. + fn host_port() -> libc::mach_port_t { + static PORT: OnceLock = OnceLock::new(); + // SAFETY: returns a send right to this host; no arguments. + *PORT.get_or_init(|| unsafe { mach_host_self() }) + } + + fn page_bytes() -> u64 { + // SAFETY: sysconf takes no pointers. + u64::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap_or(16_384) + } + + /// A fixed-size sysctl value; `None` when absent or of another size. + fn sysctl(name: &CStr) -> Option { + let mut value = MaybeUninit::::zeroed(); + let mut len = size_of::(); + // SAFETY: sysctlbyname writes at most `len` bytes into `value`. + let status = unsafe { + libc::sysctlbyname( + name.as_ptr(), + value.as_mut_ptr().cast::(), + &mut len, + std::ptr::null_mut(), + 0, + ) + }; + // SAFETY: fully written when the call succeeded with the full size. + (status == 0 && len == size_of::()).then(|| unsafe { value.assume_init() }) + } +} + +#[cfg(target_os = "linux")] +mod platform { + use super::{ProcessUsage, SystemMemory, cpu_times}; + + pub(super) fn process_usage() -> Option { + let (user, system) = cpu_times()?; + let page_bytes = page_bytes(); + let resident_bytes = std::fs::read_to_string("/proc/self/statm") + .ok() + .and_then(|statm| statm.split_whitespace().nth(1)?.parse::().ok()) + .map_or(0, |pages| pages.saturating_mul(page_bytes)); + let mut usage = std::mem::MaybeUninit::::zeroed(); + // SAFETY: getrusage fills the struct for RUSAGE_SELF. + let pageins = if unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) } == 0 { + // SAFETY: initialised by the successful call above. + u64::try_from(unsafe { usage.assume_init() }.ru_majflt).unwrap_or(0) + } else { + 0 + }; + Some(ProcessUsage { + user, + system, + resident_bytes, + footprint_bytes: resident_bytes, + wired_bytes: None, + pageins, + disk_read_bytes: None, + }) + } + + pub(super) fn system_memory() -> Option { + let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?; + let field = |name: &str| meminfo_bytes(&meminfo, name).unwrap_or(0); + let total_bytes = field("MemTotal"); + let available = field("MemAvailable"); + Some(SystemMemory { + total_bytes, + states: vec![ + ("free", field("MemFree")), + ("available", available), + ("used", total_bytes.saturating_sub(available)), + ], + swap_used_bytes: field("SwapTotal").saturating_sub(field("SwapFree")), + pressure_level: None, + paging: None, + page_bytes: page_bytes(), + }) + } + + /// A `/proc/meminfo` field, which the kernel reports in KiB. + pub(super) fn meminfo_bytes(meminfo: &str, name: &str) -> Option { + meminfo.lines().find_map(|line| { + let rest = line.strip_prefix(name)?.strip_prefix(':')?; + let kib = rest.split_whitespace().next()?.parse::().ok()?; + Some(kib.saturating_mul(1024)) + }) + } + + fn page_bytes() -> u64 { + // SAFETY: sysconf takes no pointers. + u64::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap_or(4096) + } +} + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +mod platform { + use super::{ProcessUsage, SystemMemory}; + + pub(super) fn process_usage() -> Option { + None + } + + pub(super) fn system_memory() -> Option { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn this_process_has_cpu_time_and_resident_memory() { + let usage = process_usage().expect("process usage"); + assert!(usage.resident_bytes > 0); + assert!(usage.footprint_bytes > 0); + let busy = std::time::Instant::now(); + while busy.elapsed() < Duration::from_millis(20) { + std::hint::black_box(busy.elapsed()); + } + let later = process_usage().expect("process usage"); + assert!(later.user + later.system > usage.user + usage.system); + } + + #[test] + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn the_system_reports_total_and_free_memory() { + let memory = system_memory().expect("system memory"); + assert!(memory.total_bytes > 0); + let free = memory + .states + .iter() + .find(|(state, _)| *state == "free") + .map(|(_, bytes)| *bytes) + .expect("free memory"); + assert!(free <= memory.total_bytes); + assert!(memory.page_bytes >= 4096); + } + + #[test] + #[cfg(target_os = "linux")] + fn meminfo_fields_are_read_in_kib() { + let meminfo = "MemTotal: 16384 kB\nMemFree: 2048 kB\nMemAvailableX: 1 kB\n"; + assert_eq!( + platform::meminfo_bytes(meminfo, "MemTotal"), + Some(16_384 * 1024) + ); + assert_eq!( + platform::meminfo_bytes(meminfo, "MemFree"), + Some(2048 * 1024) + ); + assert_eq!(platform::meminfo_bytes(meminfo, "MemAvailable"), None); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/span_components.rs b/skippy/crates/skippy-serving/src/telemetry/span_components.rs new file mode 100644 index 0000000000..da7b0572ca --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/span_components.rs @@ -0,0 +1,122 @@ +//! Which part of the system a span belongs to, exported as the span's +//! `service.name` (within the `skippy` service namespace). Trace viewers +//! colour a multi-service trace by service, so llama, Metal and each layer of +//! serving get their own colour while staying one trace. +//! +//! Classification is by span name. Serving names its spans `stage.*`, plus +//! `skippy.process` for the root and `native.*` for native ABI calls; the +//! native runtime names its own phases `skippy.*`, `llama.*` and `mtl.*`. + +/// The `service.namespace` every component shares. +pub(super) const SERVICE_NAMESPACE: &str = "skippy"; + +/// The component, and so the exported `service.name`, of a span named `name`. +pub(super) fn component(name: &str) -> &'static str { + let starts = |prefix: &str| name.starts_with(prefix); + if name == "skippy.process" { + return "skippy"; + } + if starts("native.") { + return "skippy-native"; + } + if starts("llama.") { + return "llama"; + } + if starts("mtl.library_") || starts("mtl.pipeline_") { + return "metal-compile"; + } + if starts("mtl.") { + return "metal-gpu"; + } + if starts("skippy.") { + return "skippy-runtime"; + } + serving_component(name) +} + +/// Serving's own `stage.*` spans, by the layer that emits them. +fn serving_component(name: &str) -> &'static str { + let starts = |prefix: &str| name.starts_with(prefix); + if is_kv(name) { + "skippy-kv" + } else if starts("stage.scheduler") || starts("stage.runtime_") { + "skippy-scheduler" + } else if starts("stage.embedded_runtime") + || starts("stage.openai_server_") + || starts("stage.openai_runtime_") + { + "skippy" + } else if [ + "stage.openai_prefill", + "stage.openai_media_prefill", + "stage.openai_decode", + "stage.openai_generation", + "stage.openai_scheduler_generation", + "stage.openai_linear_proposal", + ] + .iter() + .any(|prefix| starts(prefix)) + { + "skippy-decode" + } else if starts("stage.openai_") { + "skippy-http" + } else if starts("stage.binary_") { + "skippy-transport" + } else { + "skippy" + } +} + +/// KV cache and session-slot work: lookups, records, payloads, alignment. +fn is_kv(name: &str) -> bool { + name.starts_with("stage.openai_session_") + || name.split(['.', '_']).any(|segment| segment == "kv") +} + +#[cfg(test)] +mod tests { + use super::component; + + #[test] + fn native_runtime_spans_are_told_apart_from_serving() { + assert_eq!(component("skippy.process"), "skippy"); + assert_eq!( + component("native.skippy_iteration_batch_sampled"), + "skippy-native" + ); + assert_eq!(component("skippy.sample"), "skippy-runtime"); + assert_eq!(component("llama.graph_compute"), "llama"); + assert_eq!(component("mtl.pipeline_compile"), "metal-compile"); + assert_eq!(component("mtl.library_compile"), "metal-compile"); + assert_eq!(component("mtl.command_buffer"), "metal-gpu"); + assert_eq!(component("mtl.execute"), "metal-gpu"); + } + + #[test] + fn serving_spans_follow_their_layer() { + let cases = [ + ("stage.embedded_runtime_load", "skippy"), + ("stage.openai_server_setup", "skippy"), + ("stage.openai_runtime_prewarm", "skippy"), + ("stage.scheduler_iteration", "skippy-scheduler"), + ("stage.scheduler", "skippy-scheduler"), + ("stage.scheduler_coalesce", "skippy-scheduler"), + ("stage.runtime_lock_wait", "skippy-scheduler"), + ("stage.openai_http_request", "skippy-http"), + ("stage.openai_chat_template", "skippy-http"), + ("stage.openai_tokenize", "skippy-http"), + ("stage.openai_generation_summary", "skippy-decode"), + ("stage.openai_prefill", "skippy-decode"), + ("stage.openai_decode_token", "skippy-decode"), + ("stage.openai_kv_lookup_decision", "skippy-kv"), + ("stage.binary_kv_record_decision", "skippy-kv"), + ("stage.kv_payload_selected", "skippy-kv"), + ("stage.openai_session_stop", "skippy-kv"), + ("stage.binary_downstream_write", "skippy-transport"), + ("stage.something_new", "skippy"), + ]; + for (name, expected) in cases { + assert_eq!(component(name), expected, "{name}"); + } + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs b/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs new file mode 100644 index 0000000000..517f15b1a1 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs @@ -0,0 +1,157 @@ +//! The `SKIPPY_TELEMETRY_STDERR` debug sink: Skippy's own event JSON, one +//! line per span or event, written to stderr by a background thread. + +use std::{ + collections::BTreeMap, + env, + io::{BufWriter, Write}, + sync::{OnceLock, mpsc as std_mpsc}, + thread::{self, JoinHandle}, +}; + +use serde::Serialize; +use serde_json::Value; + +static STDERR_SINK: OnceLock = OnceLock::new(); +/// Whether the stderr debug sink is enabled via `SKIPPY_TELEMETRY_STDERR`. +/// +/// Read once: this is consulted on the record and lookup paths, which run per +/// request. +pub(super) fn stderr_sink_enabled() -> bool { + *STDERR_SINK.get_or_init(|| { + stderr_sink_enabled_from_value(env::var("SKIPPY_TELEMETRY_STDERR").ok().as_deref()) + }) +} + +fn stderr_sink_enabled_from_value(value: Option<&str>) -> bool { + value.is_some_and(|value| { + !matches!( + value.trim().to_ascii_lowercase().as_str(), + "" | "0" | "false" | "no" | "off" + ) + }) +} + +#[derive(Serialize)] +pub(super) struct StderrTelemetryEvent { + pub(super) event: String, + pub(super) attributes: BTreeMap, + pub(super) start_time_unix_nanos: u64, + pub(super) end_time_unix_nanos: u64, +} + +pub(super) struct StderrTelemetrySink { + tx: Option>, + worker: Option>, +} + +impl StderrTelemetrySink { + fn channel( + capacity: usize, + ) -> ( + std_mpsc::SyncSender, + std_mpsc::Receiver, + ) { + // Disabled telemetry supplies zero capacity. The stderr override can + // enable it later, so give that opt-in sink the same bounded default + // as debug telemetry instead of a one-event queue that loses bursts. + std_mpsc::sync_channel(if capacity == 0 { 1024 } else { capacity }) + } + + pub(super) fn new(capacity: usize) -> Option { + let (tx, rx) = Self::channel(capacity); + let worker = thread::Builder::new() + .name("skippy-telemetry-stderr".to_string()) + .spawn(move || stderr_telemetry_loop(rx)) + .ok()?; + Some(Self { + tx: Some(tx), + worker: Some(worker), + }) + } + + pub(super) fn try_send(&self, event: StderrTelemetryEvent) -> bool { + self.tx + .as_ref() + .is_some_and(|tx| tx.try_send(event).is_ok()) + } +} + +impl Drop for StderrTelemetrySink { + fn drop(&mut self) { + self.tx.take(); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +fn stderr_telemetry_loop(rx: std_mpsc::Receiver) { + while let Ok(event) = rx.recv() { + let stderr = std::io::stderr(); + let mut writer = BufWriter::new(stderr.lock()); + if serde_json::to_writer(&mut writer, &event).is_err() || writer.write_all(b"\n").is_err() { + return; + } + while let Ok(event) = rx.try_recv() { + if serde_json::to_writer(&mut writer, &event).is_err() + || writer.write_all(b"\n").is_err() + { + return; + } + } + if writer.flush().is_err() { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::{StderrTelemetryEvent, StderrTelemetrySink, stderr_sink_enabled_from_value}; + + #[test] + fn stderr_queue_buffers_disabled_config_bursts_and_respects_explicit_bounds() { + for (configured, expected) in [(0, 1024), (1, 1), (8, 8)] { + let (tx, rx) = StderrTelemetrySink::channel(configured); + let event = || StderrTelemetryEvent { + event: "stage.binary_request_summary".into(), + attributes: Default::default(), + start_time_unix_nanos: 1, + end_time_unix_nanos: 2, + }; + for _ in 0..expected { + tx.try_send(event()).expect("burst fits configured buffer"); + } + assert!(matches!( + tx.try_send(event()), + Err(std::sync::mpsc::TrySendError::Full(_)) + )); + assert_eq!(rx.try_iter().count(), expected); + tx.try_send(event()).expect("drained buffer accepts events"); + } + } + + #[test] + fn stderr_sink_false_values_do_not_enable_debug_telemetry() { + for value in [ + None, + Some(""), + Some("0"), + Some("false"), + Some("no"), + Some("off"), + ] { + assert!(!stderr_sink_enabled_from_value(value), "value={value:?}"); + } + for value in [ + Some("1"), + Some("true"), + Some("yes"), + Some("on"), + Some("debug"), + ] { + assert!(stderr_sink_enabled_from_value(value), "value={value:?}"); + } + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/trace_context.rs b/skippy/crates/skippy-serving/src/telemetry/trace_context.rs new file mode 100644 index 0000000000..209bc9c089 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/trace_context.rs @@ -0,0 +1,547 @@ +//! Trace context for Skippy telemetry. +//! +//! One trace covers the whole process under a root span. A span's parent is +//! whatever is active where it starts: the innermost span entered on this +//! thread, else the span of the enclosing tokio task, else the root. Point +//! events attach to that same span. Work batched for several requests, such +//! as a scheduler iteration, links to the request spans bound to its sequence +//! ids. + +use std::{ + cell::RefCell, + collections::{BTreeMap, HashMap, hash_map::RandomState}, + future::Future, + hash::{BuildHasher, Hasher}, + marker::PhantomData, + sync::{ + Arc, Mutex, OnceLock, PoisonError, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +use serde_json::Value; + +/// Events beyond this stay standalone spans rather than growing a buffer. +const SPAN_EVENT_LIMIT: usize = 1024; +const ROOT_EVENT_LIMIT: usize = 10_000; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct SpanContext { + pub(crate) trace_id: [u8; 16], + pub(crate) span_id: [u8; 8], +} + +#[derive(Clone, Debug)] +pub(crate) struct SpanEvent { + pub(crate) name: String, + pub(crate) time_unix_nanos: u64, + pub(crate) attributes: BTreeMap, +} + +struct EventBuffer { + events: Mutex>, + closed: AtomicBool, + limit: usize, +} + +impl EventBuffer { + fn new(limit: usize) -> Arc { + Arc::new(Self { + events: Mutex::new(Vec::new()), + closed: AtomicBool::new(false), + limit, + }) + } + + fn record(&self, event: SpanEvent) -> Result<(), SpanEvent> { + let mut events = self.events.lock().unwrap_or_else(PoisonError::into_inner); + if self.closed.load(Ordering::Acquire) || events.len() >= self.limit { + return Err(event); + } + events.push(event); + Ok(()) + } + + fn close(&self) -> Vec { + let mut events = self.events.lock().unwrap_or_else(PoisonError::into_inner); + self.closed.store(true, Ordering::Release); + std::mem::take(&mut events) + } +} + +/// A span other telemetry can attach to: its identity, its parent, and the +/// events recorded while it is open. +#[derive(Clone)] +pub(crate) struct Frame { + context: SpanContext, + parent: Option<[u8; 8]>, + events: Arc, +} + +impl Frame { + /// A new span under whatever is active here. + pub(crate) fn child() -> Self { + current_frame_or_root().new_child() + } + + /// A new span under this one, wherever it is created. + pub(crate) fn new_child(&self) -> Self { + Self { + context: SpanContext { + trace_id: self.context.trace_id, + span_id: next_span_id(), + }, + parent: Some(self.context.span_id), + events: EventBuffer::new(SPAN_EVENT_LIMIT), + } + } + + /// A new span under `parent`, which may be on another thread or ended. + pub(crate) fn under(parent: SpanContext) -> Self { + Self { + context: SpanContext { + trace_id: parent.trace_id, + span_id: next_span_id(), + }, + parent: Some(parent.span_id), + events: EventBuffer::new(SPAN_EVENT_LIMIT), + } + } + + /// The span native code already identified by `tag`, under `parent`. + pub(crate) fn tagged_under(parent: SpanContext, tag: u64) -> Self { + Self { + context: SpanContext { + trace_id: parent.trace_id, + span_id: tag.to_be_bytes(), + }, + parent: Some(parent.span_id), + events: EventBuffer::new(SPAN_EVENT_LIMIT), + } + } + + pub(crate) fn context(&self) -> SpanContext { + self.context + } + + /// The span id as a nonzero integer, for native code that can only carry + /// a `u64`; [`context_for_tag`] turns it back into a parent. + pub(crate) fn tag(&self) -> u64 { + u64::from_be_bytes(self.context.span_id) + } + + pub(crate) fn parent_span_id(&self) -> Option<[u8; 8]> { + self.parent + } + + /// Make this the active span on this thread until the guard drops. For + /// synchronous code; async code uses [`Frame::enter_task`]. + pub(crate) fn enter(&self) -> Entered { + // Pushing can only fail while the thread is tearing down; the guard + // then removes nothing, which leaves the stack consistent. + let depth = STACK + .try_with(|stack| { + let mut stack = stack.borrow_mut(); + stack.push(self.clone()); + stack.len() - 1 + }) + .ok(); + Entered { + depth, + _not_send: PhantomData, + } + } + + /// Make this the active span of the current task until the guard drops. + /// The guard is `Send`, so it may be held across `.await`. Outside a task + /// scope (see [`in_task`]) there is nothing to attach to and it is inert. + pub(crate) fn enter_task(&self) -> TaskEntered { + let stack = TASK_STACK.try_with(Arc::clone).ok(); + if let Some(stack) = stack.as_ref() { + stack + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(self.clone()); + } + TaskEntered { + stack, + span_id: self.context.span_id, + } + } + + /// Attach an event; hands it back once the span has ended or is full. + pub(crate) fn record_event(&self, event: SpanEvent) -> Result<(), SpanEvent> { + self.events.record(event) + } + + /// End event collection and take what was recorded. + pub(crate) fn take_events(&self) -> Vec { + self.events.close() + } +} + +/// Keeps a span active on the current thread. Not `Send`, so it cannot be +/// held across an `.await` that may resume elsewhere. Dropping it also ends +/// any span entered above it that was left behind, so a missed guard cannot +/// leak into later work on the thread. +#[must_use = "the span is only active while the guard is alive"] +pub(crate) struct Entered { + depth: Option, + _not_send: PhantomData<*const ()>, +} + +impl Drop for Entered { + fn drop(&mut self) { + if let Some(depth) = self.depth { + let _ = STACK.try_with(|stack| stack.borrow_mut().truncate(depth)); + } + } +} + +type TaskStack = Arc>>; + +/// Keeps a span active for the task that entered it. Dropping it, on any +/// thread, removes that span and anything entered above it. +#[must_use = "the span is only active while the guard is alive"] +pub(crate) struct TaskEntered { + stack: Option, + span_id: [u8; 8], +} + +impl Drop for TaskEntered { + fn drop(&mut self) { + let Some(stack) = self.stack.as_ref() else { + return; + }; + let mut stack = stack.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(depth) = stack + .iter() + .rposition(|frame| frame.context.span_id == self.span_id) + { + stack.truncate(depth); + } + } +} + +thread_local! { + static STACK: RefCell> = const { RefCell::new(Vec::new()) }; +} + +tokio::task_local! { + static TASK_STACK: TaskStack; +} + +/// The innermost active span: this thread's, else the current task's. +pub(crate) fn current_frame() -> Option { + STACK + .try_with(|stack| stack.borrow().last().cloned()) + .ok() + .flatten() + .or_else(|| { + TASK_STACK + .try_with(|stack| { + stack + .lock() + .unwrap_or_else(PoisonError::into_inner) + .last() + .cloned() + }) + .ok() + .flatten() + }) +} + +/// The span a [`Frame::tag`] names, in this process's trace; the root for 0. +pub(crate) fn context_for_tag(tag: u64) -> SpanContext { + let root = process().root().context(); + if tag == 0 { + return root; + } + SpanContext { + trace_id: root.trace_id, + span_id: tag.to_be_bytes(), + } +} + +pub(crate) fn current_frame_or_root() -> Frame { + current_frame().unwrap_or_else(|| process().root().clone()) +} + +/// Run `future` with `frame` as the span of its task. +pub(crate) async fn in_task(frame: Frame, future: F) -> F::Output { + TASK_STACK + .scope(Arc::new(Mutex::new(vec![frame])), future) + .await +} + +/// Carry the caller's active span onto the thread that runs `work`. +pub(crate) fn propagate(work: F) -> impl FnOnce() -> T + Send + 'static +where + F: FnOnce() -> T + Send + 'static, +{ + let frame = current_frame(); + move || { + let _entered = frame.as_ref().map(Frame::enter); + work() + } +} + +/// The process root span, created on first use. +pub(crate) struct ProcessTrace { + root: Frame, + start_unix_nanos: u64, + finished: AtomicBool, +} + +impl ProcessTrace { + pub(crate) fn root(&self) -> &Frame { + &self.root + } + + pub(crate) fn start_unix_nanos(&self) -> u64 { + self.start_unix_nanos + } + + /// True for exactly one caller: the one that ends the process span. + pub(crate) fn begin_finish(&self) -> bool { + !self.finished.swap(true, Ordering::AcqRel) + } + + /// Whether the process span has ended: the process is shutting down. + pub(crate) fn is_finished(&self) -> bool { + self.finished.load(Ordering::Acquire) + } +} + +static PROCESS: OnceLock = OnceLock::new(); +static NEXT_SPAN_ID: AtomicU64 = AtomicU64::new(1); + +pub(crate) fn process() -> &'static ProcessTrace { + PROCESS.get_or_init(|| ProcessTrace { + root: Frame { + context: SpanContext { + trace_id: new_trace_id(), + span_id: next_span_id(), + }, + parent: None, + events: EventBuffer::new(ROOT_EVENT_LIMIT), + }, + start_unix_nanos: u64::try_from(super::now_unix_nanos()).unwrap_or_default(), + finished: AtomicBool::new(false), + }) +} + +fn next_span_id() -> [u8; 8] { + NEXT_SPAN_ID.fetch_add(1, Ordering::Relaxed).to_be_bytes() +} + +/// Per-process random keys make the id unique across runs without a new +/// dependency; it identifies a trace and is not a secret. +fn new_trace_id() -> [u8; 16] { + let state = RandomState::new(); + let mut id = [0_u8; 16]; + for (half, bytes) in id.as_chunks_mut::<8>().0.iter_mut().enumerate() { + let mut hasher = state.build_hasher(); + hasher.write_i64(super::now_unix_nanos()); + hasher.write_u32(std::process::id()); + hasher.write_usize(half); + *bytes = hasher.finish().to_be_bytes(); + } + id +} + +static SEQUENCES: OnceLock>> = OnceLock::new(); + +fn sequences() -> &'static Mutex> { + SEQUENCES.get_or_init(|| Mutex::new(HashMap::new())) +} + +/// Ties a scheduler sequence or session id to the span that submitted it. +#[must_use = "the binding is removed when the guard drops"] +pub(crate) struct BoundSequence { + id: String, + context: SpanContext, +} + +impl Drop for BoundSequence { + fn drop(&mut self) { + let mut sequences = sequences().lock().unwrap_or_else(PoisonError::into_inner); + if sequences.get(&self.id) == Some(&self.context) { + sequences.remove(&self.id); + } + } +} + +/// Bind `id` to the active span for as long as the guard lives. +pub(crate) fn bind_sequence(id: &str) -> BoundSequence { + let context = current_frame_or_root().context(); + sequences() + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(id.to_string(), context); + BoundSequence { + id: id.to_string(), + context, + } +} + +pub(crate) fn sequence_context(id: &str) -> Option { + sequences() + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(id) + .copied() +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::{ + Frame, SpanEvent, bind_sequence, current_frame, current_frame_or_root, in_task, process, + propagate, sequence_context, + }; + + fn current_context() -> super::SpanContext { + current_frame_or_root().context() + } + + fn event(name: &str) -> SpanEvent { + SpanEvent { + name: name.to_string(), + time_unix_nanos: 1, + attributes: BTreeMap::new(), + } + } + + #[test] + fn spans_nest_under_the_entered_span_and_share_the_process_trace() { + let outer = Frame::child(); + let _outer = outer.enter(); + let inner = Frame::child(); + assert_eq!(inner.parent_span_id(), Some(outer.context().span_id)); + assert_eq!( + inner.context().trace_id, + process().root().context().trace_id + ); + { + let _inner = inner.enter(); + assert_eq!(current_frame_or_root().context(), inner.context()); + } + assert_eq!(current_frame_or_root().context(), outer.context()); + } + + #[test] + fn without_an_active_span_work_attaches_to_the_root() { + let handle = std::thread::spawn(|| current_frame_or_root().context()); + assert_eq!(handle.join().unwrap(), process().root().context()); + } + + #[test] + fn propagated_work_runs_under_the_callers_span() { + let frame = Frame::child(); + let _entered = frame.enter(); + let work = propagate(|| current_frame().map(|frame| frame.context())); + let observed = std::thread::spawn(work).join().unwrap(); + assert_eq!(observed, Some(frame.context())); + } + + #[test] + fn task_scope_supplies_the_span_to_async_work() { + let frame = Frame::child(); + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let observed = runtime.block_on(in_task(frame.clone(), async { + current_frame().unwrap().context() + })); + assert_eq!(observed, frame.context()); + } + + #[test] + fn events_stop_attaching_once_the_span_ends() { + let frame = Frame::child(); + assert!(frame.record_event(event("first")).is_ok()); + let events = frame.take_events(); + assert_eq!(events.len(), 1); + assert_eq!(frame.record_event(event("late")).unwrap_err().name, "late"); + } + + #[test] + fn sequence_bindings_last_as_long_as_their_guard() { + let frame = Frame::child(); + let _entered = frame.enter(); + { + let _bound = bind_sequence("trace-context-test-seq"); + assert_eq!( + sequence_context("trace-context-test-seq"), + Some(frame.context()) + ); + } + assert_eq!(sequence_context("trace-context-test-seq"), None); + } + + #[test] + fn leaving_a_thread_scope_ends_spans_left_inside_it() { + let outer = Frame::child(); + let leaked = Frame::child(); + { + let _outer = outer.enter(); + std::mem::forget(leaked.enter()); + assert_eq!(current_context(), leaked.context()); + } + assert_ne!(current_context(), outer.context()); + assert_ne!(current_context(), leaked.context()); + } + + #[test] + fn task_spans_nest_across_awaits_and_end_from_any_thread() { + let request = Frame::child(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .build() + .unwrap(); + let (phase, during, after) = runtime.block_on(in_task(request.clone(), async { + let phase = current_frame_or_root().new_child(); + let entered = phase.enter_task(); + tokio::task::yield_now().await; + let during = current_context(); + // A guard moved off the task still ends its span. + std::thread::spawn(move || drop(entered)).join().unwrap(); + (phase, during, current_context()) + })); + assert_eq!(phase.parent_span_id(), Some(request.context().span_id)); + assert_eq!(during, phase.context()); + assert_eq!(after, request.context()); + } + + #[test] + fn a_tag_names_its_span_for_children_made_elsewhere() { + let call = Frame::child(); + assert_ne!(call.tag(), 0); + let parent = super::context_for_tag(call.tag()); + assert_eq!(parent, call.context()); + let gpu = std::thread::spawn(move || Frame::under(parent)) + .join() + .unwrap(); + assert_eq!(gpu.parent_span_id(), Some(call.context().span_id)); + assert_eq!(super::context_for_tag(0), process().root().context()); + } + + #[test] + fn a_tagged_span_keeps_the_id_native_code_gave_it() { + let call = Frame::child(); + let native = Frame::tagged_under(call.context(), (1 << 63) | 9); + assert_eq!(native.tag(), (1 << 63) | 9); + assert_eq!(native.parent_span_id(), Some(call.context().span_id)); + assert_eq!(native.context().trace_id, call.context().trace_id); + assert_eq!(super::context_for_tag(native.tag()), native.context()); + } + + #[test] + fn outside_a_task_scope_a_task_guard_is_inert() { + let frame = Frame::child(); + let _entered = frame.enter_task(); + assert_ne!(current_context(), frame.context()); + } +} diff --git a/skippy/docs/PROMPT_CACHE.md b/skippy/docs/PROMPT_CACHE.md index b5e6b3988f..543ebf5648 100644 --- a/skippy/docs/PROMPT_CACHE.md +++ b/skippy/docs/PROMPT_CACHE.md @@ -23,6 +23,15 @@ For an admitted resident representation: Recurrent state can resume only at a saved checkpoint whose entire token path is a prefix of the request. A longer recurrent checkpoint cannot be truncated to an arbitrary common-prefix length. +- A recurrent prefill therefore exports up to three checkpoints, one per + distinct boundary: the message history before the assistant turn, which the + next turn of the same conversation shares; the leading system messages up to + where the first user's text begins, which every conversation with those + system messages shares, however long its first message; and the stride-grid + boundary one to two strides below the prompt's end, for prompts that share + an earlier part without a system message. A boundary shorter than the + cache's minimum prefix is neither split at nor recorded. Identical system + messages map to one cached checkpoint. This follows SGLang's radix ownership model: token paths identify shared KV blocks, while recurrent state has separate checkpoint ownership. It is an @@ -112,6 +121,28 @@ OpenAI response. Generation telemetry also reports cache status, matched prefix length, suffix-prefill tokens, and hit kind. A match identifies reusable state; it is not proof that generated tokens are correct. +A resident miss says why on its `stage.openai_kv_lookup_decision` event: +`skippy.kv.miss_reason` is `empty_cache`, `no_shared_prefix`, +`no_checkpoint_on_path` (stored prefixes share `skippy.kv.shared_prefix_tokens` +with the prompt, but no recurrent checkpoint is a whole prefix of it), +`below_min_tokens`, `not_restored` or `lookup_off`. Beside it are the prompt's +length, the cache's entry count, the length of the stored sequence that shares +the most tokens (`skippy.kv.stored_prefix_tokens`) and the longest checkpoint +on the prompt's path (`skippy.kv.checkpoint_prefix_tokens`). The lookup is also +the L1 `skippy.kv.lookup` event. + +Each recurrent checkpoint reports a `stage.openai_kv_record_decision`: +`skippy.kv.decision` is the boundary (`chat_prefix_checkpoint`, +`system_prefix_checkpoint`, `shared_prefill_checkpoint`, `final_prefill_state` +or `post_decode_checkpoint`) +followed by `_recorded`, `_already_cached`, `_skipped` or `_error`, with +`skippy.kv.checkpoint_token_count`. A skip names its `skippy.kv.skip_reason`. +At debug level, a `checkpoint_boundary` decision shows the deferred prefill's +candidate boundaries (`skippy.kv.chat_checkpoint_tokens`, +`skippy.kv.system_checkpoint_tokens`, `skippy.kv.shared_checkpoint_tokens`) and +those it exports, in prompt order +(`skippy.kv.checkpoint_kinds`). + Validate cold, repeated, changed-tail, and lane-pressure requests separately. Use uninterrupted continuations as the correctness reference for restored and forked state, and compare cache reuse and timings against vanilla llama on the diff --git a/skippy/docs/SERVING_SETTINGS.md b/skippy/docs/SERVING_SETTINGS.md index 6a139c88de..bc3d48c6b8 100644 --- a/skippy/docs/SERVING_SETTINGS.md +++ b/skippy/docs/SERVING_SETTINGS.md @@ -407,6 +407,171 @@ with their runtime purpose; existing controls follow in the same sections. | `--telemetry-level` | `telemetry_level` | See `skippy serve --help` for values and defaults. | | `--startup-timeout-secs` | `startup_timeout_secs` | See `skippy serve --help` for values and defaults. | +Two local telemetry sinks need no collector and are enabled by environment +rather than settings. `SKIPPY_TELEMETRY_STDERR=1` writes Skippy's own event +JSON to stderr. `SKIPPY_TELEMETRY_OTLP_FILE=/path/trace.otlp.jsonl` appends +OTLP/JSON trace requests, one per line, in the OpenTelemetry file-exporter +format that collectors and trace viewers ingest. Either raises an `off` level +to `debug` but never lowers an explicit level, so pass +`--telemetry-level debug` for scheduler-iteration spans under `serve`. + +A process exports one trace. The `skippy.process` root span is written at +graceful shutdown (SIGINT or SIGTERM), and everything else nests under it: + +```text +skippy.process +├── stage.embedded_runtime_load model open; native.* load calls (debug) +│ ├── native.skippy_set_native_span_callback the first traced call installs tracing +│ │ └── mtl.library_init / mtl.library_compile / mtl.pipeline_cache_open +│ └── native.skippy_model_open_with_events +│ └── skippy.backend_init / llama.model_load / llama.context_init +│ └── llama.sched_reserve / llama.graph_reserve +├── stage.openai_server_setup prewarm and cache wiring +├── stage.scheduler the scheduler worker, for its lifetime +│ ├── stage.scheduler_iteration one planned step (debug), linked to its requests +│ └── stage.scheduler_feature_iteration one direct batch (debug), linked likewise +└── stage.openai_http_request one per request; a stream ends with its body + └── stage.openai_request_summary / chat_template / tokenize / generation_admit + └── stage.openai_generation_summary + └── stage.openai_scheduler_generation | prefill | decode | decode_token + └── native.* native calls made for this request (debug) + ├── skippy.* / llama.* host phases inside the call (debug) + └── mtl.command_buffer GPU work the call submitted (debug) + └── mtl.encode / mtl.queue / mtl.execute +``` + +Each span's resource names the part of the system it belongs to as +`service.name`, within `service.namespace` `skippy`, so viewers that colour a +trace by service colour it by component: `skippy` (process lifecycle), +`skippy-http`, `skippy-scheduler`, `skippy-decode`, `skippy-kv`, +`skippy-transport`, `skippy-native` (`native.*` ABI calls), `skippy-runtime` +(the native runtime's `skippy.*` phases), `llama`, `metal-compile` and +`metal-gpu`. They remain one trace. + +Point events such as `stage.embedded_runtime_ready` become span events on the +span that was active when they fired. Batched scheduler work belongs to every +request it served, so it sits under `stage.scheduler` and carries span links to +those requests rather than one parent. A debug-level trace of a long benchmark +holds every iteration and native call; open a short run in a trace viewer, and +query the file directly for long ones. + +At debug level a native call's span is filled by the native runtime's own +spans, so its time is accounted for phase by phase. A decode step shows +`skippy.decode_prepare` or `skippy.batch_prepare`, then `llama.decode` with +`llama.batch_init`, `llama.memory_init_batch`, `llama.output_reserve` and, per +ubatch, `llama.process_ubatch` (detail `build` or `reuse`, for graph reuse) +holding `llama.memory_apply`, `llama.graph_build`, `llama.graph_alloc`, +`llama.set_inputs` and `llama.graph_compute` (encoding and submitting the +graph), then `llama.output_extract` and, for recurrent and hybrid models, +`llama.recurrent_sync`. `llama.synchronize` is the host waiting for the +device, and `skippy.sample` and `skippy.token_logprobs` follow. Phase spans +carry `skippy.native.detail` and one measured value such as +`skippy.native.tokens` or `skippy.native.nodes`. Compilation appears where it +happens: `mtl.library_compile` per kernel library and `mtl.pipeline_cache_open` +while the Metal device initialises, under the tracing install or the root +when it ran before anything was traced, and `mtl.pipeline_compile` (detail: +the pipeline) the first time a graph uses a kernel variant, under the +`llama.graph_compute` or native call that needed it. + +Other native work is named too. Model load splits into `llama.gguf_open`, +`llama.load_hparams`, `llama.load_vocab` and `llama.load_tensors` with +`llama.load_tensor_data`, and context creation into `llama.backend_init`, +`llama.memory_create`, `llama.sched_reserve` and `llama.graph_reserve`, with +`mtl.buffer_alloc`, `mtl.buffer_map` and `mtl.residency_set` beneath them. +KV and recurrent state operations appear as `llama.kv_*` and +`llama.recurrent_*` (clear, `seq_rm`, `seq_cp`, `seq_keep`, `seq_add`, state +read and write), with `llama.kv_page_export`, `llama.kv_page_import`, +`llama.state_seq_save` and `llama.state_seq_restore`. Sampling shows +`llama.sampler_apply` per sampler (detail: its name), `llama.grammar_apply` +and `llama.grammar_accept`; `llama.tokenize` shows tokenization. On Metal, +`mtl.wait` is the wait on the last command buffer, `mtl.copy_out` queues an +output copy, `mtl.upload` and `mtl.download` are blocking copies to private +buffers, and `mtl.graph_optimize` is the backend reordering a new graph. + +Between native calls, the scheduler names its own waits: `stage.scheduler_idle` +(no work queued), `stage.scheduler_coalesce` (a direct batch held open for up +to 2 ms for more sessions, with the target, the queue before and after, and +whether it timed out), `stage.scheduler_cache_defer`, `stage.scheduler_interval` +and `stage.runtime_lock_wait`. A planned step adds `stage.scheduler_plan`, +`stage.scheduler_session_setup` and `stage.scheduler_complete`; a direct batch +adds `stage.scheduler_align` and `stage.scheduler_reply`, and a cache-aware +runtime operation is the span `stage.scheduler_feature_runtime`. + +On Metal, each command buffer a native call submits becomes a +`mtl.command_buffer` span under that call, from the start of its CPU encode +to the end of its GPU execution, split into `mtl.encode`, `mtl.queue` +(committed, waiting for the GPU) and `mtl.execute`. Gaps between `mtl.execute` +spans are time the GPU sat idle. Attributes give +`skippy.gpu.encode_ms`, `skippy.gpu.queue_ms`, `skippy.gpu.execute_ms`, +`skippy.gpu.node_count`, and `skippy.gpu.context_id` with +`skippy.gpu.compute_index`. Apple GPUs time command buffers, not individual +kernels; for per-kernel timing, capture one graph for Xcode. The compute index +counts the way `GGML_METAL_CAPTURE_COMPUTE` does, so to capture the graph a +span shows, rerun the same workload with +`METAL_CAPTURE_ENABLED=1 GGML_METAL_CAPTURE_COMPUTE=` and open +`/tmp/perf-metal-.gputrace`. Every Metal context counts separately, and +the first to reach that index is the one captured. + +Debug telemetry also samples resource gauges, every 250 ms by default +(`SKIPPY_TELEMETRY_METRICS_INTERVAL_MS`), and exports them as OTLP metrics to +the same `--metrics-otlp-grpc` endpoint and, when +`SKIPPY_TELEMETRY_OTLP_METRICS_FILE` names a file, appends them there in the +same JSON-lines format as the trace file. They cover: + +| Gauge | Meaning | +|---|---| +| `process.cpu.utilization` | CPU seconds per second, by `cpu.mode` (`user`, `system`); 1 is one core | +| `process.memory.usage`, `skippy.process.memory.footprint`, `skippy.process.memory.wired` | Resident, charged (Metal buffers included on macOS) and wired memory | +| `skippy.process.pageins`, `skippy.process.disk.read` | Pages and bytes read from disk per second, such as mapped weights | +| `system.memory.usage`, `system.memory.limit` | System memory by `system.memory.state` (macOS: free, active, inactive, wired, compressed) | +| `skippy.system.swap.used`, `skippy.system.memory.pressure`, `skippy.system.paging` | Swap in use, macOS pressure (1, 2, 4) and page-in/out and swap-in/out rates | +| `skippy.gpu.busy`, `skippy.gpu.command_buffers`, `skippy.gpu.queue_wait` | GPU execution time per wall second, command buffers per second, and the mean wait before the GPU starts one | +| `skippy.gpu.memory.usage`, `skippy.gpu.memory.limit` | Memory the device has allocated, and its recommended working set, by `device` | +| `skippy.gpu.input_bytes` | Bytes GPU commands read per second, by `op_class` (`attention`, `matmul`, `recurrent`, `kv_write`, `other`): gathers from and row writes into a cache count only their rows, and attention only the K/V rows it addresses | +| `skippy.gpu.class_busy` | GPU execution time per wall second by `op_class`, only from graphs split by class (`GGML_METAL_OP_PROFILE=1`) | +| `skippy.attention.kv_cells`, `skippy.attention.queries` | The most KV cells one attention query addressed in the interval (its row list, or the whole K/V span), and the most query rows one attention node processed | +| `skippy.recurrent.states`, `skippy.recurrent.states_carried` | The most recurrent states one step gathered in the interval (the states of the batch's sequences and every state between them), and the most of those copied back unchanged; carried states are memory traffic no sequence in the batch needed | +| `skippy.runtime.busy`, `skippy.decode.tokens` | Runtime lock-held native time per wall second, and decode tokens per second | +| `skippy.scheduler.running`, `.waiting`, `.batch_size`, `skippy.kv.used_cells` | The scheduler's queue and KV occupancy as of its latest step | +| `skippy.telemetry.dropped` | Spans, native spans and GPU records lost to full queues | + +With prefix caching enabled, the KV cache tiers of +[the prompt cache](PROMPT_CACHE.md) add their pressure and misses. L1 is the +resident radix cache over the native KV pool, with recurrent checkpoints in +host RAM; L2 is the optional host-RAM mirror of L3 fills; L3 is the durable +store. Each tier's `skippy.kv..lookups` gives lookups per second by +`result` (`hit`, `miss`), and `skippy.kv..miss_ratio` the share of the +interval's lookups that missed. + +| Gauge | Meaning | +|---|---| +| `skippy.kv.l1.pool.limit`, `skippy.kv.l1.pool.utilization` | Cells in the shared native KV pool, and the share in use by requests and retained prefixes | +| `skippy.kv.l1.entries`, `.tokens`, `.pinned_tokens` | Retained prefixes, their tokens (a shared prefix once per entry), and those a restore holds | +| `skippy.kv.l1.recurrent.usage`, `.limit`, `.utilization` | Recurrent checkpoint RAM against its budget | +| `skippy.kv.l1.evictions`, `skippy.kv.l1.evicted_tokens` | Evictions per second by `component` (`attention`, `recurrent`), and the tokens they release | +| `skippy.kv.l1.hit_tokens`, `skippy.kv.l1.restored_tokens` | Prompt tokens matched by hits, and tokens restored onto requests, per second | +| `skippy.kv.l1.admission_shortfalls` | Admissions per second left below the free-space watermark after evicting all they could; each one's size is its `skippy.kv.admission_shortfall` event | +| `skippy.kv.l2.usage`, `.limit`, `.utilization`, `.entries` | L2 bytes against its budget | +| `skippy.kv.l2.inserts`, `.evictions`, `.refusals` | L2 admissions, budget evictions and verification refusals per second | +| `skippy.kv.l3.usage`, `.limit`, `.utilization`, `.reserved`, `.filesystem.available` | L3 bytes against its budget (a zero limit is unlimited), bytes reserved by writes in flight, and free space on its filesystem | +| `skippy.kv.l3.fills`, `.writes`, `.io`, `.evictions`, `.corrupt` | L3 restores, writes, bytes by `direction`, budget evictions and quarantined objects per second | +| `skippy.kv.record_queue.records`, `.bytes`, `.dropped` | Exact-state records waiting to publish to L1 and write through to L3, and those dropped because the queue was full | + +The GPU gauges come from native tracing's command buffer timings, so they +need a runtime with `SKIPPY_FEATURE_NATIVE_TRACING`. A `skippy.resources` +event with the same readings, keyed `skippy.resources.*`, marks chosen points +in the trace: `runtime_ready`, `server_start`, each request's `request_start` +and `request_response`, and `shutdown`. It includes each tier's cumulative +hits and misses and how much it holds. + +Telemetry also reports log-based events, such as cache lookups and evictions +by tier, compute-buffer reserves and pipeline compiles while serving, and +attention path changes, to the same endpoint and, when +`SKIPPY_TELEMETRY_OTLP_LOGS_FILE` names a file, to that file. Command buffer +spans say what their graph nodes did by op class, and `GGML_METAL_OP_PROFILE=1` +splits graphs so the GPU times each class alone. See +[the telemetry events reference](TELEMETRY_EVENTS.md). + ### [network] | CLI flag | TOML key | Purpose | diff --git a/skippy/docs/TELEMETRY_EVENTS.md b/skippy/docs/TELEMETRY_EVENTS.md new file mode 100644 index 0000000000..3a289e0a6e --- /dev/null +++ b/skippy/docs/TELEMETRY_EVENTS.md @@ -0,0 +1,111 @@ +# Skippy telemetry events + +Skippy reports point events as OpenTelemetry +[log-based events](https://opentelemetry.io/docs/specs/semconv/general/events/): +OTLP log records whose `event_name` identifies their structure, stamped with +the time they happened and the trace and span that were active, with no +body. An event marks a moment inside a longer operation: a lookup's +outcome, a state change, a stall. Work with a duration is a span, and facts +about a whole operation are span attributes. + +Events go to the OTLP endpoint traces use and, when +`SKIPPY_TELEMETRY_OTLP_LOGS_FILE` names a file, to that file as OTLP/JSON +lines in the collector's file-exporter format. With neither, nothing is +collected. The resource is `service.name=skippy` with the stage's lifecycle +attributes. + +## Events + +Severity numbers follow OpenTelemetry: 9 is info, 13 warn, 17 error. + +| Event | Severity | When | Attributes | +|---|---|---|---| +| `skippy.kv.lookup` | 9 | A prefix lookup at one cache tier decided whether reusable state exists: L1 when a request probes the resident radix cache, L2 and L3 when an L1 miss falls through to them | `skippy.kv.tier` (`l1`, `l2`, `l3`), `skippy.kv.result` (`hit`, `miss`), `skippy.kv.matched_tokens` on a hit | +| `skippy.kv.eviction` | 9 | The resident cache released prefixes to make room | `skippy.kv.tier`, `skippy.kv.evicted_entries`, `skippy.kv.evicted_tokens` | +| `skippy.kv.admission_shortfall` | 13 | A request was admitted below the KV pool's free-space watermark after every releasable prefix was evicted | `skippy.kv.shortfall_tokens` | +| `skippy.graph.reserved` | 13 | After the model was ready, the backend scheduler reserved compute buffers again (`llama.sched_reserve`), blocking the next graph | `skippy.native.duration_ms`, `skippy.native.detail` when the runtime names what it reserved for | +| `skippy.gpu.pipeline_compiled` | 13 | After the model was ready, a GPU kernel pipeline was compiled on first use (`mtl.pipeline_compile`) | as above; the detail names the kernel | +| `skippy.gpu.buffer_allocated` | 13 | After the model was ready, a device buffer was allocated (`mtl.buffer_alloc`) | as above | +| `skippy.attention.path` | 9 | A backend's attention was first seen, or switched path | `skippy.gpu.backend`, `skippy.attention.path` (`row_lists`: flash attention over each sequence's own rows; `flash`: flash attention over the whole masked K/V span; `unfused`: masked soft max over the whole span), `skippy.attention.kv_cells`, `skippy.attention.queries` | +| `skippy.gpu.op_profiling` | 13 | A backend first split a graph at op class boundaries (`GGML_METAL_OP_PROFILE=1`): its timings are inflated and only their shares compare | `skippy.gpu.backend` | + +The native-stall events sit on the native span that did the work; the +attention events on the call that submitted the GPU command; cache events +on the span active where the cache decided. + +The point events serving has recorded on spans (`stage.*`, `skippy.resources`) +are sent as log-based events too, under the same names and attributes, at +severity 9, except `stage.scheduler_worker_panic` and +`stage.connection_worker_panic` at 17, and `stage.binary_connection_error`, +`stage.connection_admission_rejected`, +`stage.openai_downstream_lane_return_failed` and +`stage.openai_linear_proposal_discard_failed` at 13. The span events remain, +as OpenTelemetry's migration from span events to log-based events advises. + +## GPU work by op class + +With a runtime that has `SKIPPY_FEATURE_NATIVE_TRACING`, every +`.command_buffer` span says what its graph nodes did: + +| Attribute | Meaning | +|---|---| +| `skippy.gpu.op_class` | `attention`, `matmul`, `recurrent`, `kv_write`, `other`, or `mixed` when the command holds several | +| `skippy.gpu.nodes.`, `skippy.gpu.input_bytes.` | Nodes of each class present, and the bytes they read: a gather from or row write into a cache counts only its rows, and attention only the K/V rows its nodes address | +| `skippy.gpu.layer` | The model layer of the command's first layer-named node | +| `skippy.attention.path` | `row_lists`, `flash` or `unfused`, as for the event | +| `skippy.attention.kv_cells`, `skippy.attention.queries` | The most KV cells one query addresses (for unfused attention, the K/Q product's K span), and the most query rows one attention node processes | +| `skippy.attention.row_list_nodes`, `skippy.attention.flash_nodes` | Attention nodes that read per-sequence row lists, and that are flash attention | +| `skippy.recurrent.states`, `skippy.recurrent.states_carried` | For a graph with recurrent state: the most states one gather reads (llama.cpp gathers from the batch's first state cell to its last), and the most of those copied back unchanged because no sequence in the batch owns them | +| `skippy.gpu.split_by_class` | The graph was split at class boundaries | + +Attention is flash attention, or the masked soft max and K/Q, K/Q/V +products of unfused attention. Recurrent is SSM, RWKV, gated linear +attention and delta-net state, and copies to or from its cache. Views and +reshapes do no work and have no class. + +A normal graph runs in one to three command buffers, so their GPU time +covers several classes and only the input bytes divide it. With +`GGML_METAL_OP_PROFILE=1` in the runtime's environment, Metal instead +encodes one command buffer per run of same-class nodes, in order on the +calling thread, so each command's GPU time belongs to one class and one +layer. Splitting serialises the graph and stops fusion across class +boundaries: totals grow, while each class's share of GPU time is what such a +trace measures. Compare shares between two profiled runs, not a profiled run +against an unprofiled one. A split graph's command buffers have no `encode`, +`queue` and `execute` child spans, only the `skippy.gpu.*_ms` attributes, so +that a profiled run, with hundreds of command buffers per graph, stays within +the exporter's queue. The `skippy.gpu.class_busy` and `skippy.gpu.input_bytes` +metrics sum every command, including any whose spans were dropped. + +`.idle` spans mark where the GPU waited for the host: at least +50 µs between one command's execution and the next, under the call whose +work ended the wait. `skippy.gpu.idle_kind` is `within_graph` when both +commands belong to one graph compute (the host encoded slower than the GPU +ran) and `between_graphs` otherwise (host work between steps: sampling, +scheduling, building the next graph). + +## Telling runs apart + +Every span, metric and event carries the serving configuration that decides +which kernels run and how much KV they read, as resource attributes: +`skippy.kv.cache_type_k`, `skippy.kv.cache_type_v`, `skippy.attention.flash` +(the requested mode: `auto`, `enabled` or `disabled`), `skippy.kv.ctx_size`, +`skippy.scheduler.lanes`, and when set, `skippy.batch.size`, +`skippy.batch.ubatch_size`, `skippy.kv.unified`, `skippy.kv.offload` and +`skippy.kv.swa_full`. The path attention actually took is the +`skippy.attention.path` event and span attribute. + +`OTEL_RESOURCE_ATTRIBUTES` adds the operator's own resource attributes, as +OpenTelemetry SDKs define it: comma-separated `key=value` pairs with +percent-encoded values, such as `skippy.run.label=q8-fa`. The stage's own +attributes win over a conflicting key. + +The configurations worth comparing are operator settings: K and V precision +(`--kv-cache-type-k`, `--kv-cache-type-v`: `f16`, `q8_0`, `q4_0`; quantized V +needs flash attention), flash attention (`--flash-attention`: `disabled` +selects unfused attention over the whole span), the KV pool size +(`--ctx-size`) and prefix retention (`--prefix-cache off` keeps retained +prefixes out of the pool). Whether flash attention reads per-sequence row +lists is a runtime fact, not a setting: the runtime uses them wherever the +backend supports the stored K/V type (on Metal: F16, Q4_0, Q4_1, Q5_0, Q5_1 +and Q8_0), and Skippy's KV pool is always unified. diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index a46001da9e..dae1f5f95a 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -98,6 +98,12 @@ Standard vanilla explicitly uses separate KV slots, parallel=C, context=C×131072, F16 FA, batch2048/ubatch512 and cache RAM8192MiB. Each baseline must report the expected slots/context. Unified-llama is not substituted. +`diagnostic_telemetry: true` runs Skippy at `--telemetry-level debug` and +writes each cell's spans to `skippy-telemetry.otlp.jsonl` (OTLP/JSON, one +request per line) beside the cell's other evidence. Debug telemetry perturbs +timing, so the report scope becomes `telemetry_diagnostic_not_performance` and +MLflow export refuses it. Standard llama is unchanged. + Use `backend` cuda/metal with matching prepared bundles/hosts. CPU requires `diagnostic_cpu:true`; its report is explicitly ineligible for GPU performance publication. Independent model campaigns can occupy equivalent idle machines; diff --git a/skippy/evals/agentx/tools.example.json b/skippy/evals/agentx/tools.example.json index 6efae5c4a6..36ac4336f4 100644 --- a/skippy/evals/agentx/tools.example.json +++ b/skippy/evals/agentx/tools.example.json @@ -15,5 +15,6 @@ "threads": 20, "diagnostic_generation_lanes": null, "diagnostic_cpu": false, + "diagnostic_telemetry": false, "cell_seconds": 10200 } diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index 02759682c4..22ad6fa18f 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -1,4 +1,4 @@ -From 43dc48235a7b30a1dba4d59ad3cb90928df2aa00 Mon Sep 17 00:00:00 2001 +From d96bec3062e9d6b566576d2e0a11ccc00b24abf6 Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Thu, 22 Oct 2026 17:15:05 +1100 Subject: [PATCH] skippy: add Whisper speech recognition @@ -16,19 +16,15 @@ SKIPPY_FEATURE_SPEECH_RECOGNITION clear, and report UNSUPPORTED. Bumps the Skippy ABI to 0.1.72. --- - include/skippy.h | 1 + - include/skippy/asr.h | 172 +++++++++ - include/skippy/common.h | 4 +- - src/CMakeLists.txt | 44 +++ - src/skippy/abi.cpp | 6 +- - src/skippy/asr.cpp | 447 +++++++++++++++++++++++ - src/skippy/asr_decode.h | 50 +++ - src/skippy/tests/asr_decode_boundary.cpp | 81 ++++ - 8 files changed, 803 insertions(+), 2 deletions(-) + include/skippy.h | 1 + + include/skippy/asr.h | 172 +++++++++++++++ + include/skippy/common.h | 4 +- + src/CMakeLists.txt | 37 ++++ + src/skippy/abi.cpp | 6 +- + src/skippy/asr.cpp | 465 ++++++++++++++++++++++++++++++++++++++++ + 6 files changed, 683 insertions(+), 2 deletions(-) create mode 100644 include/skippy/asr.h create mode 100644 src/skippy/asr.cpp - create mode 100644 src/skippy/asr_decode.h - create mode 100644 src/skippy/tests/asr_decode_boundary.cpp diff --git a/include/skippy.h b/include/skippy.h index ac091dd24..4e33847d9 100644 @@ -220,7 +216,7 @@ index 000000000..99d4a1094 + +#endif // SKIPPY_ASR_H diff --git a/include/skippy/common.h b/include/skippy/common.h -index 54c87b6f2..4214d0b89 100644 +index 54c87b6f2..80710eb3b 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -228,7 +224,7 @@ index 54c87b6f2..4214d0b89 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 -#define SKIPPY_ABI_VERSION_PATCH 73 -+#define SKIPPY_ABI_VERSION_PATCH 74 ++#define SKIPPY_ABI_VERSION_PATCH 75 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) @@ -242,10 +238,10 @@ index 54c87b6f2..4214d0b89 100644 enum skippy_status { SKIPPY_STATUS_OK = 0, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index f43b87266..deb634e8a 100644 +index eab1c3a46..ea0cdd178 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -101,6 +101,7 @@ add_library(llama +@@ -97,6 +97,7 @@ add_library(llama skippy/system_one.cpp skippy/laya.cpp ../tools/laya/laya.cpp @@ -253,7 +249,7 @@ index f43b87266..deb634e8a 100644 unicode.h ${LLAMA_MODELS_SOURCES} ) -@@ -127,6 +128,10 @@ set_source_files_properties(${LLAMA_CORE_SOURCES} ../include/llama.h unicode.h . +@@ -123,6 +124,10 @@ set_source_files_properties(${LLAMA_CORE_SOURCES} ../include/llama.h unicode.h . set_source_files_properties(${LLAMA_MODELS_SOURCES} PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) @@ -264,7 +260,7 @@ index f43b87266..deb634e8a 100644 configure_file(llama-version.h.in ${CMAKE_CURRENT_BINARY_DIR}/llama-version.h @ONLY) target_include_directories(llama PRIVATE . ../common ../tools/laya ${CMAKE_CURRENT_BINARY_DIR}) -@@ -173,6 +178,38 @@ if (LLAMA_LLGUIDANCE) +@@ -170,6 +175,38 @@ if (LLAMA_LLGUIDANCE) endif() @@ -303,20 +299,6 @@ index f43b87266..deb634e8a 100644 if (LLAMA_STAGE_BUILD_TESTS) target_compile_definitions(llama PRIVATE LLAMA_STAGE_BUILD_TESTS) -@@ -240,6 +277,13 @@ if (LLAMA_STAGE_BUILD_TESTS) - add_test(NAME skippy_diffusion_host_fallback COMMAND skippy-diffusion-host-fallback - "${DIFFUSION_FALLBACK_FIXTURE_DIR}/diffusion-gemma-moe.gguf") - set_tests_properties(skippy_diffusion_host_fallback PROPERTIES FIXTURES_REQUIRED diffusion-fallback-model) -+ -+ add_executable(skippy-asr-decode-boundary skippy/tests/asr_decode_boundary.cpp) -+ target_include_directories(skippy-asr-decode-boundary PRIVATE .) -+ target_include_directories(skippy-asr-decode-boundary SYSTEM PRIVATE ../vendor) -+ target_compile_features(skippy-asr-decode-boundary PRIVATE cxx_std_17) -+ target_link_libraries(skippy-asr-decode-boundary PRIVATE llama) -+ add_test(NAME skippy_asr_decode_boundary COMMAND skippy-asr-decode-boundary) - set(MTP_WIDTH_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/mtp-width-models") - file(MAKE_DIRECTORY "${MTP_WIDTH_FIXTURE_DIR}") - add_test(NAME skippy_generate_mtp_width COMMAND skippy-model-fixture-generator diff --git a/src/skippy/abi.cpp b/src/skippy/abi.cpp index f806cdbdc..ed9825df3 100644 --- a/src/skippy/abi.cpp @@ -336,10 +318,10 @@ index f806cdbdc..ed9825df3 100644 void skippy_error_free(struct skippy_error * error) { diff --git a/src/skippy/asr.cpp b/src/skippy/asr.cpp new file mode 100644 -index 000000000..a0c619289 +index 000000000..680549066 --- /dev/null +++ b/src/skippy/asr.cpp -@@ -0,0 +1,447 @@ +@@ -0,0 +1,465 @@ +#include "skippy/asr.h" +#include "skippy/errors.h" + @@ -376,7 +358,7 @@ index 000000000..a0c619289 +#define MA_NO_ENGINE +#define MA_NO_GENERATION +#define MA_API static -+#include "asr_decode.h" ++#include "miniaudio/miniaudio.h" +#endif + +struct skippy_asr_model { @@ -488,7 +470,7 @@ index 000000000..a0c619289 + return stat(path, &info) == 0 ? static_cast(info.st_size) : 0; +} + -+using skippy_asr_detail::decode_outcome; ++enum class decode_outcome { ok, failed, too_long }; + +decode_outcome decode_audio(const uint8_t * data, size_t len, std::vector & samples) { + ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 1, SKIPPY_ASR_SAMPLE_RATE); @@ -500,8 +482,26 @@ index 000000000..a0c619289 + return decode_outcome::failed; + } + // Read in chunks: VBR MP3 cannot always report its length up front. -+ const decode_outcome outcome = skippy_asr_detail::read_bounded_audio( -+ decoder, samples, static_cast(SKIPPY_ASR_MAX_SAMPLES), SKIPPY_ASR_SAMPLE_RATE); ++ constexpr ma_uint64 chunk = SKIPPY_ASR_SAMPLE_RATE; ++ decode_outcome outcome = decode_outcome::ok; ++ for (;;) { ++ if (samples.size() >= static_cast(SKIPPY_ASR_MAX_SAMPLES)) { ++ outcome = decode_outcome::too_long; ++ break; ++ } ++ const size_t offset = samples.size(); ++ samples.resize(offset + chunk); ++ ma_uint64 read = 0; ++ const ma_result result = ma_decoder_read_pcm_frames(&decoder, samples.data() + offset, chunk, &read); ++ samples.resize(offset + read); ++ if (result == MA_AT_END || (result == MA_SUCCESS && read < chunk)) { ++ break; ++ } ++ if (result != MA_SUCCESS) { ++ outcome = decode_outcome::failed; ++ break; ++ } ++ } + ma_decoder_uninit(&decoder); + return outcome; +} @@ -787,149 +787,6 @@ index 000000000..a0c619289 +extern "C" void skippy_asr_result_free(struct skippy_asr_result * result) { + delete result; +} -diff --git a/src/skippy/asr_decode.h b/src/skippy/asr_decode.h -new file mode 100644 -index 000000000..c56a5ea9c ---- /dev/null -+++ b/src/skippy/asr_decode.h -@@ -0,0 +1,50 @@ -+#pragma once -+ -+#if defined(_WIN32) && !defined(NOMINMAX) -+#define NOMINMAX -+#endif -+#include "miniaudio/miniaudio.h" -+ -+#include -+#include -+ -+namespace skippy_asr_detail { -+ -+enum class decode_outcome { ok, failed, too_long }; -+ -+// The production limit and read chunk are supplied by the ASR contract. Keeping the -+// decoder loop independent of Whisper also permits small, real audio boundary tests. -+inline decode_outcome read_bounded_audio(ma_decoder & decoder, std::vector & samples, -+ size_t limit, ma_uint64 chunk) { -+ if (samples.size() > limit) { -+ return decode_outcome::too_long; -+ } -+ if (chunk == 0) { -+ return decode_outcome::failed; -+ } -+ while (samples.size() < limit) { -+ const size_t offset = samples.size(); -+ const ma_uint64 request = (std::min)(chunk, limit - offset); -+ samples.resize(offset + static_cast(request)); -+ ma_uint64 read = 0; -+ const ma_result result = ma_decoder_read_pcm_frames(&decoder, samples.data() + offset, request, &read); -+ samples.resize(offset + static_cast(read)); -+ if (result == MA_AT_END || (result == MA_SUCCESS && read < request)) { -+ return decode_outcome::ok; -+ } -+ if (result != MA_SUCCESS) { -+ return decode_outcome::failed; -+ } -+ } -+ // A successful full read does not establish EOF. Probe one frame without growing -+ // the sample buffer: the inclusive maximum is valid only if no further frame exists. -+ float extra = 0.0f; -+ ma_uint64 read = 0; -+ const ma_result result = ma_decoder_read_pcm_frames(&decoder, &extra, 1, &read); -+ if (read != 0) { -+ return decode_outcome::too_long; -+ } -+ return result == MA_AT_END || result == MA_SUCCESS ? decode_outcome::ok : decode_outcome::failed; -+} -+ -+} // namespace skippy_asr_detail -diff --git a/src/skippy/tests/asr_decode_boundary.cpp b/src/skippy/tests/asr_decode_boundary.cpp -new file mode 100644 -index 000000000..a5b1ff113 ---- /dev/null -+++ b/src/skippy/tests/asr_decode_boundary.cpp -@@ -0,0 +1,81 @@ -+// Use the same file-local decoder implementation as ASR, without a Whisper model. -+#define ma_atomic_global_lock skippy_asr_test_ma_atomic_global_lock -+#define MINIAUDIO_IMPLEMENTATION -+#define MA_NO_ENCODING -+#define MA_NO_DEVICE_IO -+#define MA_NO_RESOURCE_MANAGER -+#define MA_NO_NODE_GRAPH -+#define MA_NO_ENGINE -+#define MA_NO_GENERATION -+#define MA_API static -+#include "../asr_decode.h" -+ -+#include -+#include -+#include -+#include -+ -+namespace { -+void le16(std::vector & wav, size_t offset, uint16_t value) { -+ wav[offset] = uint8_t(value); -+ wav[offset + 1] = uint8_t(value >> 8); -+} -+ -+void le32(std::vector & wav, size_t offset, uint32_t value) { -+ le16(wav, offset, uint16_t(value)); -+ le16(wav, offset + 2, uint16_t(value >> 16)); -+} -+ -+bool check(size_t frames, size_t limit) { -+ // A real mono PCM WAV, just a few frames long. Samples remain recognizable -+ // after decoding so boundary checks also detect skipped/duplicated frames. -+ std::vector wav(44 + frames * 2, 0); -+ std::memcpy(wav.data(), "RIFF", 4); -+ le32(wav, 4, uint32_t(wav.size() - 8)); -+ std::memcpy(wav.data() + 8, "WAVEfmt ", 8); -+ le32(wav, 16, 16); -+ le16(wav, 20, 1); -+ le16(wav, 22, 1); -+ le32(wav, 24, 16000); -+ le32(wav, 28, 32000); -+ le16(wav, 32, 2); -+ le16(wav, 34, 16); -+ std::memcpy(wav.data() + 36, "data", 4); -+ le32(wav, 40, uint32_t(frames * 2)); -+ for (size_t i = 0; i < frames; ++i) { -+ le16(wav, 44 + i * 2, uint16_t((i + 1) * 1024)); -+ } -+ auto config = ma_decoder_config_init(ma_format_f32, 1, 16000); -+ ma_decoder decoder; -+ if (ma_decoder_init_memory(wav.data(), wav.size(), &config, &decoder) != MA_SUCCESS) { -+ return false; -+ } -+ std::vector samples; -+ const auto outcome = skippy_asr_detail::read_bounded_audio(decoder, samples, limit, 4); -+ ma_decoder_uninit(&decoder); -+ const auto expected = frames > limit ? skippy_asr_detail::decode_outcome::too_long : -+ skippy_asr_detail::decode_outcome::ok; -+ bool valid = outcome == expected && samples.size() == (std::min)(frames, limit); -+ for (size_t i = 0; i < samples.size(); ++i) { -+ valid &= std::fabs(samples[i] - float(i + 1) / 32.0f) < 1e-6f; -+ } -+ if (!valid) { -+ std::fprintf(stderr, "audio frames=%zu limit=%zu: outcome=%d retained=%zu\n", -+ frames, limit, int(outcome), samples.size()); -+ } -+ return valid; -+} -+} // namespace -+ -+int main() { -+ // Exercise a chunk-aligned limit (requires an EOF probe) and an unaligned -+ // limit (requires capping the last read). No large allocation or model needed. -+ for (size_t limit : { size_t(8), size_t(7) }) { -+ for (size_t frames : { limit - 1, limit, limit + 1 }) { -+ if (!check(frames, limit)) { -+ return 1; -+ } -+ } -+ } -+ return 0; -+} -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 92ed594e49..5bb7366cf2 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -1,4 +1,4 @@ -From 5dbf1902a59cc99e2e2f37fff9c1c5ee3a4098ca Mon Sep 17 00:00:00 2001 +From 76c1598c4144f104a0b8946f6533619fd9ad6b33 Mon Sep 17 00:00:00 2001 From: Virgile-pct Date: Wed, 21 Oct 2026 23:42:33 +0200 Subject: [PATCH] skippy: record per-token logprobs while sampling @@ -20,11 +20,11 @@ to touch common.h it carries the queue's ABI version, 0.1.77. include/skippy/sampling.h | 4 ++ src/CMakeLists.txt | 1 + src/skippy/logprobs.cpp | 94 ++++++++++++++++++++++++++++++++++ - src/skippy/resident_prefix.cpp | 1 + src/skippy/runtime_types.h | 2 + src/skippy/sampling.cpp | 21 +++++++- src/skippy/sampling_internal.h | 7 +++ src/skippy/session.cpp | 1 + + src/skippy/state.cpp | 1 + src/skippy/workloads.cpp | 1 + 12 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 include/skippy/logprobs.h @@ -43,15 +43,15 @@ index 4e33847d9..9497734b7 100644 #include "skippy/system_one.h" #include "skippy/laya.h" diff --git a/include/skippy/common.h b/include/skippy/common.h -index 4214d0b89..dae7be31c 100644 +index 80710eb3b..93232a2b8 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 74 -+#define SKIPPY_ABI_VERSION_PATCH 77 +-#define SKIPPY_ABI_VERSION_PATCH 75 ++#define SKIPPY_ABI_VERSION_PATCH 78 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) @@ -144,10 +144,10 @@ index 1b42f32c0..c1a755c4c 100644 #ifdef __cplusplus diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index deb634e8a..a75262731 100644 +index ea0cdd178..beded64e4 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -87,6 +87,7 @@ add_library(llama +@@ -84,6 +84,7 @@ add_library(llama skippy/sampling_config.cpp skippy/chat_sampling.cpp skippy/sampling_vocab.cpp @@ -255,24 +255,12 @@ index 000000000..43260dfc2 + *out_count = taken; + return skippy_success(out_error); +} -diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp -index 42769ba7c..577b4be2e 100644 ---- a/src/skippy/resident_prefix.cpp -+++ b/src/skippy/resident_prefix.cpp -@@ -183,6 +183,7 @@ skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, - session->n_past = static_cast(count); - session->token_history = std::move(history); - session->signal_history.clear(); -+ session->token_logprobs.clear(); - skippy_mtp_clear_session_state(session); - session->verify_checkpoints.clear(); - return skippy_success(error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index b8e4251aa..255334489 100644 +index ec9fb94b1..cd8a82f7a 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -153,6 +153,8 @@ struct skippy_session { - int32_t borrowed_prefix_tokens = 0; +@@ -146,6 +146,8 @@ struct skippy_session { + int32_t preserve_prefix_tokens = 0; std::vector token_history; std::vector signal_history; + // Recorded by sampling with SKIPPY_SAMPLING_FLAG_LOGPROBS until the caller takes them. @@ -351,10 +339,10 @@ index 7bbf16016..81bc26ff5 100644 skippy_session * session, const llama_token * token_ids, diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 1e6cf90e1..bc86d41d7 100644 +index a9251d2c9..13e318534 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp -@@ -376,6 +376,7 @@ enum skippy_status skippy_session_reset( +@@ -379,6 +379,7 @@ enum skippy_status skippy_session_reset( session->token_history.clear(); } session->signal_history.clear(); @@ -362,6 +350,18 @@ index 1e6cf90e1..bc86d41d7 100644 // Keep a reusable backend sampler attached across reset. Detaching it // makes the next sampled decode reattach the chain and mark the scheduler // for reserve, which rebuilds compute buffers at every request boundary. +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +index 45a53c4ba..1f2e58a37 100644 +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -1037,6 +1037,7 @@ enum skippy_status skippy_session_restore_prefix( + session->token_history.assign(token_ids, token_ids + token_count); + } + session->signal_history.clear(); ++ session->token_logprobs.clear(); + skippy_mtp_clear_session_state(session); + skippy_clear_verify_windows(session); + return skippy_success(out_error); diff --git a/src/skippy/workloads.cpp b/src/skippy/workloads.cpp index d3de66cbe..3ca967bf3 100644 --- a/src/skippy/workloads.cpp @@ -375,5 +375,5 @@ index d3de66cbe..3ca967bf3 100644 namespace { -- -2.56.0 +2.54.0 (Apple Git-157) diff --git a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch index 5f4ebfb536..37683bfb94 100644 --- a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch @@ -188,7 +188,7 @@ index 93232a2b8..d2ab5d538 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 -#define SKIPPY_ABI_VERSION_PATCH 78 -+#define SKIPPY_ABI_VERSION_PATCH 79 ++#define SKIPPY_ABI_VERSION_PATCH 81 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index bcf0f8404d..53bf94caf5 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -536,6 +536,7 @@ if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then skippy-model-loader-accounting skippy-runtime-events-test skippy-sampling-history + skippy-concurrent-sampling skippy-selected-logits skippy-noalloc-graph-planning skippy-renamed-multishard-planning diff --git a/tools/xtask/src/automation/agentx/final_sweep.rs b/tools/xtask/src/automation/agentx/final_sweep.rs index 8b6df3ad96..270da4cbcf 100644 --- a/tools/xtask/src/automation/agentx/final_sweep.rs +++ b/tools/xtask/src/automation/agentx/final_sweep.rs @@ -107,7 +107,7 @@ fn run(request: Request, output: &Path) -> DynResult<()> { let status = if result.is_ok() { "passed" } else { "failed" }; let mut report = json!({"schema_version":1,"campaign":request.campaign,"model_key":request.model_key,"request":request, "backend":request.tools.backend,"status":status,"arms":arms,"error":result.as_ref().err().map(ToString::to_string), - "repeat_order":ORDER,"concurrencies":[1,2,4],"scope":report_scope(request.tools.backend, request.tools.diagnostic_generation_lanes), + "repeat_order":ORDER,"concurrencies":[1,2,4],"scope":request.tools.campaign_scope(), "jy_job_id":std::env::var("JIANYANG_JOB_ID").ok(),"jy_run_id":std::env::var("JIANYANG_RUN_ID").ok(), "source_attribution":{"product":request.tools.product_source_commit,"native":request.tools.native_source_commit, "standard_upstream":request.tools.standard_upstream,"automation_binary_sha256":crate::product::digest::file_sha256(&std::env::current_exe()?).map_err(|e|e.error)?}, diff --git a/tools/xtask/src/automation/agentx/final_sweep_tests.rs b/tools/xtask/src/automation/agentx/final_sweep_tests.rs index bb0e9c29d7..dcd99c6b84 100644 --- a/tools/xtask/src/automation/agentx/final_sweep_tests.rs +++ b/tools/xtask/src/automation/agentx/final_sweep_tests.rs @@ -1,7 +1,7 @@ use super::{ final_sweep::{self, COHORT_SHA, ORDER}, prepared_launch, - prepared_tools::{Tools, Tree}, + prepared_tools::{Backend, Tools, Tree}, }; use serde_json::{Value, json}; @@ -40,6 +40,39 @@ fn tools() -> Tools { .unwrap() } #[test] +fn telemetry_diagnostics_are_scoped_out_of_publication() { + let mut tools = tools(); + assert_eq!(tools.campaign_scope(), "fixed_complete_AgentX_comparison"); + tools.diagnostic_telemetry = true; + assert_eq!( + tools.campaign_scope(), + "telemetry_diagnostic_not_performance" + ); + tools.backend = Backend::Cpu; + assert_eq!(tools.campaign_scope(), "cpu_diagnostic_not_gpu_performance"); + tools.backend = Backend::Metal; + tools.diagnostic_telemetry = false; + tools.diagnostic_generation_lanes = Some(1); + assert_eq!( + tools.campaign_scope(), + "diagnostic_generation_lanes_AgentX_comparison" + ); + + let mut earlier: Value = serde_json::from_str(include_str!( + "../../../../../skippy/evals/agentx/tools.example.json" + )) + .unwrap(); + earlier + .as_object_mut() + .unwrap() + .remove("diagnostic_telemetry"); + let earlier: Tools = serde_json::from_value(earlier).unwrap(); + assert!( + !earlier.diagnostic_telemetry, + "earlier pins stay qualifying" + ); +} +#[test] fn product_auto_capacity_is_preserved_and_diagnostic_override_is_verified() { let mut tools = tools(); let mut args = vec!["serve".into(), "--n-gpu-layers".into(), "99".into()]; diff --git a/tools/xtask/src/automation/agentx/lifecycle.rs b/tools/xtask/src/automation/agentx/lifecycle.rs index 1c6755abfa..ce9d2751ba 100644 --- a/tools/xtask/src/automation/agentx/lifecycle.rs +++ b/tools/xtask/src/automation/agentx/lifecycle.rs @@ -19,6 +19,7 @@ const SKIPPY_KV_UNIFIED_ENV: &str = "AGENTX_SKIPPY_KV_UNIFIED"; const SKIPPY_MICROBATCH_TOKENS_ENV: &str = "AGENTX_SKIPPY_MICROBATCH_TOKENS"; const SKIPPY_GENERATION_CONCURRENCY_ENV: &str = "AGENTX_SKIPPY_GENERATION_CONCURRENCY"; const BASELINE_MICROBATCH_TOKENS: usize = 512; +const TELEMETRY_FILE: &str = "skippy-telemetry.otlp.jsonl"; const BATCH_TOKENS: usize = 2_048; fn llama_comparison_context(concurrency: u32) -> DynResult { @@ -334,6 +335,13 @@ fn server( .into_os_string(), ), ]); + if input + .tools + .as_ref() + .is_some_and(|tools| tools.diagnostic_telemetry) + { + enable_diagnostic_telemetry(&mut spec, &input.output); + } if input.tools.is_none() && (input.profile == Profile::Contention || std::env::var("AGENTX_SKIPPY_DEBUG_TELEMETRY").as_deref() == Ok("1")) @@ -377,6 +385,18 @@ fn server( Ok(spec) } +/// Debug telemetry as OTLP JSON beside the cell's other retained evidence. +fn enable_diagnostic_telemetry(spec: &mut process::ProcessSpec, cell: &std::path::Path) { + spec.arguments.extend([ + process::Value::Public("--telemetry-level".into()), + process::Value::Public("debug".into()), + ]); + spec.environment.insert( + "SKIPPY_TELEMETRY_OTLP_FILE".into(), + process::Value::Public(cell.join(TELEMETRY_FILE).into_os_string()), + ); +} + fn enable_exact_state_diagnostics(spec: &mut process::ProcessSpec) { spec.environment.insert( "SKIPPY_EXACT_STATE_DIAGNOSTICS".into(), @@ -785,6 +805,20 @@ mod tests { )); } + #[test] + fn diagnostic_telemetry_writes_debug_otlp_into_the_cell() { + let mut spec = command::spec(&std::env::temp_dir(), "sh", &[]).unwrap(); + enable_diagnostic_telemetry(&mut spec, std::path::Path::new("/runs/skippy-c4")); + assert!(spec.arguments.windows(2).any(|pair| matches!(pair, + [process::Value::Public(flag), process::Value::Public(level)] + if flag == "--telemetry-level" && level == "debug"))); + assert!(matches!( + spec.environment.get(std::ffi::OsStr::new("SKIPPY_TELEMETRY_OTLP_FILE")), + Some(process::Value::Public(path)) + if path == "/runs/skippy-c4/skippy-telemetry.otlp.jsonl" + )); + } + #[test] fn kv_span_diagnostic_enables_native_cell_span_logging() { let mut spec = command::spec(&std::env::temp_dir(), "sh", &[]).unwrap(); diff --git a/tools/xtask/src/automation/agentx/prepared_tools.rs b/tools/xtask/src/automation/agentx/prepared_tools.rs index 894ebc0bb8..a412b1d3bd 100644 --- a/tools/xtask/src/automation/agentx/prepared_tools.rs +++ b/tools/xtask/src/automation/agentx/prepared_tools.rs @@ -203,9 +203,26 @@ pub(super) struct Tools { /// None preserves the product's automatic lane plan independently of offered C. pub diagnostic_generation_lanes: Option, pub diagnostic_cpu: bool, + /// Debug Skippy telemetry to a per-cell OTLP JSON file. It perturbs + /// timing, so the campaign is scoped as a diagnostic and never published. + #[serde(default)] + pub diagnostic_telemetry: bool, pub cell_seconds: u64, } impl Tools { + /// Only an undiagnosed GPU campaign is a publishable comparison. + pub(super) fn campaign_scope(&self) -> &'static str { + if self.backend == Backend::Cpu { + "cpu_diagnostic_not_gpu_performance" + } else if self.diagnostic_telemetry { + "telemetry_diagnostic_not_performance" + } else if self.diagnostic_generation_lanes.is_some() { + "diagnostic_generation_lanes_AgentX_comparison" + } else { + "fixed_complete_AgentX_comparison" + } + } + fn verify_client_environment(&self) -> DynResult<()> { absolute(&self.client_environment.path)?; verify_python_venv_config(&self.client_environment.path.join("pyvenv.cfg")).map_err( diff --git a/tools/xtask/src/automation/agentx/standard_runtime.rs b/tools/xtask/src/automation/agentx/standard_runtime.rs index 827eb4993f..aa8bfc9bcc 100644 --- a/tools/xtask/src/automation/agentx/standard_runtime.rs +++ b/tools/xtask/src/automation/agentx/standard_runtime.rs @@ -5,6 +5,10 @@ use std::{ path::{Path, PathBuf}, }; +// CUDA vendor libraries can exceed 512 MiB; keep native-image inspection bounded +// independently of the much smaller automation inputs and receipts. +const MAX_NATIVE_IMAGE_BYTES: u64 = 1024 * 1024 * 1024; + struct Imports { libraries: Vec, search: Vec, @@ -96,7 +100,10 @@ fn is_library(path: &Path) -> bool { } fn inspect(path: &Path) -> DynResult { - let bytes = crate::automation::receipt_files::bounded(path, 512 * 1024 * 1024)?; + if std::fs::symlink_metadata(path)?.len() > MAX_NATIVE_IMAGE_BYTES { + return Err("standard runtime native image exceeds inspection bound".into()); + } + let bytes = crate::automation::receipt_files::bounded(path, MAX_NATIVE_IMAGE_BYTES)?; match goblin::Object::parse(&bytes)? { goblin::Object::Elf(image) => Ok(Imports { libraries: image @@ -272,6 +279,30 @@ mod tests { std::fs::write(path, bytes).unwrap(); } + #[test] + fn large_native_image_preserves_imports_and_rejects_oversized_files() { + let dir = tempfile::tempdir().unwrap(); + let library = dir.path().join("liblarge.so"); + elf(&library, Some("libggml.so"), Some("$ORIGIN")); + let file = std::fs::OpenOptions::new() + .write(true) + .open(&library) + .unwrap(); + file.set_len(512 * 1024 * 1024 + 4096).unwrap(); + + let imports = inspect(&library).unwrap(); + assert_eq!(imports.libraries, ["libggml.so"]); + assert_eq!(imports.search, ["$ORIGIN"]); + assert!(!imports.macho); + + file.set_len(MAX_NATIVE_IMAGE_BYTES + 1).unwrap(); + let error = inspect(&library).err().unwrap(); + assert_eq!( + error.to_string(), + "standard runtime native image exceeds inspection bound" + ); + } + #[test] fn inspected_elf_closure_requires_its_actual_needed_library_inside_the_pin() { let dir = tempfile::tempdir().unwrap(); diff --git a/tools/xtask/src/no_console_print/scope.rs b/tools/xtask/src/no_console_print/scope.rs index b1ec1af1c4..cb9c906c1e 100644 --- a/tools/xtask/src/no_console_print/scope.rs +++ b/tools/xtask/src/no_console_print/scope.rs @@ -47,7 +47,7 @@ pub(super) const CONSOLE_OUTPUT_OWNERS: &[&str] = &[ "mesh/crates/mesh-llm-tui/src/output/formatting.rs", "mesh/crates/mesh-llm-tui/src/output/terminal_out.rs", "mesh/crates/mesh-llm-host-runtime/src/runtime/tracing_writer.rs", - "skippy/crates/skippy-serving/src/telemetry.rs", + "skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs", "skippy/crates/skippy-commands/src/console.rs", "mesh/crates/mesh-llm-cli/src/pager.rs", "mesh/crates/mesh-llm-commands/src/gpus/tune_runner.rs", diff --git a/tools/xtask/tests/fixtures/ci_operations/runner_identity/check.json b/tools/xtask/tests/fixtures/ci_operations/runner_identity/check.json index 3539174dda..4295153a0a 100644 --- a/tools/xtask/tests/fixtures/ci_operations/runner_identity/check.json +++ b/tools/xtask/tests/fixtures/ci_operations/runner_identity/check.json @@ -1,5 +1,5 @@ { "code": 0, "stderr": "", - "stdout": "{\n \"images\": 11,\n \"roles\": 38,\n \"runtime_rows\": 4,\n \"seed_consumers\": 6,\n \"workflow_bindings\": 38\n}\n" + "stdout": "{\n \"images\": 11,\n \"roles\": 37,\n \"runtime_rows\": 4,\n \"seed_consumers\": 6,\n \"workflow_bindings\": 37\n}\n" } diff --git a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs index 0b3e92563d..2633a41d00 100644 --- a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs +++ b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs @@ -49,7 +49,7 @@ const VALID_SOURCES: [(&str, &[u8], &[u8]); 2] = [ ( "abi", include_bytes!("../../../../skippy/crates/skippy-ffi/src/lib.rs"), - b"0.1.79\n", + b"0.1.80\n", ), ]; diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index c64e31cace..cdb6f8b4b6 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -232,6 +232,8 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( "skippy-model-fixture-generator", "skippy-model-loader-accounting", "skippy-runtime-events-test", + "skippy-sampling-history", + "skippy-concurrent-sampling", "skippy-noalloc-graph-planning", "skippy-renamed-multishard-planning", "skippy-stage-slice-plan", From 63602d8911ae13dfc041680a15ddcda18dc607f1 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 32/81] perf(skippy): rebase the Metal decode work onto the new llama pin --- Cargo.lock | 22 + ci/model-artifacts/README.md | 29 + .../manifests/competitive-benchmark.json | 2 +- .../manifests/hf-download-smoke.json | 2 +- .../manifests/openai-smoke.json | 2 +- .../manifests/performance-coverage.json | 409 +++ .../manifests/product-smoke.json | 2 +- ci/model-artifacts/manifests/radix-cache.json | 2 +- .../manifests/safetensors-runtime-smoke.json | 2 +- .../manifests/scripted-binary-smoke.json | 2 +- ci/model-artifacts/manifests/sdk-smoke.json | 2 +- .../manifests/skippy-ci-smoke.json | 2 +- .../manifests/skippy-correctness.json | 2 +- .../manifests/skippy-cpp-api.json | 2 +- .../manifests/skippy-parity.json | 2 +- .../manifests/skippy-system-one-smoke.json | 2 +- ci/model-artifacts/registry.json | 337 +- .../src/inference/skippy/deployment.rs | 5 + .../src/runtime/local_model_only.rs | 2 + .../src/config/translation.rs | 4 + mesh/website/src/docs/pages/skippy-api.md | 17 +- skippy/crates/llama-spec-bench/src/main.rs | 4 + skippy/crates/skippy-api/src/family_policy.rs | 2 + .../skippy-api/src/split-certified.json | 4 +- skippy/crates/skippy-api/src/stage.rs | 5 + skippy/crates/skippy-api/src/stage_load.rs | 5 + skippy/crates/skippy-cache/src/identity.rs | 12 + skippy/crates/skippy-cli/Cargo.toml | 2 + .../skippy-cli/src/serve_settings/catalog.rs | 49 + .../src/serve_settings/resolution.rs | 15 + .../src/runner/kv_page_growth.rs | 4 + .../src/runner/remote_handoff.rs | 4 + .../src/runner/single_step.rs | 8 + .../src/runner/split_chain.rs | 4 + .../src/runner/stage_execution.rs | 4 + .../src/runner/stage_fa_parity.rs | 4 + .../src/runner/state_handoff.rs | 8 + .../tests/parity_models/mod.rs | 4 + skippy/crates/skippy-ffi/README.md | 2 +- .../crates/skippy-ffi/src/bindings/skippy.rs | 14 +- skippy/crates/skippy-ffi/src/dynamic.rs | 1 + skippy/crates/skippy-ffi/src/lib.rs | 8 +- skippy/crates/skippy-protocol/src/config.rs | 67 + skippy/crates/skippy-protocol/src/lib.rs | 3 +- .../crates/skippy-quantize/src/mtp_attach.rs | 4 + skippy/crates/skippy-runtime/src/config.rs | 48 + skippy/crates/skippy-runtime/src/native.rs | 7 + skippy/crates/skippy-runtime/src/tests.rs | 4 + skippy/crates/skippy-serving/Cargo.toml | 3 + skippy/crates/skippy-serving/build.rs | 65 + .../src/binary_transport/stage_execution.rs | 2 + .../src/frontend/backend/tests.rs | 2 + .../src/frontend/generation/draft_runner.rs | 4 + .../frontend/generation/http_request_span.rs | 3 +- .../src/frontend/generation/server.rs | 3 + .../src/frontend/generation/streaming.rs | 9 +- .../src/frontend/generation/types.rs | 23 + .../src/frontend/generation_flow.rs | 4 +- .../generation_flow/text_generation.rs | 4 +- .../src/frontend/iteration_scheduler.rs | 13 +- .../iteration_scheduler/cache_wave.rs | 1 + .../iteration_scheduler/command_waits.rs | 60 +- .../iteration_scheduler/direct_batch.rs | 70 +- .../direct_batch/coalescing_tests.rs | 1 + .../iteration_scheduler/direct_execution.rs | 3 +- .../iteration_scheduler/step_telemetry.rs | 1 + .../src/frontend/iteration_scheduler/tests.rs | 12 + .../local_generation/linear_decode.rs | 3 +- .../src/frontend/local_generation/tests.rs | 9 +- .../tests/cooperative_prefill.rs | 2 - .../local_generation/tests/durable_prefix.rs | 1 - .../tests/recurrent_fixture.rs | 3 + .../src/frontend/prefix_cache.rs | 4 + .../skippy-serving/src/frontend/prompting.rs | 17 +- .../src/frontend/tests/multimodal.rs | 2 + .../src/frontend/tests/support.rs | 4 + .../src/kv_integration/activation.rs | 2 + .../src/kv_integration/cache_affinity.rs | 4 + .../src/kv_integration/config.rs | 14 + .../kv_integration/config/resident_policy.rs | 2 + .../exact_state/resident_preference/tests.rs | 2 + .../src/kv_integration/identity.rs | 2 + .../skippy-serving/src/kv_integration/mod.rs | 4 + .../src/kv_integration/resident_prefix.rs | 103 +- .../src/kv_integration/scheduling.rs | 153 +- .../src/kv_integration/snapshot_validation.rs | 2 + .../skippy-serving/src/runtime_state.rs | 9 +- .../src/runtime_state/context_capacity.rs | 58 +- skippy/crates/skippy-serving/src/telemetry.rs | 628 ++-- .../src/telemetry/active_span.rs | 72 +- .../src/telemetry/otlp_collector.rs | 293 ++ .../src/telemetry/otlp_encoding.rs | 4 +- .../skippy-serving/src/telemetry/otlp_file.rs | 75 +- .../src/telemetry/resource_attrs.rs | 172 +- .../src/telemetry/resource_metrics.rs | 112 +- .../resource_metrics/otlp_metrics.rs | 52 +- .../skippy-serving/src/telemetry/sink.rs | 285 ++ .../src/telemetry/stderr_sink.rs | 82 +- .../src/telemetry/tracy_sink.rs | 518 +++ skippy/docs/PROMPT_CACHE.md | 21 + skippy/docs/SERVING_SETTINGS.md | 7 + skippy/docs/TELEMETRY_EVENTS.md | 20 +- ...esident-prefixes-as-shared-cells-plu.patch | 2226 ++++++++++++ ...ls-without-rollback-snapshots-unless.patch | 761 +++++ ...tive-trace-spans-and-GPU-command-tim.patch | 3038 +++++++++++++++++ ...mple-a-batch-s-requests-concurrently.patch | 621 ++++ .../0021-skippy-trace-K-V-row-list-runs.patch | 149 + ...consecutive-row-list-blocks-like-den.patch | 112 + ...uence-s-unified-pool-cells-in-chunks.patch | 193 ++ ...le-a-gather-free-row-list-attention-.patch | 162 + ...GML_METAL_CAPTURE_DIR-choose-where-a.patch | 35 + ...ost-of-ordinary-vs-row-list-decode-a.patch | 336 ++ ...-start-every-row-list-run-on-an-atte.patch | 433 +++ ...METAL_ROWS_DEBUG-counts-the-row-atte.patch | 77 + ...rt-every-backend-buffer-s-life-as-a-.patch | 230 ++ ...ol-cells-as-the-high-water-mark-adva.patch | 252 ++ ...ages-of-freed-KV-chunks-back-to-the-.patch | 312 ++ ...unified-KV-pool-and-choose-its-memor.patch | 329 ++ ...01-models-add-inkling-family-support.patch | 18 +- ...-add-diffusiongemma-system-one-reads.patch | 4 +- ...dels-add-laya-decision-model-support.patch | 4 +- ...kippy-add-whisper-speech-recognition.patch | 4 +- ...rd-per-token-logprobs-while-sampling.patch | 36 +- ...pose-glm5-next-stage-graph-semantics.patch | 6 +- ...skippy-add-clef-joint-decision-reads.patch | 4 +- skippy/scripts/build-llama.sh | 6 +- tools/xtask/src/cli.rs | 2 +- tools/xtask/src/model_registry/derived.rs | 335 ++ tools/xtask/src/model_registry/fetch.rs | 377 ++ tools/xtask/src/model_registry/generate.rs | 25 +- tools/xtask/src/model_registry/manifest.rs | 18 + tools/xtask/src/model_registry/mod.rs | 19 +- tools/xtask/src/model_registry/pin.rs | 711 ++++ tools/xtask/src/model_registry/projection.rs | 29 +- .../src/model_registry/projector_download.rs | 13 + .../projector_download/transfer.rs | 99 +- tools/xtask/src/model_registry/registry.rs | 38 +- .../xtask/tests/migration_models/generator.rs | 76 +- tools/xtask/tests/migration_models/live.rs | 65 +- tools/xtask/tests/migration_models/support.rs | 17 + .../encoding_approval.rs | 2 +- .../full_replay.rs | 12 +- 142 files changed, 14627 insertions(+), 730 deletions(-) create mode 100644 ci/model-artifacts/manifests/performance-coverage.json create mode 100644 skippy/crates/skippy-serving/build.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/otlp_collector.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/sink.rs create mode 100644 skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs create mode 100644 skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch create mode 100644 skippy/llama_cpp/patches/0018-skippy-open-models-without-rollback-snapshots-unless.patch create mode 100644 skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch create mode 100644 skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch create mode 100644 skippy/llama_cpp/patches/0021-skippy-trace-K-V-row-list-runs.patch create mode 100644 skippy/llama_cpp/patches/0022-ggml-metal-read-consecutive-row-list-blocks-like-den.patch create mode 100644 skippy/llama_cpp/patches/0023-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch create mode 100644 skippy/llama_cpp/patches/0024-ggml-metal-compile-a-gather-free-row-list-attention-.patch create mode 100644 skippy/llama_cpp/patches/0025-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch create mode 100644 skippy/llama_cpp/patches/0026-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch create mode 100644 skippy/llama_cpp/patches/0027-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch create mode 100644 skippy/llama_cpp/patches/0028-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch create mode 100644 skippy/llama_cpp/patches/0029-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch create mode 100644 skippy/llama_cpp/patches/0030-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch create mode 100644 skippy/llama_cpp/patches/0031-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch create mode 100644 skippy/llama_cpp/patches/0032-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch create mode 100644 tools/xtask/src/model_registry/derived.rs create mode 100644 tools/xtask/src/model_registry/fetch.rs create mode 100644 tools/xtask/src/model_registry/pin.rs diff --git a/Cargo.lock b/Cargo.lock index bc398818eb..4d6e0a85f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9140,6 +9140,7 @@ dependencies = [ "tonic", "tower", "tracing", + "tracy-client", "uuid", ] @@ -10277,6 +10278,27 @@ dependencies = [ "tracing-serde", ] +[[package]] +name = "tracy-client" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6131992ff3e2cb96f407eb4eb005427ba15e2687260d99089b90e60e33169ce0" +dependencies = [ + "loom", + "once_cell", + "tracy-client-sys", +] + +[[package]] +name = "tracy-client-sys" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab27f167b093214c68413a2e0bcd318f0591af475597405ff68138ba0a433379" +dependencies = [ + "cc", + "windows-targets 0.52.6", +] + [[package]] name = "trajectory-reader" version = "0.78.0" diff --git a/ci/model-artifacts/README.md b/ci/model-artifacts/README.md index ec140dca09..fefae18da8 100644 --- a/ci/model-artifacts/README.md +++ b/ci/model-artifacts/README.md @@ -6,6 +6,22 @@ to this contract. Every artifact records an immutable Hugging Face revision, its exact file set, byte sizes, SHA-256 digests, family capabilities, and the suites and cadences allowed to use it. +A suite built from models pinned elsewhere is declared, not typed in: +`derived_suites` names a pinned evals model list +(`skippy/evals/kv-validation/models.json`), the selectors to register it at +and an id prefix, and the generator refuses the registry until every derived +row exists, so a member cannot be forgotten. `cargo xtool models pin` with no +arguments registers exactly the missing rows: each file name is the list's +with its selector suffix swapped (`Qwen3.5-4B-Q4_K_M.gguf` at `BF16` is +`Qwen3.5-4B-BF16.gguf`), each id is `-` with the selector slug +swapped (`perf-qwen3.5-4b-bf16`), and the size and LFS SHA-256 come from the +Hub over the pinned HTTPS transport, with the list's own digest enforced at +its own selector. A single file enters with +`cargo xtool models pin @ --id --family +--selector --suite --tag ...`, which resolves the revision +to its commit the same way; `--expect-sha256` checks the Hub against a digest +pinned elsewhere and `--dry-run` prints the rows instead of writing them. + Run the generator after changing the registry: ```bash @@ -25,6 +41,19 @@ files with `--verify-root`. Single-file consumers additionally pass `--require-single-file` so multipart artifacts fail closed. CI caches use the artifact digest in their exact key; a cache hit is still verified before use. +A whole suite is materialized on one machine with +`cargo xtool models fetch --cadence --root `. Each +artifact lands in `//` through the pinned HTTPS +transfer and is held to the manifest's size and SHA-256; a file that already +verifies is kept, one that does not is reported and left for the operator. +`--dry-run` lists what would be fetched and how much, `--artifact-id` limits +the fetch to one artifact, and `models resolve --artifact-id +--verify-root /` checks a fetched artifact afterwards. The +`performance-*` suites are the manual performance tiers: `performance-coverage` +pins one representative of each architecture class (dense, MoE, MLA, MXFP4, +sliding window, Mamba2, RWKV7, Granite hybrid, embedding, reranker) at the +same revision the family battery certifies. + Multi-artifact manifests may declare `default_artifact_id` for callers that intentionally consume the suite's canonical fixture without selecting an artifact explicitly. Explicit `--artifact-id` selection always takes diff --git a/ci/model-artifacts/manifests/competitive-benchmark.json b/ci/model-artifacts/manifests/competitive-benchmark.json index 50b9abb423..e27bd76b7a 100644 --- a/ci/model-artifacts/manifests/competitive-benchmark.json +++ b/ci/model-artifacts/manifests/competitive-benchmark.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "competitive-benchmark", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-llama", diff --git a/ci/model-artifacts/manifests/hf-download-smoke.json b/ci/model-artifacts/manifests/hf-download-smoke.json index 0d8b65d49f..eefb1ec77f 100644 --- a/ci/model-artifacts/manifests/hf-download-smoke.json +++ b/ci/model-artifacts/manifests/hf-download-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "hf-download-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "smollm2-q4-download", diff --git a/ci/model-artifacts/manifests/openai-smoke.json b/ci/model-artifacts/manifests/openai-smoke.json index 09105cf241..b5f44ade5a 100644 --- a/ci/model-artifacts/manifests/openai-smoke.json +++ b/ci/model-artifacts/manifests/openai-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "openai-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "smollm2-q4-download", diff --git a/ci/model-artifacts/manifests/performance-coverage.json b/ci/model-artifacts/manifests/performance-coverage.json new file mode 100644 index 0000000000..d675e0b117 --- /dev/null +++ b/ci/model-artifacts/manifests/performance-coverage.json @@ -0,0 +1,409 @@ +{ + "schema_version": 1, + "manifest_kind": "test-model-artifacts", + "suite": "performance-coverage", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", + "artifacts": [ + { + "id": "perf-gpt-oss-20b-mxfp4", + "family": "gpt-oss", + "capability_tags": [ + "gguf", + "moe", + "mxfp4", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "ggml-org/gpt-oss-20b-GGUF", + "revision": "ef9b12f2ff56c69cf32153a02784e7a3c88bf524", + "selector": "MXFP4", + "files": [ + "gpt-oss-20b-MXFP4.gguf" + ], + "file_integrity": { + "gpt-oss-20b-MXFP4.gguf": { + "size_bytes": 12109566624, + "blob_id": "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901" + } + }, + "model_ref": "ggml-org/gpt-oss-20b-GGUF:MXFP4", + "urls": [ + "https://huggingface.co/ggml-org/gpt-oss-20b-GGUF/resolve/ef9b12f2ff56c69cf32153a02784e7a3c88bf524/gpt-oss-20b-MXFP4.gguf" + ], + "file": "gpt-oss-20b-MXFP4.gguf", + "size_bytes": 12109566624, + "sha256": "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901", + "url": "https://huggingface.co/ggml-org/gpt-oss-20b-GGUF/resolve/ef9b12f2ff56c69cf32153a02784e7a3c88bf524/gpt-oss-20b-MXFP4.gguf", + "notes": "Performance coverage: MXFP4 MoE with attention sinks; same pin as family-gpt-oss." + }, + { + "id": "perf-deepseek2-coder-lite-q4", + "family": "deepseek2", + "capability_tags": [ + "gguf", + "mla", + "moe", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF", + "revision": "8f248fa2072348f77a8bc37754e470de1f61866e", + "selector": "Q4_K_M", + "files": [ + "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf" + ], + "file_integrity": { + "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf": { + "size_bytes": 10364416768, + "blob_id": "603bd3f8a0281d16571da7c08bd661ee17ff0d1be6fcbd1b42242da257ef0bb8" + } + }, + "model_ref": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF/resolve/8f248fa2072348f77a8bc37754e470de1f61866e/DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf" + ], + "file": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf", + "size_bytes": 10364416768, + "sha256": "603bd3f8a0281d16571da7c08bd661ee17ff0d1be6fcbd1b42242da257ef0bb8", + "url": "https://huggingface.co/bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF/resolve/8f248fa2072348f77a8bc37754e470de1f61866e/DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf", + "notes": "Performance coverage: MLA attention MoE; same pin as family-deepseek2." + }, + { + "id": "perf-mistral-small-24b-q4", + "family": "mistral-small", + "capability_tags": [ + "dense", + "gguf", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF", + "revision": "b750ec2299225e492f1bd27cab88a0a595fa848f", + "selector": "Q4_K_M", + "files": [ + "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf" + ], + "file_integrity": { + "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf": { + "size_bytes": 14333922848, + "blob_id": "a3cc56310807ed0d145eaf9f018ccda9ae7ad8edb41ec870aa2454b0d4700b3c" + } + }, + "model_ref": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF/resolve/b750ec2299225e492f1bd27cab88a0a595fa848f/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf" + ], + "file": "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf", + "size_bytes": 14333922848, + "sha256": "a3cc56310807ed0d145eaf9f018ccda9ae7ad8edb41ec870aa2454b0d4700b3c", + "url": "https://huggingface.co/unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF/resolve/b750ec2299225e492f1bd27cab88a0a595fa848f/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf", + "notes": "Performance coverage: 24B dense; same pin as family-mistral-small." + }, + { + "id": "perf-phi4-q4", + "family": "phi4", + "capability_tags": [ + "dense", + "gguf", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "unsloth/phi-4-GGUF", + "revision": "5110b7771e8166d5530e73346a15aea096a8cb99", + "selector": "Q4_K_M", + "files": [ + "phi-4-Q4_K_M.gguf" + ], + "file_integrity": { + "phi-4-Q4_K_M.gguf": { + "size_bytes": 8890306112, + "blob_id": "01e1f25b3e6931054c6c2227b06f4969828434eebc299e8e171f55dab6814485" + } + }, + "model_ref": "unsloth/phi-4-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/unsloth/phi-4-GGUF/resolve/5110b7771e8166d5530e73346a15aea096a8cb99/phi-4-Q4_K_M.gguf" + ], + "file": "phi-4-Q4_K_M.gguf", + "size_bytes": 8890306112, + "sha256": "01e1f25b3e6931054c6c2227b06f4969828434eebc299e8e171f55dab6814485", + "url": "https://huggingface.co/unsloth/phi-4-GGUF/resolve/5110b7771e8166d5530e73346a15aea096a8cb99/phi-4-Q4_K_M.gguf", + "notes": "Performance coverage: 14B dense; same pin as family-phi4." + }, + { + "id": "perf-falcon-mamba-7b-q4", + "family": "mamba2", + "capability_tags": [ + "gguf", + "performance", + "recurrent" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "bartowski/falcon-mamba-7b-GGUF", + "revision": "1236a076ebddbcfcbd6ba0fe310d473d20527f11", + "selector": "Q4_K_M", + "files": [ + "falcon-mamba-7b-Q4_K_M.gguf" + ], + "file_integrity": { + "falcon-mamba-7b-Q4_K_M.gguf": { + "size_bytes": 4204230656, + "blob_id": "ef8ba78a1fd0b0fd1d1c966acc5f4c043b12fbbd7044f4d9aad82e6b7a51e0a7" + } + }, + "model_ref": "bartowski/falcon-mamba-7b-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/bartowski/falcon-mamba-7b-GGUF/resolve/1236a076ebddbcfcbd6ba0fe310d473d20527f11/falcon-mamba-7b-Q4_K_M.gguf" + ], + "file": "falcon-mamba-7b-Q4_K_M.gguf", + "size_bytes": 4204230656, + "sha256": "ef8ba78a1fd0b0fd1d1c966acc5f4c043b12fbbd7044f4d9aad82e6b7a51e0a7", + "url": "https://huggingface.co/bartowski/falcon-mamba-7b-GGUF/resolve/1236a076ebddbcfcbd6ba0fe310d473d20527f11/falcon-mamba-7b-Q4_K_M.gguf", + "notes": "Performance coverage: pure Mamba2 recurrence; same pin as family-mamba2." + }, + { + "id": "perf-rwkv7-2b9-q4", + "family": "rwkv7", + "capability_tags": [ + "gguf", + "performance", + "recurrent" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "Mungert/RWKV7-Goose-World3-2.9B-HF-GGUF", + "revision": "e85c69858772a4d6b481d99e1e49910dad48e123", + "selector": "Q4_K", + "files": [ + "RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf" + ], + "file_integrity": { + "RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf": { + "size_bytes": 2314884576, + "blob_id": "bfcb5b239cf99ac4a590d7163266bbe3bb14f41d221ad6f7a2bf602b610211b0" + } + }, + "model_ref": "Mungert/RWKV7-Goose-World3-2.9B-HF-GGUF:Q4_K", + "urls": [ + "https://huggingface.co/Mungert/RWKV7-Goose-World3-2.9B-HF-GGUF/resolve/e85c69858772a4d6b481d99e1e49910dad48e123/RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf" + ], + "file": "RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf", + "size_bytes": 2314884576, + "sha256": "bfcb5b239cf99ac4a590d7163266bbe3bb14f41d221ad6f7a2bf602b610211b0", + "url": "https://huggingface.co/Mungert/RWKV7-Goose-World3-2.9B-HF-GGUF/resolve/e85c69858772a4d6b481d99e1e49910dad48e123/RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf", + "notes": "Performance coverage: RWKV7 recurrence; same pin as family-rwkv7." + }, + { + "id": "perf-granite-4-h-350m-q4", + "family": "granite-hybrid", + "capability_tags": [ + "gguf", + "hybrid", + "performance", + "recurrent" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "ibm-granite/granite-4.0-h-350m-GGUF", + "revision": "a864f823cce6e6048b5752e2816fe7a23987d790", + "selector": "Q4_K_M", + "files": [ + "granite-4.0-h-350m-Q4_K_M.gguf" + ], + "file_integrity": { + "granite-4.0-h-350m-Q4_K_M.gguf": { + "size_bytes": 222662560, + "blob_id": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb" + } + }, + "model_ref": "ibm-granite/granite-4.0-h-350m-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/ibm-granite/granite-4.0-h-350m-GGUF/resolve/a864f823cce6e6048b5752e2816fe7a23987d790/granite-4.0-h-350m-Q4_K_M.gguf" + ], + "file": "granite-4.0-h-350m-Q4_K_M.gguf", + "size_bytes": 222662560, + "sha256": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb", + "url": "https://huggingface.co/ibm-granite/granite-4.0-h-350m-GGUF/resolve/a864f823cce6e6048b5752e2816fe7a23987d790/granite-4.0-h-350m-Q4_K_M.gguf", + "notes": "Performance coverage: Granite hybrid Mamba2 plus attention; same pin as family-granite-hybrid." + }, + { + "id": "perf-gemma3-1b-q4", + "family": "gemma3", + "capability_tags": [ + "dense", + "gguf", + "performance", + "swa" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "ggml-org/gemma-3-1b-it-GGUF", + "revision": "f9c28bcd85737ffc5aef028638d3341d49869c27", + "selector": "Q4_K_M", + "files": [ + "gemma-3-1b-it-Q4_K_M.gguf" + ], + "file_integrity": { + "gemma-3-1b-it-Q4_K_M.gguf": { + "size_bytes": 806058240, + "blob_id": "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135" + } + }, + "model_ref": "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/ggml-org/gemma-3-1b-it-GGUF/resolve/f9c28bcd85737ffc5aef028638d3341d49869c27/gemma-3-1b-it-Q4_K_M.gguf" + ], + "file": "gemma-3-1b-it-Q4_K_M.gguf", + "size_bytes": 806058240, + "sha256": "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135", + "url": "https://huggingface.co/ggml-org/gemma-3-1b-it-GGUF/resolve/f9c28bcd85737ffc5aef028638d3341d49869c27/gemma-3-1b-it-Q4_K_M.gguf", + "notes": "Performance coverage: sliding-window attention; same pin as family-gemma3." + }, + { + "id": "perf-llama-3-2-1b-q4", + "family": "llama", + "capability_tags": [ + "dense", + "gguf", + "llama", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "bartowski/Llama-3.2-1B-Instruct-GGUF", + "revision": "067b946cf014b7c697f3654f621d577a3e3afd1c", + "selector": "Q4_K_M", + "files": [ + "Llama-3.2-1B-Instruct-Q4_K_M.gguf" + ], + "file_integrity": { + "Llama-3.2-1B-Instruct-Q4_K_M.gguf": { + "size_bytes": 807694464, + "blob_id": "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83" + } + }, + "model_ref": "bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/067b946cf014b7c697f3654f621d577a3e3afd1c/Llama-3.2-1B-Instruct-Q4_K_M.gguf" + ], + "file": "Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "size_bytes": 807694464, + "sha256": "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83", + "url": "https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/067b946cf014b7c697f3654f621d577a3e3afd1c/Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "notes": "Performance coverage: Llama dense baseline; same pin as family-llama." + }, + { + "id": "perf-nomic-embed-q8", + "family": "nomic-bert-embedding", + "capability_tags": [ + "embedding", + "gguf", + "performance" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "nomic-ai/nomic-embed-text-v1.5-GGUF", + "revision": "0188c9bf409793f810680a5a431e7b899c46104c", + "selector": "Q8_0", + "files": [ + "nomic-embed-text-v1.5.Q8_0.gguf" + ], + "file_integrity": { + "nomic-embed-text-v1.5.Q8_0.gguf": { + "size_bytes": 146146432, + "blob_id": "3e24342164b3d94991ba9692fdc0dd08e3fd7362e0aacc396a9a5c54a544c3b7" + } + }, + "model_ref": "nomic-ai/nomic-embed-text-v1.5-GGUF:Q8_0", + "urls": [ + "https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/resolve/0188c9bf409793f810680a5a431e7b899c46104c/nomic-embed-text-v1.5.Q8_0.gguf" + ], + "file": "nomic-embed-text-v1.5.Q8_0.gguf", + "size_bytes": 146146432, + "sha256": "3e24342164b3d94991ba9692fdc0dd08e3fd7362e0aacc396a9a5c54a544c3b7", + "url": "https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/resolve/0188c9bf409793f810680a5a431e7b899c46104c/nomic-embed-text-v1.5.Q8_0.gguf", + "notes": "Performance coverage: BERT embedding; same pin as family-nomic-bert-embedding." + }, + { + "id": "perf-bge-reranker-q4", + "family": "xlm-roberta", + "capability_tags": [ + "gguf", + "performance", + "reranker" + ], + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "repo": "gpustack/bge-reranker-v2-m3-GGUF", + "revision": "3093af03b1a635e67b084b1d8c03c5f5e020fd05", + "selector": "Q4_K_M", + "files": [ + "bge-reranker-v2-m3-Q4_K_M.gguf" + ], + "file_integrity": { + "bge-reranker-v2-m3-Q4_K_M.gguf": { + "size_bytes": 438376864, + "blob_id": "e186a244ed455b4ab66ec64339ce7427a6ae13f5c0b5e544de96e50f0f8b3673" + } + }, + "model_ref": "gpustack/bge-reranker-v2-m3-GGUF:Q4_K_M", + "urls": [ + "https://huggingface.co/gpustack/bge-reranker-v2-m3-GGUF/resolve/3093af03b1a635e67b084b1d8c03c5f5e020fd05/bge-reranker-v2-m3-Q4_K_M.gguf" + ], + "file": "bge-reranker-v2-m3-Q4_K_M.gguf", + "size_bytes": 438376864, + "sha256": "e186a244ed455b4ab66ec64339ce7427a6ae13f5c0b5e544de96e50f0f8b3673", + "url": "https://huggingface.co/gpustack/bge-reranker-v2-m3-GGUF/resolve/3093af03b1a635e67b084b1d8c03c5f5e020fd05/bge-reranker-v2-m3-Q4_K_M.gguf", + "notes": "Performance coverage: XLM-RoBERTa reranker; same pin as bge-reranker-q4-cpp-api." + } + ] +} diff --git a/ci/model-artifacts/manifests/product-smoke.json b/ci/model-artifacts/manifests/product-smoke.json index 9f7bb749c4..a1efe96846 100644 --- a/ci/model-artifacts/manifests/product-smoke.json +++ b/ci/model-artifacts/manifests/product-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "product-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-granite-hybrid", diff --git a/ci/model-artifacts/manifests/radix-cache.json b/ci/model-artifacts/manifests/radix-cache.json index 2637f3a7b9..a96448c42c 100644 --- a/ci/model-artifacts/manifests/radix-cache.json +++ b/ci/model-artifacts/manifests/radix-cache.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "radix-cache", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-deepseek2", diff --git a/ci/model-artifacts/manifests/safetensors-runtime-smoke.json b/ci/model-artifacts/manifests/safetensors-runtime-smoke.json index 971a2d0aae..aa60624898 100644 --- a/ci/model-artifacts/manifests/safetensors-runtime-smoke.json +++ b/ci/model-artifacts/manifests/safetensors-runtime-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "safetensors-runtime-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "smollm2-safetensors", diff --git a/ci/model-artifacts/manifests/scripted-binary-smoke.json b/ci/model-artifacts/manifests/scripted-binary-smoke.json index 3963b2644d..78b92b3df1 100644 --- a/ci/model-artifacts/manifests/scripted-binary-smoke.json +++ b/ci/model-artifacts/manifests/scripted-binary-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "scripted-binary-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-granite-hybrid", diff --git a/ci/model-artifacts/manifests/sdk-smoke.json b/ci/model-artifacts/manifests/sdk-smoke.json index 30e24c998d..62099b8f90 100644 --- a/ci/model-artifacts/manifests/sdk-smoke.json +++ b/ci/model-artifacts/manifests/sdk-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "sdk-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "smollm2-q8-inference", diff --git a/ci/model-artifacts/manifests/skippy-ci-smoke.json b/ci/model-artifacts/manifests/skippy-ci-smoke.json index 17e4b1700d..b75d8d3eaa 100644 --- a/ci/model-artifacts/manifests/skippy-ci-smoke.json +++ b/ci/model-artifacts/manifests/skippy-ci-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "skippy-ci-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-qwen3-dense", diff --git a/ci/model-artifacts/manifests/skippy-correctness.json b/ci/model-artifacts/manifests/skippy-correctness.json index 2ee412486c..3e6d50bdd9 100644 --- a/ci/model-artifacts/manifests/skippy-correctness.json +++ b/ci/model-artifacts/manifests/skippy-correctness.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "skippy-correctness", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "qwen3-q8-correctness", diff --git a/ci/model-artifacts/manifests/skippy-cpp-api.json b/ci/model-artifacts/manifests/skippy-cpp-api.json index e5a5e1e0a4..57454490f1 100644 --- a/ci/model-artifacts/manifests/skippy-cpp-api.json +++ b/ci/model-artifacts/manifests/skippy-cpp-api.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "skippy-cpp-api", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "smollm2-q8-inference", diff --git a/ci/model-artifacts/manifests/skippy-parity.json b/ci/model-artifacts/manifests/skippy-parity.json index cacc0f8677..6519aaef05 100644 --- a/ci/model-artifacts/manifests/skippy-parity.json +++ b/ci/model-artifacts/manifests/skippy-parity.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "skippy-parity", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-deepseek2", diff --git a/ci/model-artifacts/manifests/skippy-system-one-smoke.json b/ci/model-artifacts/manifests/skippy-system-one-smoke.json index a2c93e9184..f3dcf7c33d 100644 --- a/ci/model-artifacts/manifests/skippy-system-one-smoke.json +++ b/ci/model-artifacts/manifests/skippy-system-one-smoke.json @@ -2,7 +2,7 @@ "schema_version": 1, "manifest_kind": "test-model-artifacts", "suite": "skippy-system-one-smoke", - "registry_sha256": "b728aded7ecf526901a7b2735a4cb94aac4d749c0ebb8888caa8aa82d65e134e", + "registry_sha256": "66c2ae6cf5724d2609d60c1f2f442b7de5483f43e860f4c4fa5a14332e387f59", "artifacts": [ { "id": "family-qwen3-dense", diff --git a/ci/model-artifacts/registry.json b/ci/model-artifacts/registry.json index 825eb4c9c6..adb4b73fda 100644 --- a/ci/model-artifacts/registry.json +++ b/ci/model-artifacts/registry.json @@ -24,7 +24,10 @@ "competitive-benchmark", "radix-cache", "skippy-system-one-smoke", - "skippy-cpp-api" + "skippy-cpp-api", + "performance-coverage", + "performance-core", + "performance-parity" ], "family_policy": { "profiles": { @@ -5253,6 +5256,338 @@ ] }, "notes": "Rank-pooled scalar classifier fixture used by the standalone facade Rust end-to-end suite; immutable file metadata from the source repository." + }, + { + "id": "perf-gpt-oss-20b-mxfp4", + "family": "gpt-oss", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "moe", + "mxfp4", + "performance" + ], + "artifact": { + "repo": "ggml-org/gpt-oss-20b-GGUF", + "revision": "ef9b12f2ff56c69cf32153a02784e7a3c88bf524", + "selector": "MXFP4", + "files": [ + { + "path": "gpt-oss-20b-MXFP4.gguf", + "size_bytes": 12109566624, + "sha256": "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901" + } + ] + }, + "notes": "Performance coverage: MXFP4 MoE with attention sinks; same pin as family-gpt-oss." + }, + { + "id": "perf-deepseek2-coder-lite-q4", + "family": "deepseek2", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "mla", + "moe", + "performance" + ], + "artifact": { + "repo": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF", + "revision": "8f248fa2072348f77a8bc37754e470de1f61866e", + "selector": "Q4_K_M", + "files": [ + { + "path": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf", + "size_bytes": 10364416768, + "sha256": "603bd3f8a0281d16571da7c08bd661ee17ff0d1be6fcbd1b42242da257ef0bb8" + } + ] + }, + "notes": "Performance coverage: MLA attention MoE; same pin as family-deepseek2." + }, + { + "id": "perf-mistral-small-24b-q4", + "family": "mistral-small", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "dense", + "gguf", + "performance" + ], + "artifact": { + "repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF", + "revision": "b750ec2299225e492f1bd27cab88a0a595fa848f", + "selector": "Q4_K_M", + "files": [ + { + "path": "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf", + "size_bytes": 14333922848, + "sha256": "a3cc56310807ed0d145eaf9f018ccda9ae7ad8edb41ec870aa2454b0d4700b3c" + } + ] + }, + "notes": "Performance coverage: 24B dense; same pin as family-mistral-small." + }, + { + "id": "perf-phi4-q4", + "family": "phi4", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "dense", + "gguf", + "performance" + ], + "artifact": { + "repo": "unsloth/phi-4-GGUF", + "revision": "5110b7771e8166d5530e73346a15aea096a8cb99", + "selector": "Q4_K_M", + "files": [ + { + "path": "phi-4-Q4_K_M.gguf", + "size_bytes": 8890306112, + "sha256": "01e1f25b3e6931054c6c2227b06f4969828434eebc299e8e171f55dab6814485" + } + ] + }, + "notes": "Performance coverage: 14B dense; same pin as family-phi4." + }, + { + "id": "perf-falcon-mamba-7b-q4", + "family": "mamba2", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "performance", + "recurrent" + ], + "artifact": { + "repo": "bartowski/falcon-mamba-7b-GGUF", + "revision": "1236a076ebddbcfcbd6ba0fe310d473d20527f11", + "selector": "Q4_K_M", + "files": [ + { + "path": "falcon-mamba-7b-Q4_K_M.gguf", + "size_bytes": 4204230656, + "sha256": "ef8ba78a1fd0b0fd1d1c966acc5f4c043b12fbbd7044f4d9aad82e6b7a51e0a7" + } + ] + }, + "notes": "Performance coverage: pure Mamba2 recurrence; same pin as family-mamba2." + }, + { + "id": "perf-rwkv7-2b9-q4", + "family": "rwkv7", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "performance", + "recurrent" + ], + "artifact": { + "repo": "Mungert/RWKV7-Goose-World3-2.9B-HF-GGUF", + "revision": "e85c69858772a4d6b481d99e1e49910dad48e123", + "selector": "Q4_K", + "files": [ + { + "path": "RWKV7-Goose-World3-2.9B-HF-f16-q4_k.gguf", + "size_bytes": 2314884576, + "sha256": "bfcb5b239cf99ac4a590d7163266bbe3bb14f41d221ad6f7a2bf602b610211b0" + } + ] + }, + "notes": "Performance coverage: RWKV7 recurrence; same pin as family-rwkv7." + }, + { + "id": "perf-granite-4-h-350m-q4", + "family": "granite-hybrid", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "hybrid", + "performance", + "recurrent" + ], + "artifact": { + "repo": "ibm-granite/granite-4.0-h-350m-GGUF", + "revision": "a864f823cce6e6048b5752e2816fe7a23987d790", + "selector": "Q4_K_M", + "files": [ + { + "path": "granite-4.0-h-350m-Q4_K_M.gguf", + "size_bytes": 222662560, + "sha256": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb" + } + ] + }, + "notes": "Performance coverage: Granite hybrid Mamba2 plus attention; same pin as family-granite-hybrid." + }, + { + "id": "perf-gemma3-1b-q4", + "family": "gemma3", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "dense", + "gguf", + "performance", + "swa" + ], + "artifact": { + "repo": "ggml-org/gemma-3-1b-it-GGUF", + "revision": "f9c28bcd85737ffc5aef028638d3341d49869c27", + "selector": "Q4_K_M", + "files": [ + { + "path": "gemma-3-1b-it-Q4_K_M.gguf", + "size_bytes": 806058240, + "sha256": "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135" + } + ] + }, + "notes": "Performance coverage: sliding-window attention; same pin as family-gemma3." + }, + { + "id": "perf-llama-3-2-1b-q4", + "family": "llama", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "dense", + "gguf", + "llama", + "performance" + ], + "artifact": { + "repo": "bartowski/Llama-3.2-1B-Instruct-GGUF", + "revision": "067b946cf014b7c697f3654f621d577a3e3afd1c", + "selector": "Q4_K_M", + "files": [ + { + "path": "Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "size_bytes": 807694464, + "sha256": "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83" + } + ] + }, + "notes": "Performance coverage: Llama dense baseline; same pin as family-llama." + }, + { + "id": "perf-nomic-embed-q8", + "family": "nomic-bert-embedding", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "embedding", + "gguf", + "performance" + ], + "artifact": { + "repo": "nomic-ai/nomic-embed-text-v1.5-GGUF", + "revision": "0188c9bf409793f810680a5a431e7b899c46104c", + "selector": "Q8_0", + "files": [ + { + "path": "nomic-embed-text-v1.5.Q8_0.gguf", + "size_bytes": 146146432, + "sha256": "3e24342164b3d94991ba9692fdc0dd08e3fd7362e0aacc396a9a5c54a544c3b7" + } + ] + }, + "notes": "Performance coverage: BERT embedding; same pin as family-nomic-bert-embedding." + }, + { + "id": "perf-bge-reranker-q4", + "family": "xlm-roberta", + "suites": [ + "performance-coverage" + ], + "cadences": [ + "manual" + ], + "capability_tags": [ + "gguf", + "performance", + "reranker" + ], + "artifact": { + "repo": "gpustack/bge-reranker-v2-m3-GGUF", + "revision": "3093af03b1a635e67b084b1d8c03c5f5e020fd05", + "selector": "Q4_K_M", + "files": [ + { + "path": "bge-reranker-v2-m3-Q4_K_M.gguf", + "size_bytes": 438376864, + "sha256": "e186a244ed455b4ab66ec64339ce7427a6ae13f5c0b5e544de96e50f0f8b3673" + } + ] + }, + "notes": "Performance coverage: XLM-RoBERTa reranker; same pin as bge-reranker-q4-cpp-api." + } + ], + "derived_suites": [ + { + "suite": "performance-core", + "from": "skippy/evals/kv-validation/models.json", + "selectors": [ + "Q4_K_M" + ], + "id_prefix": "perf" + }, + { + "suite": "performance-parity", + "from": "skippy/evals/kv-validation/models.json", + "selectors": [ + "Q8_0", + "BF16" + ], + "id_prefix": "perf" } ] } diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs index 263f555a6e..3e0f77dd09 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs @@ -169,6 +169,11 @@ pub(crate) fn stage0_config( kv_offload: context.runtime_settings.kv_offload, kv_unified: context.runtime_settings.kv_unified, swa_full: context.runtime_settings.swa_full, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, + prefill_coalesce_max_ms: None, cache_idle_slots: context.runtime_settings.cache_idle_slots, resident_tensor_names: Vec::new(), execution_contract: context.admission.execution_contract.clone(), diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs index 45b00a4bfa..9f78ff97eb 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs @@ -551,6 +551,8 @@ mod tests { min_tokens: 8, shared_prefix_stride_tokens: 8, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), })); let handle = SkippyModelHandle::load(options).expect("load kv-disabled local model"); diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs index ec99ae7e6e..592107908a 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/translation.rs @@ -460,6 +460,8 @@ impl ResolvedSkippyConfig { shared_prefix_record_limit: 0, l2_max_bytes: 0, codec: skippy_protocol::StageKvCacheCodec::Native, + prefill_admission: Default::default(), + retention: Default::default(), }), ResolvedStageKvCache::Explicit(template) => { let mut cache = family_default.unwrap_or(StageKvCacheConfig { @@ -472,6 +474,8 @@ impl ResolvedSkippyConfig { shared_prefix_record_limit: 2, l2_max_bytes: 0, codec: skippy_protocol::StageKvCacheCodec::Native, + prefill_admission: Default::default(), + retention: Default::default(), }); cache.mode = template.mode.clone(); if let Some(value) = template.max_entries { diff --git a/mesh/website/src/docs/pages/skippy-api.md b/mesh/website/src/docs/pages/skippy-api.md index e71d17759d..219903594e 100644 --- a/mesh/website/src/docs/pages/skippy-api.md +++ b/mesh/website/src/docs/pages/skippy-api.md @@ -9,7 +9,7 @@ description: Generated reference for the capability-oriented Skippy C ABI. This reference is generated from the patched llama.cpp public headers. It documents the native C ABI used by Skippy's Rust FFI layer and staged runtime. The ABI is experimental and versioned for lockstep native/Rust builds. -Current generated surface: **22 headers** and **137 exported functions**. +Current generated surface: **22 headers** and **138 exported functions**. ## Quick navigation @@ -199,9 +199,10 @@ Current generated surface: **22 headers** and **137 exported functions**.
- state.h20 functions + state.h21 functions
skippy_model_memory_cache_capabilities + skippy_model_kv_pool_cells skippy_export_state skippy_import_state skippy_export_full_state @@ -1767,6 +1768,16 @@ LLAMA_API uint32_t skippy_model_memory_cache_capabilities( const struct skippy_model * model); ``` + +#### `skippy_model_kv_pool_cells` + +Cells in the model's KV pool, the capacity admission shares among its lanes; 0 before a context exists. + +```cpp +LLAMA_API uint32_t skippy_model_kv_pool_cells( + const struct skippy_model * model); +``` + #### `skippy_export_state` @@ -2295,7 +2306,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `activation.h`: `skippy_activation_part_desc`, `skippy_activation_boundary_desc`, `skippy_activation_desc`, `SKIPPY_ACTIVATION_FRAME_VERSION = 2`, `SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION = 2`, `SKIPPY_ACTIVATION_IDENTITY_BYTES = 32`, `SKIPPY_ACTIVATION_MAX_DIMS = 4`, `SKIPPY_ACTIVATION_MAX_PARTS = 16`, `SKIPPY_ACTIVATION_PART_OPTIONAL = (UINT32_C(1) << 0)` - `asr.h`: `skippy_asr_model`, `skippy_asr_result`, `skippy_asr_info_v1`, `skippy_asr_transcribe_params_v1`, `skippy_asr_segment_v1`, `SKIPPY_ASR_INFO_V1_ABI_VERSION = 1`, `SKIPPY_ASR_TRANSCRIBE_PARAMS_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SEGMENT_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SAMPLE_RATE = 16000`, `SKIPPY_ASR_MAX_SAMPLES = (SKIPPY_ASR_SAMPLE_RATE * 60 * 30)` - `clef.h`: `skippy_clef_model`, `skippy_clef_order`, `skippy_clef_info_v1`, `SKIPPY_CLEF_INFO_V1_ABI_VERSION = 1` -- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 81`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` +- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 83`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` - `devices.h`: `skippy_backend_device_type`, `skippy_backend_device_cap`, `skippy_backend_device` - `events.h`: `skippy_runtime_event_v1`, `skippy_runtime_event_reporter_v1`, `SKIPPY_RUNTIME_EVENT_V1_ABI_VERSION = 1` - `execution.h`: `skippy_token_score_request`, `skippy_iteration_request` diff --git a/skippy/crates/llama-spec-bench/src/main.rs b/skippy/crates/llama-spec-bench/src/main.rs index 835c8e0c71..58f92e3279 100644 --- a/skippy/crates/llama-spec-bench/src/main.rs +++ b/skippy/crates/llama-spec-bench/src/main.rs @@ -353,6 +353,10 @@ fn full_model_config(path: &Path, ctx_size: u32, n_gpu_layers: i32) -> Result Result { } } +/// A token count, or `unbounded` for whatever the pool has room for, as +/// `StageKvRetention` serializes. +fn retention(value: &Value) -> Result { + if value.as_str() == Some("unbounded") { + return Ok(json!("unbounded")); + } + let tokens = value + .as_u64() + .or_else(|| value.as_str().and_then(|text| text.parse::().ok())) + .context("prefix-cache-retention-tokens must be a token count or unbounded")?; + Ok(json!({ "tokens": tokens })) +} + pub(super) fn set(object: &mut Value, path: &str, value: Value) { if !object.is_object() { *object = json!({}); diff --git a/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs b/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs index 003199a83c..a58f893fe6 100644 --- a/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs +++ b/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs @@ -162,6 +162,10 @@ pub fn kv_page_growth(args: KvPageGrowthArgs) -> Result<()> { kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }; plan.apply_to(&mut config); let model = StageModel::open(&args.runtime.model, &config) diff --git a/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs b/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs index 1d2f4b5644..3977baa612 100644 --- a/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs +++ b/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs @@ -331,6 +331,10 @@ fn open_full_model(args: &RemoteHandoffArgs, lane_count: u32) -> Result Result Result Result { kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }; let stage0 = StageModel::open(&stage0_resolution.path, &stage0_config) .context("failed to open stage 0")?; diff --git a/skippy/crates/skippy-correctness/src/runner/stage_execution.rs b/skippy/crates/skippy-correctness/src/runner/stage_execution.rs index f6221255f3..089e99a70b 100644 --- a/skippy/crates/skippy-correctness/src/runner/stage_execution.rs +++ b/skippy/crates/skippy-correctness/src/runner/stage_execution.rs @@ -510,6 +510,10 @@ pub(in crate::runner) fn tokenizer_model_for_state_handoff( kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }, )) } diff --git a/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs b/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs index 5afc047521..8eb55e8e6b 100644 --- a/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs +++ b/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs @@ -127,6 +127,10 @@ fn decode_boundary( kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }; plan.apply_to(&mut config); let selection = select_layer_package_parts(&PackageStageRequest { diff --git a/skippy/crates/skippy-correctness/src/runner/state_handoff.rs b/skippy/crates/skippy-correctness/src/runner/state_handoff.rs index 276ee21b1e..767f3d838e 100644 --- a/skippy/crates/skippy-correctness/src/runner/state_handoff.rs +++ b/skippy/crates/skippy-correctness/src/runner/state_handoff.rs @@ -1033,6 +1033,10 @@ fn open_local_state_model( kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }; StageModel::open(&stage_resolution.path, &runtime_config) .context("failed to open local state handoff stage") @@ -1611,6 +1615,10 @@ fn build_state_handoff_inputs( kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }; let input_model = StageModel::open(&input_resolution.path, &input_config) .context("failed to open state handoff input producer")?; diff --git a/skippy/crates/skippy-correctness/tests/parity_models/mod.rs b/skippy/crates/skippy-correctness/tests/parity_models/mod.rs index b996bc03ca..f1bdca8136 100644 --- a/skippy/crates/skippy-correctness/tests/parity_models/mod.rs +++ b/skippy/crates/skippy-correctness/tests/parity_models/mod.rs @@ -1640,6 +1640,10 @@ fn open_stage_model(path: &StagePath, shape: StageShape, n_gpu_layers: i32) -> R kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, }, ) .with_context(|| { diff --git a/skippy/crates/skippy-ffi/README.md b/skippy/crates/skippy-ffi/README.md index 85482d1302..7fb77a8a22 100644 --- a/skippy/crates/skippy-ffi/README.md +++ b/skippy/crates/skippy-ffi/README.md @@ -105,7 +105,7 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.81`. The patch header in +The staged ABI is versioned as `0.1.83`. The patch header in `skippy/llama_cpp/patches/` and the Rust constants in `skippy/crates/skippy-ffi/src/lib.rs` are the source of truth, so keep this README aligned with those files instead of treating it as canonical prose. diff --git a/skippy/crates/skippy-ffi/src/bindings/skippy.rs b/skippy/crates/skippy-ffi/src/bindings/skippy.rs index e4b82c603d..e0cb34ab6f 100644 --- a/skippy/crates/skippy-ffi/src/bindings/skippy.rs +++ b/skippy/crates/skippy-ffi/src/bindings/skippy.rs @@ -6,7 +6,7 @@ pub const SKIPPY_ABI_VERSION_MAJOR: u32 = 0; pub const SKIPPY_ABI_VERSION_MINOR: u32 = 1; -pub const SKIPPY_ABI_VERSION_PATCH: u32 = 81; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 83; pub const SKIPPY_ACTIVATION_FRAME_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_IDENTITY_BYTES: u32 = 32; @@ -621,6 +621,14 @@ pub struct skippy_runtime_config { pub kv_unified: i32, #[doc = " @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`)."] pub swa_full: i32, + #[doc = " @brief Cells in the unified KV pool, which the lanes share. 0 reserves `ctx_size` for every lane (`ctx_size` x `lane_count`), so each lane can reach its window whatever the others hold. Any other value is the whole pool: it must hold at least one lane's `ctx_size`, and requires a unified cache."] + pub kv_pool_tokens: u32, + #[doc = " @brief Whether KV cells are zeroed as the pool's high-water mark advances rather than all at creation. AUTO and TRUE zero lazily wherever the cache layout and its buffers allow; FALSE zeroes the whole pool at creation and keeps every page, as upstream does."] + pub kv_lazy_clear: i32, + #[doc = " @brief Whether chunks of free KV cells hand their pages back to the kernel. AUTO and TRUE release wherever cells are zeroed lazily and the pool's memory is host-visible; FALSE keeps the pages."] + pub kv_release_pages: i32, + #[doc = " @brief Whether attention reads a unified pool through per-owner row lists. AUTO and TRUE use row lists wherever the backend supports them; FALSE keeps ordinary attention over the whole pool, to measure one against the other."] + pub kv_row_attention: i32, #[doc = " @brief Whether the backend offloads host tensor operations to device (mirrors upstream `op_offload`). SKIPPY_TRISTATE_AUTO preserves llama.cpp's derived default (enabled); FALSE/TRUE force the value."] pub op_offload: i32, #[doc = " @brief Whether model loading bypasses the host buffer, allowing extra buffers to be used (mirrors upstream `no_host`)."] @@ -1443,6 +1451,10 @@ unsafe extern "C" { #[doc = " @brief Returns complete cache representations admitted by the built graph and loaded memory.\n Graph state effects restrict the loaded memory adapters' complete export capabilities.\n Full-state serialization is admitted explicitly too. Zero means no complete\n cache representation is available; callers cannot supply capability labels."] pub fn skippy_model_memory_cache_capabilities(model: *const skippy_model) -> u32; } +unsafe extern "C" { + #[doc = " @brief Cells in the model's KV pool, the capacity admission shares among its lanes; 0 before a context exists."] + pub fn skippy_model_kv_pool_cells(model: *const skippy_model) -> u32; +} #[repr(u32)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum skippy_kv_page_flag { diff --git a/skippy/crates/skippy-ffi/src/dynamic.rs b/skippy/crates/skippy-ffi/src/dynamic.rs index 3c11dde06b..12a3b0bf45 100644 --- a/skippy/crates/skippy-ffi/src/dynamic.rs +++ b/skippy/crates/skippy-ffi/src/dynamic.rs @@ -264,6 +264,7 @@ dynamic_symbols! { skippy_import_kv_page(session: *mut Session, desc: *const KvPageDesc, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; skippy_import_cachegen_kv_page_v1(session: *mut Session, desc: *const KvPageDesc, records: *const CacheGenRecordV1, record_count: usize, out_error: *mut *mut Error) -> Status; skippy_model_memory_cache_capabilities(model: *const Model) -> u32; + skippy_model_kv_pool_cells(model: *const Model) -> u32; skippy_export_recurrent_state(session: *mut Session, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_import_recurrent_state(session: *mut Session, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; skippy_session_export_resident_kv_page(session: *mut Session, cache_seq_id: i32, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; diff --git a/skippy/crates/skippy-ffi/src/lib.rs b/skippy/crates/skippy-ffi/src/lib.rs index 8ae546b423..ef1a05752d 100644 --- a/skippy/crates/skippy-ffi/src/lib.rs +++ b/skippy/crates/skippy-ffi/src/lib.rs @@ -5,7 +5,7 @@ mod dynamic_library; // without compiling the crate to determine native-runtime compatibility. pub const ABI_VERSION_MAJOR: u32 = 0; pub const ABI_VERSION_MINOR: u32 = 1; -pub const ABI_VERSION_PATCH: u32 = 81; +pub const ABI_VERSION_PATCH: u32 = 83; // The facade constants are parsed without compiling; tie them to the generated // bindings' view of the native ABI version at compile time so a common.h bump @@ -189,8 +189,8 @@ pub use dynamic::{ skippy_laya_read, skippy_laya_tokenize, skippy_model_attach_mtp_draft_model_fn, skippy_model_free, skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, skippy_model_input_activation_boundary, - skippy_model_llama_model, skippy_model_memory_cache_capabilities, skippy_model_open, - skippy_model_open_from_parts, skippy_model_open_from_parts_with_events_fn, + skippy_model_kv_pool_cells, skippy_model_llama_model, skippy_model_memory_cache_capabilities, + skippy_model_open, skippy_model_open_from_parts, skippy_model_open_from_parts_with_events_fn, skippy_model_open_from_source, skippy_model_open_with_events_fn, skippy_model_output_activation_boundary, skippy_model_supports_causal_readout, skippy_model_workload_info_v1, skippy_ngram_cache_append, skippy_ngram_cache_create, @@ -261,7 +261,7 @@ pub use static_bindings::{ skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, skippy_model_attach_mtp_draft_model, skippy_model_free, skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, - skippy_model_input_activation_boundary, skippy_model_llama_model, + skippy_model_input_activation_boundary, skippy_model_kv_pool_cells, skippy_model_llama_model, skippy_model_memory_cache_capabilities, skippy_model_open, skippy_model_open_from_parts, skippy_model_open_from_source, skippy_model_output_activation_boundary, skippy_model_supports_causal_readout, skippy_model_workload_info_v1, skippy_ngram_cache_append, diff --git a/skippy/crates/skippy-protocol/src/config.rs b/skippy/crates/skippy-protocol/src/config.rs index 55098cfe66..2ac70f3c71 100644 --- a/skippy/crates/skippy-protocol/src/config.rs +++ b/skippy/crates/skippy-protocol/src/config.rs @@ -1,6 +1,7 @@ //! Stage configuration, topology, and activation contracts. use serde::{Deserialize, Deserializer, Serialize, de}; +use std::num::NonZeroU32; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct StageIdentity { pub run_id: String, @@ -432,8 +433,30 @@ pub struct StageConfig { pub kv_unified: Option, #[serde(default)] pub swa_full: Option, + /// Cells in the unified KV pool, which the lanes share; at least + /// `ctx_size`. None reserves `ctx_size` for every lane, so each can reach + /// its window whatever the others hold. + #[serde(default)] + pub kv_pool_tokens: Option, + /// Zero KV cells as the pool's high-water mark advances rather than all at + /// load. None and true are lazy wherever the cache supports it. + #[serde(default)] + pub kv_lazy_clear: Option, + /// Hand the pages of free KV cells back to the system. None and true + /// release wherever the pool's memory is host-visible. + #[serde(default)] + pub kv_release_pages: Option, + /// Read a unified pool through per-owner row lists. None and true use + /// them wherever the backend supports it; false keeps ordinary attention + /// over the whole pool. + #[serde(default)] + pub kv_row_attention: Option, #[serde(default)] pub cache_idle_slots: Option, + /// The longest a prompt waits for others to join its prefill wave, in + /// milliseconds. None is the scheduler's own ceiling; zero never waits. + #[serde(default)] + pub prefill_coalesce_max_ms: Option, /// Exact native tensor names resolved locally from admitted package-v2 /// tensor IDs. Empty is valid only for an unsplit full-model load. #[serde( @@ -563,6 +586,50 @@ pub struct StageKvCacheConfig { pub shared_prefix_stride_tokens: u64, #[serde(default = "default_kv_cache_shared_record_limit")] pub shared_prefix_record_limit: u64, + /// How a prompt enters the runtime once its prefix has been looked up. + #[serde(default)] + pub prefill_admission: StagePrefillAdmission, + /// What finished requests may keep resident in the KV pool for reuse. + #[serde(default)] + pub retention: StageKvRetention, +} + +/// How many KV pool cells finished requests may keep resident, beyond what +/// active sessions hold, so a later prompt can reuse them. Retention fills +/// whatever it is allowed, and the pool's resident memory follows it there. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StageKvRetention { + /// At most this many cells; zero keeps nothing once a request ends. + Tokens(u64), + /// Whatever the pool has room for. + Unbounded, +} + +impl StageKvRetention { + /// A few dozen typical prompts, or four 4k-token contexts. + pub const DEFAULT_TOKENS: u64 = 16_384; +} + +impl Default for StageKvRetention { + fn default() -> Self { + Self::Tokens(Self::DEFAULT_TOKENS) + } +} + +/// Prompt admission policy. Prefix lookup and restore always run as one cache +/// operation under the runtime lock; the policy decides who prefills the rest. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum StagePrefillAdmission { + /// The cache operation prefills the whole prompt itself: one prompt at a + /// time, and every other request's decode waits for it. + Serialized, + /// The cache operation restores the prefix only; the suffix is prefilled + /// as iteration batches that coalesce with other requests' prompt chunks + /// and decode rows. + #[default] + Cooperative, } fn default_kv_cache_mode() -> StageKvCacheMode { diff --git a/skippy/crates/skippy-protocol/src/lib.rs b/skippy/crates/skippy-protocol/src/lib.rs index fc4d9e0783..e830c3a7e3 100644 --- a/skippy/crates/skippy-protocol/src/lib.rs +++ b/skippy/crates/skippy-protocol/src/lib.rs @@ -27,7 +27,8 @@ pub use config::{ ActivationDType, ActivationDescriptor, ActivationLayout, FlashAttentionType, GlmDsaPolicy, HostExpertLayers, HostExpertPolicy, LoadMode, PeerConfig, SplitMode, StageActivationCodec, StageActivationCodecPolicy, StageConfig, StageDevice, StageIdentity, StageKvCacheCodec, - StageKvCacheConfig, StageKvCacheMode, StageTopology, StageTopologyEntry, + StageKvCacheConfig, StageKvCacheMode, StageKvRetention, StagePrefillAdmission, StageTopology, + StageTopologyEntry, }; pub use messages::{ AckMessage, DecodeTokenMessage, ErrorMessage, FinalPrefillChunkMessage, MessageBase, diff --git a/skippy/crates/skippy-quantize/src/mtp_attach.rs b/skippy/crates/skippy-quantize/src/mtp_attach.rs index e8ae499098..067e10365e 100644 --- a/skippy/crates/skippy-quantize/src/mtp_attach.rs +++ b/skippy/crates/skippy-quantize/src/mtp_attach.rs @@ -208,6 +208,10 @@ fn runtime_config( kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, checkpoint_quantization: skippy_runtime::CheckpointQuantization::Preserve, checkpoint_imatrix: None, checkpoint_imatrix_sha256: None, diff --git a/skippy/crates/skippy-runtime/src/config.rs b/skippy/crates/skippy-runtime/src/config.rs index 6407e68d1f..dd22c47a81 100644 --- a/skippy/crates/skippy-runtime/src/config.rs +++ b/skippy/crates/skippy-runtime/src/config.rs @@ -1,4 +1,5 @@ use std::ffi::CString; +use std::num::NonZeroU32; use std::ptr; use anyhow::{Context, Result, anyhow}; @@ -134,6 +135,20 @@ pub struct RuntimeConfig { /// Sliding-window-attention full (unshifted) cache window. `None` /// preserves llama.cpp's built-in default (full). pub swa_full: Option, + /// Cells in the unified KV pool, which the lanes share; at least + /// `ctx_size`. `None` reserves `ctx_size` for every lane. + pub kv_pool_tokens: Option, + /// Zero KV cells as the pool's high-water mark advances rather than all + /// at load. `None` and `Some(true)` are lazy wherever the cache supports + /// it; `Some(false)` zeroes the whole pool at load and keeps every page. + pub kv_lazy_clear: Option, + /// Hand the pages of free KV cells back to the system. `None` and + /// `Some(true)` release wherever the pool's memory is host-visible. + pub kv_release_pages: Option, + /// Read a unified pool through per-owner row lists. `None` and + /// `Some(true)` use them wherever the backend supports it; `Some(false)` + /// keeps ordinary attention over the whole pool. + pub kv_row_attention: Option, /// Whether the backend offloads host tensor operations to device. `None` /// preserves llama.cpp's derived default (enabled). pub op_offload: Option, @@ -396,6 +411,10 @@ impl RuntimeConfig { kv_offload: tristate(self.kv_offload), kv_unified: tristate(self.kv_unified), swa_full: tristate(self.swa_full), + kv_pool_tokens: self.kv_pool_tokens.map_or(0, NonZeroU32::get), + kv_lazy_clear: tristate(self.kv_lazy_clear), + kv_release_pages: tristate(self.kv_release_pages), + kv_row_attention: tristate(self.kv_row_attention), op_offload: tristate(self.op_offload), no_host_buffer: self.no_host_buffer, check_tensors: self.check_tensors, @@ -537,6 +556,10 @@ impl Default for RuntimeConfig { kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, op_offload: None, no_host_buffer: false, check_tensors: false, @@ -1082,6 +1105,31 @@ mod tests { assert_eq!(raw.kv_offload, skippy_ffi::TRISTATE_AUTO); assert_eq!(raw.kv_unified, skippy_ffi::TRISTATE_AUTO); assert_eq!(raw.swa_full, skippy_ffi::TRISTATE_AUTO); + assert_eq!(raw.kv_pool_tokens, 0); + assert_eq!(raw.kv_lazy_clear, skippy_ffi::TRISTATE_AUTO); + assert_eq!(raw.kv_release_pages, skippy_ffi::TRISTATE_AUTO); + assert_eq!(raw.kv_row_attention, skippy_ffi::TRISTATE_AUTO); + Ok(()) + } + + /// The pool and what it does with unused memory reach native as + /// configured: a shared pool by its cell count, each switch as a tristate. + #[test] + fn runtime_config_raw_carries_kv_memory_settings() -> anyhow::Result<()> { + let raw = RuntimeConfig { + kv_pool_tokens: NonZeroU32::new(32_768), + kv_lazy_clear: Some(false), + kv_release_pages: Some(false), + kv_row_attention: Some(true), + ..RuntimeConfig::default() + } + .as_raw()? + .raw; + + assert_eq!(raw.kv_pool_tokens, 32_768); + assert_eq!(raw.kv_lazy_clear, skippy_ffi::TRISTATE_FALSE); + assert_eq!(raw.kv_release_pages, skippy_ffi::TRISTATE_FALSE); + assert_eq!(raw.kv_row_attention, skippy_ffi::TRISTATE_TRUE); Ok(()) } diff --git a/skippy/crates/skippy-runtime/src/native.rs b/skippy/crates/skippy-runtime/src/native.rs index cfab68b3f3..ae47dd8dfa 100644 --- a/skippy/crates/skippy-runtime/src/native.rs +++ b/skippy/crates/skippy-runtime/src/native.rs @@ -186,6 +186,13 @@ impl StageModel { !self.inner.raw.is_null() } + /// Cells in the native KV pool, the capacity admission shares among the + /// lanes. The dummy model has no pool. + pub fn kv_pool_cells(&self) -> Option { + self.has_native_model() + .then(|| unsafe { skippy_ffi::skippy_model_kv_pool_cells(self.inner.raw) }) + } + pub fn output_activation_boundary(&self) -> Option { let mut raw = skippy_ffi::ActivationBoundaryDesc::default(); let present = unsafe { diff --git a/skippy/crates/skippy-runtime/src/tests.rs b/skippy/crates/skippy-runtime/src/tests.rs index 30c46629ec..d8bf413d39 100644 --- a/skippy/crates/skippy-runtime/src/tests.rs +++ b/skippy/crates/skippy-runtime/src/tests.rs @@ -124,6 +124,10 @@ mod tests { kv_offload: None, kv_unified: None, swa_full: None, + kv_pool_tokens: None, + kv_lazy_clear: None, + kv_release_pages: None, + kv_row_attention: None, op_offload: None, no_host_buffer: false, check_tensors: false, diff --git a/skippy/crates/skippy-serving/Cargo.toml b/skippy/crates/skippy-serving/Cargo.toml index 20b31b4464..9ea5d21775 100644 --- a/skippy/crates/skippy-serving/Cargo.toml +++ b/skippy/crates/skippy-serving/Cargo.toml @@ -15,6 +15,8 @@ path = "src/lib.rs" default = [] dynamic-native-runtime = ["skippy-runtime/dynamic-native-runtime"] test-support = [] +# Tracy as a telemetry sink; see src/telemetry/tracy_sink.rs +tracy = ["dep:tracy-client"] [dependencies] skippy-config = { path = "../skippy-config", version = "0.78.0" } @@ -45,6 +47,7 @@ libc = "0.2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync"] } tonic = "0.14" tracing = "0.1" +tracy-client = { version = "0.18", optional = true, default-features = false, features = ["enable", "fibers", "ondemand", "only-localhost"] } uuid = { version = "1", features = ["v4"] } [dev-dependencies] diff --git a/skippy/crates/skippy-serving/build.rs b/skippy/crates/skippy-serving/build.rs new file mode 100644 index 0000000000..5165a5e942 --- /dev/null +++ b/skippy/crates/skippy-serving/build.rs @@ -0,0 +1,65 @@ +//! Records the commit this crate is built from as `SKIPPY_GIT_COMMIT`, the +//! `git.commit.sha` telemetry resource attribute. Read from the repository's +//! own files rather than by running git, so a build without git on `PATH` +//! still knows its commit; a build from an exported tree, with no +//! repository, reports `unknown` unless `SKIPPY_GIT_COMMIT` says otherwise. + +use std::{ + env, fs, + path::{Path, PathBuf}, +}; + +fn main() { + println!("cargo:rerun-if-env-changed=SKIPPY_GIT_COMMIT"); + let commit = env::var("SKIPPY_GIT_COMMIT") + .ok() + .filter(|commit| !commit.trim().is_empty()) + .or_else(|| head_commit(&PathBuf::from(env::var_os("CARGO_MANIFEST_DIR")?))) + .unwrap_or_else(|| "unknown".to_string()); + println!("cargo:rustc-env=SKIPPY_GIT_COMMIT={commit}"); +} + +/// The commit `HEAD` names in the repository enclosing `manifest_dir`. +fn head_commit(manifest_dir: &Path) -> Option { + let dot_git = manifest_dir + .ancestors() + .map(|dir| dir.join(".git")) + .find(|candidate| candidate.exists())?; + let git_dir = git_dir(&dot_git)?; + let head = read_watched(&git_dir.join("HEAD"))?; + let Some(reference) = head.strip_prefix("ref: ") else { + return Some(head); + }; + // a worktree's refs live in the main repository's git directory + let common_dir = read_watched(&git_dir.join("commondir")) + .map(|common| git_dir.join(common)) + .unwrap_or(git_dir); + read_watched(&common_dir.join(reference)) + .or_else(|| packed_ref(&common_dir.join("packed-refs"), reference)) +} + +/// `.git` is the git directory, or a file naming it for a worktree or submodule. +fn git_dir(dot_git: &Path) -> Option { + if dot_git.is_dir() { + return Some(dot_git.to_path_buf()); + } + let pointer = read_watched(dot_git)?; + let target = pointer.strip_prefix("gitdir: ")?; + Some(dot_git.parent()?.join(target)) +} + +fn packed_ref(packed_refs: &Path, reference: &str) -> Option { + read_watched(packed_refs)? + .lines() + .filter_map(|line| line.split_once(' ')) + .find(|(_, name)| *name == reference) + .map(|(commit, _)| commit.to_string()) +} + +/// The trimmed contents of a file the build must watch; absent files are not +/// watched, since cargo reruns the script every build for a missing path. +fn read_watched(path: &Path) -> Option { + let contents = fs::read_to_string(path).ok()?; + println!("cargo:rerun-if-changed={}", path.display()); + Some(contents.trim().to_string()) +} diff --git a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs index 1a2c600a10..9e887c806f 100644 --- a/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs +++ b/skippy/crates/skippy-serving/src/binary_transport/stage_execution.rs @@ -1166,6 +1166,8 @@ pub(in crate::binary_transport) fn prefix_cache_test_config() -> StageConfig { min_tokens: 256, shared_prefix_stride_tokens: 128, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: true, load_mode: LoadMode::RuntimeSlice, diff --git a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs index 4316066614..1504fa1973 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/tests.rs @@ -5,6 +5,7 @@ use crate::frontend::EmbeddedOpenAiRequestDefaults; use crate::frontend::SpeculativeDecodeConfig; use crate::frontend::admission::GenerationTokenBudget; use crate::frontend::generation::InferenceBackendMode; +use crate::frontend::generation::LoadedModel; use crate::frontend::iteration_scheduler::IterationScheduler; use crate::frontend::prefill::PrefillChunkPolicy; use crate::runtime_state::RuntimeState; @@ -340,6 +341,7 @@ pub(super) fn hooks_test_backend( let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); StageOpenAiBackend { runtime: runtime.clone(), + model: LoadedModel::from_runtime(&runtime), runtime_lane_admission, workload: Default::default(), config: config.clone(), diff --git a/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs b/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs index f65fec6f87..439287ed8a 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs @@ -388,6 +388,10 @@ pub(in crate::frontend) fn draft_runtime_config( kv_offload: config.kv_offload, kv_unified: config.kv_unified, swa_full: config.swa_full, + kv_pool_tokens: config.kv_pool_tokens, + kv_lazy_clear: config.kv_lazy_clear, + kv_release_pages: config.kv_release_pages, + kv_row_attention: config.kv_row_attention, }) } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs b/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs index c4415c66d9..00f915171e 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/http_request_span.rs @@ -33,7 +33,8 @@ pub(in crate::frontend) async fn openai_http_telemetry( Some(&telemetry), "stage.openai_http_request", SpanLevel::Summary, - ); + ) + .with_metrics(); telemetry.record_resources_on(span.frame(), "request_start"); let method = request.method().to_string(); let path = request.uri().path().to_string(); diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index 19e573303b..0142aa374c 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -12,6 +12,7 @@ use crate::frontend::generation::GenerationConcurrencyController; use crate::frontend::generation::GenerationServiceEstimator; use crate::frontend::generation::InferenceBackendMode; use crate::frontend::generation::PersistentStageLanePool; +use crate::frontend::generation::LoadedModel; use crate::frontend::generation::StageOpenAiBackend; use crate::frontend::generation::attach_dflash_draft; use crate::frontend::generation::attach_native_mtp_draft_model; @@ -448,8 +449,10 @@ fn embedded_openai_backend_with_state_kind( args.telemetry.clone(), )?, }; + let model = LoadedModel::from_runtime(&args.runtime); let stage_backend = Arc::new(StageOpenAiBackend { runtime: args.runtime, + model, runtime_lane_admission, workload: Default::default(), config: args.config.clone(), diff --git a/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs b/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs index 1d2fbad3bf..d00b1f260e 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs @@ -17,8 +17,6 @@ use crate::frontend::util::openai_backend_error; use crate::frontend::util::saturating_u32; use crate::frontend::util::trim_at_stop; use crate::frontend::util::valid_utf8_prefix_len; -use crate::runtime_state::RuntimeState; -use crate::runtime_state::panic_recovery::lock_runtime; use serde_json::Value; use skippy_inference_api::CompletionChunk; use skippy_inference_api::FinishReason; @@ -31,8 +29,6 @@ use skippy_inference_api::generation::GenerationEvent; use skippy_inference_api::generation::GenerationRequest; use skippy_runtime::StageModelReader; use std::collections::BTreeMap; -use std::sync::Arc; -use std::sync::Mutex; use std::time::Instant; pub(in crate::frontend) type GenerationStream = std::pin::Pin< @@ -193,7 +189,7 @@ impl ChatOutputStreamParser { ) -> InferenceResult { let passthrough_content = chat_stream_can_passthrough_content(&request, &metadata, emit_reasoning); - let model = lock_runtime(&backend.runtime).model.reader(); + let model = backend.model_reader(); Ok(Self { backend, model, @@ -375,7 +371,7 @@ where F: FnMut(&str) -> InferenceResult<()>, { pub(in crate::frontend) fn new( - runtime: Arc>, + model: StageModelReader, stop_values: Vec<&'a str>, on_text_chunk: F, ) -> InferenceResult { @@ -384,7 +380,6 @@ where .map(|value| value.len()) .max() .unwrap_or(0); - let model = lock_runtime(&runtime).model.reader(); Ok(Self { model, stop_values, diff --git a/skippy/crates/skippy-serving/src/frontend/generation/types.rs b/skippy/crates/skippy-serving/src/frontend/generation/types.rs index ea6d2ef39d..b6b09f547f 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/types.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/types.rs @@ -46,9 +46,32 @@ pub(in crate::frontend) struct GenerationSessionLockEntry { pub(in crate::frontend) users: AtomicUsize, } +/// The loaded model's immutable surface — template rendering, tokenization, +/// the media marker — taken from the runtime once at startup so request +/// preparation never waits on the runtime lock behind a native batch. +#[derive(Clone)] +pub(in crate::frontend) struct LoadedModel { + pub(in crate::frontend) reader: skippy_runtime::StageModelReader, + pub(in crate::frontend) media_marker: String, +} + +impl LoadedModel { + pub(in crate::frontend) fn from_state(runtime: &RuntimeState) -> Self { + Self { + reader: runtime.model.reader(), + media_marker: runtime.media_marker(), + } + } + + pub(in crate::frontend) fn from_runtime(runtime: &Arc>) -> Self { + Self::from_state(&crate::runtime_state::panic_recovery::lock_runtime(runtime)) + } +} + #[derive(Clone)] pub(in crate::frontend) struct StageOpenAiBackend { pub(in crate::frontend) runtime: Arc>, + pub(in crate::frontend) model: LoadedModel, pub(in crate::frontend) runtime_lane_admission: Arc, pub(in crate::frontend) workload: Arc, diff --git a/skippy/crates/skippy-serving/src/frontend/generation_flow.rs b/skippy/crates/skippy-serving/src/frontend/generation_flow.rs index 324f1e26f3..20dc63c1e1 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation_flow.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation_flow.rs @@ -287,7 +287,7 @@ impl StageOpenAiBackend { let mut receipt_cancelled = false; let mut receipt_model_generation_elapsed = None; let mut collector = - TextGenerationCollector::new(self.runtime.clone(), stop_values, on_text_chunk)? + TextGenerationCollector::new(self.model_reader(), stop_values, on_text_chunk)? .with_emulation_stop(emulation_active) .with_ignore_eos(sampling.ignore_eos); let (result, mut session_cleanup) = LocalSessionCleanupGuard::run( @@ -685,7 +685,7 @@ impl StageOpenAiBackend { .map(String::as_str) .collect::>(); let mut collector = - TextGenerationCollector::new(self.runtime.clone(), stop_values, on_text_chunk)? + TextGenerationCollector::new(self.model_reader(), stop_values, on_text_chunk)? .with_emulation_stop(request.emulation_active) .with_ignore_eos(request.sampling.ignore_eos); let session_id = request.ids.session_id; diff --git a/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs b/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs index 2ebd1917f7..82f077aa05 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs @@ -104,7 +104,7 @@ impl StageOpenAiBackend { )); } let mut collector = - TextGenerationCollector::new(self.runtime.clone(), stop_values, on_text_chunk)? + TextGenerationCollector::new(self.model_reader(), stop_values, on_text_chunk)? .with_ignore_eos(sampling.ignore_eos); let cache_stats = self.generate_encoder_decoder_tokens( &prompt_token_ids, @@ -197,7 +197,7 @@ impl StageOpenAiBackend { let emulation_active = emulation_generation_active(hook_request.as_ref(), &prompt); let mut collector = - TextGenerationCollector::new(self.runtime.clone(), stop_values, on_text_chunk)? + TextGenerationCollector::new(self.model_reader(), stop_values, on_text_chunk)? .with_emulation_stop(emulation_active) .with_ignore_eos(sampling.ignore_eos); // The gate's verdict, applied once for this request rather than looked diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index a13a1ad5a6..7528afda0e 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -15,8 +15,10 @@ use self::cache_runtime::{ }; use self::direct_batch::{ PIPELINE_DECODE_GROUPS_ENV, direct_coalesce_target, effective_scheduler_lane_count, - pipeline_group_batch_size, resolve_pipeline_decode_groups, scheduler_safe_mode_from_value, - should_serve_direct, take_direct_iteration_batch, validate_direct_iteration, + pipeline_group_batch_size, prefill_coalesce_max, prefill_coalesce_window, + resolve_pipeline_decode_groups, + scheduler_safe_mode_from_value, should_serve_direct, take_direct_iteration_batch, + validate_direct_iteration, }; use self::direct_reply::DirectReply; use self::step_telemetry::{StepTiming, sample_kv_used_cells}; @@ -395,6 +397,8 @@ struct SchedulerWorker { /// Decode batch cap per pipeline group; equals `max_direct_batch_size` /// unless `SKIPPY_PIPELINE_DECODE_GROUPS` splits waves into groups. direct_group_batch_size: usize, + /// The ceiling on how long a prefill waits for others to join its wave. + prefill_coalesce_max: Duration, max_direct_iteration_tokens: usize, max_commands_per_turn: usize, iteration_interval: Duration, @@ -430,6 +434,7 @@ impl IterationScheduler { ) }; let safe_mode = scheduler_safe_mode_from_value(env::var(SAFE_MODE_ENV).ok().as_deref()); + let prefill_coalesce_max = prefill_coalesce_max(config.prefill_coalesce_max_ms); let pipeline_decode_groups = resolve_pipeline_decode_groups( env::var(PIPELINE_DECODE_GROUPS_ENV).ok().as_deref(), planned_pipeline_decode_groups, @@ -520,6 +525,7 @@ impl IterationScheduler { scheduler_lane_count.max(1), pipeline_decode_groups, ), + prefill_coalesce_max, max_direct_iteration_tokens, max_commands_per_turn: command_queue_capacity.min(MAX_COMMANDS_PER_TURN), iteration_interval, @@ -1204,7 +1210,8 @@ impl SchedulerWorker { self.telemetry.as_ref(), "stage.scheduler_iteration", SpanLevel::Debug, - ); + ) + .with_metrics(); let plan_span = ActiveSpan::start( self.telemetry.as_ref(), "stage.scheduler_plan", diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs index c8233da514..d4d2ee0a92 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs @@ -91,6 +91,7 @@ mod tests { kv_capacity_tokens: 8192, max_direct_batch_size: 4, direct_group_batch_size: 4, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: 32, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs index 1dc7b091dc..ba1a9e711b 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs @@ -51,12 +51,34 @@ impl SchedulerWorker { /// Hold a direct batch open for up to the coalesce window while more /// active sessions may still join it; false once the worker should stop. + /// + /// A batch that holds a prefill waits for a full wave rather than for the + /// sessions already active, and for a window sized to the prompt: the + /// requests that arrive together should prefill together. While it + /// waits, cache operations that would admit another session into the + /// wave run at once instead of taking a turn of their own, so a request + /// that is a few milliseconds behind can still submit its prefill in time. pub(super) fn coalesce_direct_iterations(&mut self) -> bool { - let target = direct_coalesce_target( - self.active_runtime_sessions, - self.direct_iterations.len(), - self.direct_group_batch_size, - ); + let prefill_tokens = self + .direct_iterations + .iter() + .filter(|request| request.phase == IterationBatchPhase::Prefill) + .map(|request| request.token_ids.len()) + .max(); + let (target, window) = match prefill_tokens { + Some(tokens) => ( + self.direct_group_batch_size, + prefill_coalesce_window(tokens, self.prefill_coalesce_max), + ), + None => ( + direct_coalesce_target( + self.active_runtime_sessions, + self.direct_iterations.len(), + self.direct_group_batch_size, + ), + DIRECT_ITERATION_COALESCE_WINDOW, + ), + }; let queued_before = self.direct_iterations.len(); if target <= queued_before { return true; @@ -67,7 +89,7 @@ impl SchedulerWorker { "stage.scheduler_coalesce", SpanLevel::Debug, ); - let deadline = Instant::now() + DIRECT_ITERATION_COALESCE_WINDOW; + let deadline = Instant::now() + window; let mut timed_out = false; let mut running = true; while running && self.direct_iterations.len() < target { @@ -80,7 +102,10 @@ impl SchedulerWorker { self.fail_all(InferenceError::backend("iteration scheduler stopped")); running = false; } - Ok(command) => self.handle_command(command), + Ok(command) => { + self.handle_command(command); + self.admit_into_wave_while_coalescing(); + } Err(std_mpsc::RecvTimeoutError::Timeout) => timed_out = true, Err(std_mpsc::RecvTimeoutError::Disconnected) => running = false, } @@ -93,6 +118,10 @@ impl SchedulerWorker { "skippy.scheduler.coalesce_target".to_string(), json!(target), ), + ( + "skippy.scheduler.coalesce_window_ms".to_string(), + json!(window.as_secs_f64() * 1_000.0), + ), ( "skippy.scheduler.coalesce_queued_before".to_string(), json!(queued_before), @@ -110,6 +139,23 @@ impl SchedulerWorker { running } + /// Run the cache operations that admit sessions into the wave being + /// coalesced, while it still has room. Each is a few hundred + /// microseconds; its request then submits the prefill the wave waits for. + fn admit_into_wave_while_coalescing(&mut self) { + self.refresh_cache_wave_sessions(); + while should_fill_cache_runtime_wave( + true, + self.cache_runtime_queue.has_wave_aware_operations(), + self.cache_wave_sessions, + self.max_direct_batch_size, + ) { + self.cache_runtime_queue.advance_turn(); + self.run_cache_runtime_operation(); + self.refresh_cache_wave_sessions(); + } + } + /// The configured pause between iterations, open to commands; false once /// the worker should stop. pub(super) fn wait_iteration_interval(&mut self) -> bool { diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs index f6d7dc270a..7e9f7e314a 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs @@ -1,6 +1,7 @@ -use super::{DirectIteration, MAX_NATIVE_ITERATION_TOKENS}; +use super::{DIRECT_ITERATION_COALESCE_WINDOW, DirectIteration, MAX_NATIVE_ITERATION_TOKENS}; use skippy_inference_api::{InferenceError, InferenceResult}; use std::collections::{BTreeSet, VecDeque}; +use std::time::Duration; pub(super) fn should_serve_direct( has_direct: bool, @@ -30,6 +31,32 @@ pub(super) fn direct_coalesce_target( .min(max_direct_batch_size) } +/// How long a prefill may wait for company, per prompt token. A prefill +/// costs on the order of a millisecond per token on the runtime, so a few +/// microseconds a token buys the chance that requests arriving together +/// prefill as one wave and start decoding together, instead of one taking +/// the runtime for hundreds of milliseconds while the rest queue behind it. +const PREFILL_COALESCE_PER_TOKEN: Duration = Duration::from_micros(15); +/// The longest a prefill waits unless the stage configures another ceiling. +const PREFILL_COALESCE_WINDOW_MAX: Duration = Duration::from_millis(8); + +/// The ceiling on the prefill coalesce window: the stage's +/// `prefill_coalesce_max_ms`, else the scheduler's own. +pub(super) fn prefill_coalesce_max(configured_ms: Option) -> Duration { + configured_ms.map_or(PREFILL_COALESCE_WINDOW_MAX, |ms| { + Duration::from_millis(u64::from(ms)) + }) +} + +/// The coalesce window for a batch that holds a prefill of `tokens`: a small +/// fraction of the prefill itself, at least the decode window, and never +/// past `max`, which may be shorter than the decode window or zero. +pub(super) fn prefill_coalesce_window(tokens: usize, max: Duration) -> Duration { + (PREFILL_COALESCE_PER_TOKEN * u32::try_from(tokens).unwrap_or(u32::MAX)) + .max(DIRECT_ITERATION_COALESCE_WINDOW) + .min(max) +} + #[cfg(test)] mod coalescing_tests; #[cfg(test)] @@ -165,6 +192,47 @@ pub(super) fn validate_direct_iteration( Ok(()) } +#[cfg(test)] +mod prefill_coalesce_tests { + use super::*; + + #[test] + fn a_long_prompt_waits_the_most_and_a_short_one_the_decode_window() { + let max = prefill_coalesce_max(None); + assert_eq!(max, PREFILL_COALESCE_WINDOW_MAX); + assert_eq!( + prefill_coalesce_window(512, max), + Duration::from_micros(7_680) + ); + assert_eq!(prefill_coalesce_window(4096, max), max); + assert_eq!( + prefill_coalesce_window(9, max), + DIRECT_ITERATION_COALESCE_WINDOW + ); + assert_eq!(prefill_coalesce_window(200, max), Duration::from_millis(3)); + } + + /// The stage's ceiling bounds every window, the decode floor included: + /// zero means a prefill never waits for company. + #[test] + fn a_configured_ceiling_bounds_every_window() { + let max = prefill_coalesce_max(Some(3)); + assert_eq!(prefill_coalesce_window(4096, max), Duration::from_millis(3)); + assert_eq!( + prefill_coalesce_window(9, max), + DIRECT_ITERATION_COALESCE_WINDOW + ); + let never = prefill_coalesce_max(Some(0)); + assert_eq!(prefill_coalesce_window(4096, never), Duration::ZERO); + assert_eq!(prefill_coalesce_window(9, never), Duration::ZERO); + let long = prefill_coalesce_max(Some(50)); + assert_eq!( + prefill_coalesce_window(4096, long), + Duration::from_micros(61_440).min(long) + ); + } +} + #[cfg(test)] mod pipeline_group_tests { use super::*; diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs index c1d94beee1..0770b96a57 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs @@ -14,6 +14,7 @@ fn worker(commands: std_mpsc::Receiver) -> SchedulerWorker { kv_capacity_tokens: 64, max_direct_batch_size: 4, direct_group_batch_size: 4, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, // Leave the sentinel command for coalescing or the next idle turn. max_commands_per_turn: 0, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs index 6b189b4eca..437ba7809b 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs @@ -35,7 +35,8 @@ impl SchedulerWorker { self.telemetry.as_ref(), "stage.scheduler_feature_iteration", SpanLevel::Debug, - ); + ) + .with_metrics(); let entered = span.enter(); let lock_started = Instant::now(); let mut runtime = self.lock_runtime_traced(); diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs index 88eb523ea5..130e649da3 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs @@ -198,6 +198,7 @@ mod tests { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index e73a512950..63e57ee312 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -94,6 +94,7 @@ fn expired_direct_iteration_behind_blocked_worker_never_reaches_native_runtime() kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -267,6 +268,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { kv_capacity_tokens: 64, max_direct_batch_size: 2, direct_group_batch_size: 2, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -376,6 +378,7 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -436,6 +439,7 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -494,6 +498,7 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { kv_capacity_tokens: 64, max_direct_batch_size: 3, direct_group_batch_size: 3, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -541,6 +546,7 @@ fn detached_runtime_operation_returns_before_work_completes() { kv_capacity_tokens: 64, max_direct_batch_size: 3, direct_group_batch_size: 3, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -685,6 +691,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -734,6 +741,7 @@ fn resident_kv_does_not_engage_direct_wave_gate() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -830,6 +838,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -951,6 +960,7 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -1046,6 +1056,7 @@ fn scheduler_worker_keeps_serving_after_an_operation_panics() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -1109,6 +1120,7 @@ fn direct_iterations_in_a_panicking_batch_get_an_error() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, + prefill_coalesce_max: std::time::Duration::from_millis(8), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs index 5a50482a92..40548656c5 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs @@ -295,6 +295,7 @@ mod tests { use std::sync::{Arc, Mutex, atomic::AtomicUsize}; use super::*; + use crate::frontend::generation::LoadedModel; use crate::frontend::admission::GenerationTokenBudget; use crate::frontend::generation::{ GenerationConcurrencyController, InferenceBackendMode, InferenceCacheHints, @@ -423,6 +424,7 @@ mod tests { let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + model: LoadedModel::from_runtime(&runtime), runtime_lane_admission, workload: Default::default(), config: stage_config.clone(), @@ -467,7 +469,6 @@ mod tests { let request = LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 5, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index f8fc605b59..eaf393a3a2 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -10,7 +10,7 @@ use crate::frontend::SpeculativeDecodeConfig; use crate::frontend::admission::GenerationTokenBudget; use crate::frontend::generation::{ GenerationConcurrencyController, InferenceBackendMode, InferenceCacheHints, - InferenceGenerationIds, LocalGeneration, StageOpenAiBackend, TokenControl, + InferenceGenerationIds, LoadedModel, LocalGeneration, StageOpenAiBackend, TokenControl, }; use crate::frontend::iteration_scheduler::IterationScheduler; use crate::frontend::local_generation::{ @@ -196,8 +196,10 @@ fn local_generation_signal_window_uses_configured_value() { IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone()) .unwrap(); let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); + let model = LoadedModel::from_runtime(&runtime); let backend = StageOpenAiBackend { runtime, + model, runtime_lane_admission, workload: Default::default(), config, @@ -299,7 +301,6 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &first_prompt, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 2, sampling: &sampling, chat_sampling_metadata: None, @@ -361,7 +362,6 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &second_prompt, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -696,6 +696,7 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + model: LoadedModel::from_runtime(&runtime), runtime_lane_admission, workload: Default::default(), config, @@ -739,7 +740,6 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -795,7 +795,6 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs index 0f4f69a59f..d617ede612 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs @@ -56,7 +56,6 @@ fn prefill_only_resident_recurrent_request_retains_shared_grid_checkpoint() -> R LocalGeneration { prompt_token_ids: &tokens, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 0, sampling: &sampling, chat_sampling_metadata: None, @@ -137,7 +136,6 @@ fn resident_checkpoint_prefill_yields_to_decode_and_cancels_without_losing_check LocalGeneration { prompt_token_ids: &worker_prompt, recurrent_cache_prefix_token_ids: Some(&worker_prompt[..64]), - shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index 4e6a73fd70..a4a62de004 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -159,7 +159,6 @@ fn failed_long_l3_import_rolls_back_then_reuses_the_short_native_owner() -> Resu LocalGeneration { prompt_token_ids: &prompt, recurrent_cache_prefix_token_ids: None, - shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index af7399838f..301c1a8dee 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -118,6 +118,8 @@ pub(super) fn recurrent_test_backend_with_lanes( min_tokens: 1, shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 0, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: false, load_mode: LoadMode::RuntimeSlice, @@ -156,6 +158,7 @@ pub(super) fn recurrent_test_backend_with_lanes( let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); let backend = StageOpenAiBackend { runtime: runtime.clone(), + model: LoadedModel::from_runtime(&runtime), runtime_lane_admission, workload: Default::default(), config, diff --git a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs index 943c96627e..0dea2d03b6 100644 --- a/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/skippy/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -1295,6 +1295,8 @@ mod tests { min_tokens: 1, shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 1, + prefill_admission: Default::default(), + retention: Default::default(), }), ..Default::default() }; @@ -1383,6 +1385,8 @@ mod tests { min_tokens: 1, shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 1, + prefill_admission: Default::default(), + retention: Default::default(), }), ..Default::default() }; diff --git a/skippy/crates/skippy-serving/src/frontend/prompting.rs b/skippy/crates/skippy-serving/src/frontend/prompting.rs index 199ff69f93..936101eaf8 100644 --- a/skippy/crates/skippy-serving/src/frontend/prompting.rs +++ b/skippy/crates/skippy-serving/src/frontend/prompting.rs @@ -67,10 +67,7 @@ impl StageOpenAiBackend { request: &GenerationRequest, options: ChatTemplateOptions, ) -> InferenceResult { - let marker = { - let runtime = lock_runtime(&self.runtime); - runtime.media_marker() - }; + let marker = self.model.media_marker.clone(); // Native path: render with tools and use the template's own metadata. let native = self.render_chat_prompt(request, &options, &marker, None, true)?; @@ -180,7 +177,7 @@ impl StageOpenAiBackend { // Short-lock reader pattern: clone the immutable reader and run the // template FFI on it, so template rendering never waits behind // decode's hold of the runtime mutex (and vice versa). - let reader = lock_runtime(&self.runtime).model.reader(); + let reader = self.model_reader(); let result = reader .apply_chat_template_json( &messages_json, @@ -219,7 +216,7 @@ impl StageOpenAiBackend { let Some(metadata) = metadata else { return Ok(None); }; - let model = lock_runtime(&self.runtime).model.reader(); + let model = self.model_reader(); self.parse_chat_output_with_reader(&model, text, request, metadata, is_partial) } @@ -275,12 +272,18 @@ impl StageOpenAiBackend { // reader; the tokenizer FFI runs on the reader, so decode can hold // the runtime lock concurrently without serializing tokenization // behind it (see render_chat_prompt for the same pattern). - let reader = lock_runtime(&self.runtime).model.reader(); + let reader = self.model_reader(); reader .tokenize(text, add_special) .map_err(openai_backend_error) } + /// The immutable model: no runtime lock, so a request renders its template + /// and tokenizes while a native batch runs. + pub(in crate::frontend) fn model_reader(&self) -> skippy_runtime::StageModelReader { + self.model.reader.clone() + } + pub(super) fn inject_hook_text_into_session( &self, session_id: &str, diff --git a/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs b/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs index 7332a76220..d9247b1699 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/multimodal.rs @@ -656,11 +656,13 @@ async fn real_multimodal_split_smoke_when_fixture_is_set() -> Result<()> { telemetry.clone(), )?; let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); + let model = LoadedModel::from_runtime(&runtime); let backend = StageOpenAiBackend { runtime_lane_admission, speculation_governor: None, runahead_governor: None, runtime, + model, workload: Default::default(), telemetry, config: stage0_config.clone(), diff --git a/skippy/crates/skippy-serving/src/frontend/tests/support.rs b/skippy/crates/skippy-serving/src/frontend/tests/support.rs index f75696369c..66d5a0087d 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/support.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/support.rs @@ -53,6 +53,8 @@ pub(super) fn prefix_cache_test_config() -> StageConfig { min_tokens: 256, shared_prefix_stride_tokens: 128, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: true, load_mode: LoadMode::RuntimeSlice, @@ -137,8 +139,10 @@ pub(super) fn local_openai_backend( let iteration_scheduler = IterationScheduler::new(runtime.clone(), &config, 1, true, None, telemetry.clone())?; let runtime_lane_admission = runtime.lock().unwrap().lane_admission(); + let model = LoadedModel::from_runtime(&runtime); Ok(StageOpenAiBackend { runtime, + model, runtime_lane_admission, workload: Default::default(), telemetry, diff --git a/skippy/crates/skippy-serving/src/kv_integration/activation.rs b/skippy/crates/skippy-serving/src/kv_integration/activation.rs index c7d3951dbf..6e315545ca 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/activation.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/activation.rs @@ -217,6 +217,8 @@ mod tests { min_tokens: 256, shared_prefix_stride_tokens: 128, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: true, load_mode: LoadMode::RuntimeSlice, diff --git a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs index 6a75e53da7..6a8331b38c 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -114,6 +114,8 @@ mod tests { min_tokens: 64, shared_prefix_stride_tokens: 32, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: true, load_mode: LoadMode::RuntimeSlice, @@ -173,6 +175,8 @@ mod checkpoint_matching_tests { min_tokens: 1, shared_prefix_stride_tokens: 128, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), ..StageConfig::default() }; diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 245db5f63d..c73c63d2a9 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -189,6 +189,12 @@ impl KvStageIntegration { cache_config.max_entries = cache_config.max_entries.min(RECURRENT_CACHE_MAX_ENTRIES); } let mut checkpoint_policy = SparseCheckpointPolicy::from_cache(&cache_config); + let prefill_admission = super::scheduling::resolve_prefill_admission( + std::env::var(super::scheduling::PREFILL_ADMISSION_ENV) + .ok() + .as_deref(), + cache_config.prefill_admission, + ); let resident_checkpoint_max_bytes = resident_policy::checkpoint_budget(&cache_config); let activation_config = ResidentCacheConfig::from_stage(config, &cache_config); let mut resident_config = activation_config; @@ -363,8 +369,10 @@ impl KvStageIntegration { correctness_mode: false, trust_local_writes: true, checkpoint_policy, + prefill_admission, inflight_records, resident_config, + retention: cache_config.retention, resident_capacity_reservations: Default::default(), resident_sequences: Arc::new(Mutex::new(ResidentSequencePool::new( resident_config.reserved_seq_count, @@ -992,6 +1000,8 @@ pub(super) fn effective_cache_config(config: &StageConfig) -> Option (KvStageIntegration, PrefillKvIdentity) { codec: Default::default(), shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 0, + prefill_admission: Default::default(), + retention: Default::default(), }), ..StageConfig::default() }; diff --git a/skippy/crates/skippy-serving/src/kv_integration/identity.rs b/skippy/crates/skippy-serving/src/kv_integration/identity.rs index 6083781c8d..675c835952 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/identity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/identity.rs @@ -265,6 +265,8 @@ mod tests { min_tokens: 64, shared_prefix_stride_tokens: 32, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), native_mtp_enabled: true, load_mode: LoadMode::RuntimeSlice, diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 901ccc9a99..1190ea75b8 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -16,6 +16,7 @@ use skippy_cache::{ SparseCheckpointPolicy, UnifiedRadixCache, }; use skippy_metrics::attr as attr_key; +use skippy_protocol::StageKvRetention; use skippy_runtime::{ActivationFrame, MemoryCacheCapabilities, ModelStateKind, RuntimeKvPageDesc}; use crate::kv_proto::{ @@ -176,8 +177,11 @@ pub struct KvStageIntegration { pub(crate) correctness_mode: bool, pub(crate) trust_local_writes: bool, pub(crate) checkpoint_policy: SparseCheckpointPolicy, + pub(crate) prefill_admission: scheduling::CacheSchedulingPolicy, pub(crate) inflight_records: Arc>>, pub(crate) resident_config: ResidentCacheConfig, + /// What finished requests may keep resident beyond the active sessions. + pub(crate) retention: StageKvRetention, pub(crate) resident_capacity_reservations: resident_prefix::ResidentCapacityReservations, pub(crate) resident_sequences: Arc>, pub(crate) activations: Arc>>, diff --git a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs index c385ad8822..259b8079a4 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -4,6 +4,7 @@ mod selection; use recording::resident_index_over_capacity; use anyhow::{Context, Result}; +use skippy_protocol::StageKvRetention; use skippy_scheduler::{ CapacityDemand, ComponentCapacitySnapshot, EvictableCacheEntry, plan_component_capacity, rank_eviction_candidates, @@ -238,9 +239,21 @@ impl KvStageIntegration { } .max(minimum_free) .min(capacity_tokens); + // Retention beyond the budget is evicted even when the pool has room: + // the budget bounds what finished requests keep, not what this one may + // use, so admission itself is still judged against the whole pool. + let eviction_capacity = match self.retention { + StageKvRetention::Unbounded => capacity_tokens, + StageKvRetention::Tokens(budget) => capacity_tokens.min( + active_tokens + .saturating_add(request_tokens) + .saturating_add(target_free) + .saturating_add(budget), + ), + }; let required_eviction_tokens = occupied_after_request .saturating_add(target_free) - .saturating_sub(capacity_tokens); + .saturating_sub(eviction_capacity); let mut ranked = candidates .iter() .filter(|candidate| Some(candidate.value.seq_id) != protected_seq_id) @@ -272,7 +285,7 @@ impl KvStageIntegration { if used_tokens .saturating_add(request_tokens) .saturating_add(target_free) - <= capacity_tokens + <= eviction_capacity { break; } @@ -684,6 +697,8 @@ mod proactive_eviction_tests { min_tokens: 1, shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 1, + prefill_admission: Default::default(), + retention: Default::default(), }), ..StageConfig::default() }; @@ -741,6 +756,90 @@ mod proactive_eviction_tests { ); } + /// A pool with room still sheds retention over the budget; what it keeps + /// is the budget, and the request is admitted against the whole pool. + #[test] + fn retention_over_budget_is_evicted_while_the_pool_has_room() { + let config = StageConfig { + ctx_size: 1000, + lane_count: 1, + kv_cache: Some(StageKvCacheConfig { + exact_max_bytes: None, + mode: StageKvCacheMode::LookupRecord, + max_entries: 4, + max_bytes: 0, + l2_max_bytes: 0, + codec: skippy_protocol::StageKvCacheCodec::Native, + min_tokens: 1, + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 1, + prefill_admission: Default::default(), + retention: Default::default(), + }), + ..StageConfig::default() + }; + let mut integration = KvStageIntegration::from_loaded_model( + &config, + Some(ModelStateKind::Dense), + Some(skippy_runtime::MemoryCacheCapabilities { + resident_attention: true, + resident_checkpoint: false, + resident: true, + kv_recurrent: true, + full_state: true, + }), + None, + ) + .unwrap() + .expect("resident cache should be enabled"); + integration.retention = StageKvRetention::Tokens(10); + let mut sequences = lock_resident_sequences(&integration.resident_sequences); + let mut radix = integration.radix.lock().unwrap(); + for (index, tokens) in [8_u64, 8, 8].into_iter().enumerate() { + let seq_id = sequences.allocate().unwrap(); + let ids = (0..tokens) + .map(|t| t as i32 + 100 * index as i32) + .collect::>(); + radix + .insert_resident( + "stage", + &ids, + tokens, + RadixResidentEntry { + page_id: format!("page-{index}"), + seq_id, + token_count: tokens, + recompute_cost: tokens, + }, + ) + .unwrap(); + } + drop(radix); + drop(sequences); + + let mut runtime = + crate::runtime_state::RuntimeState::new_modelless_with_capacity_for_test(1, 1000); + let decision = integration + .admit_resident_capacity(&mut runtime, "session", 5, 0, 0, None) + .unwrap(); + + assert!(decision.admitted, "the pool itself had room"); + assert_eq!( + decision.evicted_entries, 2, + "24 retained over a budget of 10 sheds two" + ); + assert_eq!(decision.evicted_tokens, 16); + + integration.retention = StageKvRetention::Unbounded; + let decision = integration + .admit_resident_capacity(&mut runtime, "session", 5, 0, 0, None) + .unwrap(); + assert_eq!( + decision.evicted_entries, 0, + "no budget means the pool is the bound" + ); + } + #[test] fn native_drop_failure_preserves_the_radix_entry_and_sequence_id() { let mut radix = skippy_cache::UnifiedRadixCache::new(); diff --git a/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs index ab08223888..86888a3788 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/scheduling.rs @@ -1,10 +1,24 @@ -//! Scheduling follows the loaded state contract, independently of storage tiers. +//! Prompt admission: who prefills a prompt once its prefix is looked up. +//! +//! The policy is configuration (`kv_cache.prefill_admission`), independent of +//! the model's state kind and of storage tiers. `SKIPPY_PREFILL_ADMISSION` +//! overrides it for a bench or an incident without a replan, the same shape +//! as `SKIPPY_KV_CACHE`. use super::KvStageIntegration; +use skippy_protocol::StagePrefillAdmission; +pub(crate) const PREFILL_ADMISSION_ENV: &str = "SKIPPY_PREFILL_ADMISSION"; + +// The internal default stays Serialized: it is what a cache operation without a +// configured policy (no kv integration, lazy queue entries) assumes. The configured +// default lives in `StagePrefillAdmission`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum CacheSchedulingPolicy { + /// The cache operation prefills the whole prompt under the runtime lock. #[default] Serialized, + /// The cache operation restores the prefix; the suffix runs as iteration + /// batches beside other requests' chunks and decode rows. Cooperative, } @@ -14,13 +28,34 @@ impl CacheSchedulingPolicy { } } +impl From for CacheSchedulingPolicy { + fn from(admission: StagePrefillAdmission) -> Self { + match admission { + StagePrefillAdmission::Serialized => Self::Serialized, + StagePrefillAdmission::Cooperative => Self::Cooperative, + } + } +} + +pub(crate) fn prefill_admission_from_value(value: Option<&str>) -> Option { + match value?.trim().to_ascii_lowercase().as_str() { + "serialized" => Some(CacheSchedulingPolicy::Serialized), + "cooperative" => Some(CacheSchedulingPolicy::Cooperative), + _ => None, + } +} + +/// The environment override wins when it parses; otherwise the configured policy. +pub(crate) fn resolve_prefill_admission( + env_value: Option<&str>, + configured: StagePrefillAdmission, +) -> CacheSchedulingPolicy { + prefill_admission_from_value(env_value).unwrap_or_else(|| configured.into()) +} + impl KvStageIntegration { pub(crate) fn scheduling_policy(&self) -> CacheSchedulingPolicy { - if self.retains_recurrent_checkpoints() { - CacheSchedulingPolicy::Cooperative - } else { - CacheSchedulingPolicy::Serialized - } + self.prefill_admission } } @@ -30,41 +65,81 @@ mod tests { use skippy_protocol::{StageConfig, StageKvCacheConfig, StageKvCacheMode}; use skippy_runtime::{MemoryCacheCapabilities, ModelStateKind}; + fn integration(admission: StagePrefillAdmission, checkpoint: bool) -> KvStageIntegration { + let config = StageConfig { + kv_cache: Some(StageKvCacheConfig { + mode: StageKvCacheMode::LookupRecord, + min_tokens: 1, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 1024, + exact_max_bytes: None, + codec: Default::default(), + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + prefill_admission: admission, + retention: Default::default(), + }), + ..StageConfig::default() + }; + KvStageIntegration::from_test_model_with_l3_manager( + &config, + Some(ModelStateKind::Dense), + Some(MemoryCacheCapabilities { + resident: true, + resident_checkpoint: checkpoint, + resident_attention: true, + kv_recurrent: true, + full_state: true, + }), + None, + None, + ) + .unwrap() + .unwrap() + } + #[test] - fn loaded_checkpoint_memory_is_cooperative_without_disk_or_family_labels() { + fn admission_follows_configuration_not_checkpoint_retention() { for checkpoint in [false, true] { - let config = StageConfig { - kv_cache: Some(StageKvCacheConfig { - mode: StageKvCacheMode::LookupRecord, - min_tokens: 1, - max_entries: 8, - max_bytes: 0, - l2_max_bytes: 1024, - exact_max_bytes: None, - codec: Default::default(), - shared_prefix_stride_tokens: 1, - shared_prefix_record_limit: 0, - }), - ..StageConfig::default() - }; - let kv = KvStageIntegration::from_test_model_with_l3_manager( - &config, - Some(ModelStateKind::Dense), - Some(MemoryCacheCapabilities { - resident: true, - resident_checkpoint: checkpoint, - resident_attention: true, - kv_recurrent: true, - full_state: true, - }), - None, - None, - ) - .unwrap() - .unwrap(); - assert!(kv.l3.is_none()); - assert!(kv.durable_payload.is_none()); - assert_eq!(kv.scheduling_policy().cooperative(), checkpoint); + let cooperative = integration(StagePrefillAdmission::Cooperative, checkpoint); + assert!(cooperative.l3.is_none()); + assert!(cooperative.durable_payload.is_none()); + assert!(cooperative.scheduling_policy().cooperative()); + assert!( + !integration(StagePrefillAdmission::Serialized, checkpoint) + .scheduling_policy() + .cooperative() + ); } } + + #[test] + fn cooperative_is_the_default() { + assert_eq!( + CacheSchedulingPolicy::from(StagePrefillAdmission::default()), + CacheSchedulingPolicy::Cooperative + ); + } + + #[test] + fn environment_override_parses_or_yields_to_configuration() { + assert_eq!( + resolve_prefill_admission(Some(" Serialized "), StagePrefillAdmission::Cooperative), + CacheSchedulingPolicy::Serialized + ); + assert_eq!( + resolve_prefill_admission(Some("cooperative"), StagePrefillAdmission::Serialized), + CacheSchedulingPolicy::Cooperative + ); + assert_eq!( + resolve_prefill_admission(Some("sometimes"), StagePrefillAdmission::Serialized), + CacheSchedulingPolicy::Serialized + ); + assert_eq!( + resolve_prefill_admission(None, StagePrefillAdmission::Serialized), + CacheSchedulingPolicy::Serialized + ); + assert_eq!(prefill_admission_from_value(None), None); + } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/snapshot_validation.rs b/skippy/crates/skippy-serving/src/kv_integration/snapshot_validation.rs index 35d0f08889..202d91696e 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/snapshot_validation.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/snapshot_validation.rs @@ -68,6 +68,8 @@ mod tests { min_tokens: 1, shared_prefix_stride_tokens: 128, shared_prefix_record_limit: 2, + prefill_admission: Default::default(), + retention: Default::default(), }), ..Default::default() }; diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index 8f2e7a2df1..465bde75c5 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -434,7 +434,10 @@ fn runtime_from_loaded_model( reject_unsupported_staged_workload(config, &model)?; let lane_count = effective_lane_count(config.lane_count, &model)?; let context_capacity = - ContextCapacity::for_loaded_model(config.ctx_size, lane_count, model.has_native_model())?; + ContextCapacity::for_loaded_model(config.ctx_size, model.kv_pool_cells())?; + crate::telemetry::resource_metrics::record_kv_pool_cells(u64::from( + context_capacity.pool_tokens(), + )); Ok(Arc::new(Mutex::new(RuntimeState { model, runtime_lane_admission: lane_admission::RuntimeLaneAdmission::new(lane_count), @@ -612,6 +615,10 @@ pub(crate) fn runtime_config_from_stage_config( kv_offload: config.kv_offload, kv_unified: config.kv_unified, swa_full: config.swa_full, + kv_pool_tokens: config.kv_pool_tokens, + kv_lazy_clear: config.kv_lazy_clear, + kv_release_pages: config.kv_release_pages, + kv_row_attention: config.kv_row_attention, projector_path: config.projector_path.clone(), projector_use_gpu: config.projector_use_gpu, media_marker: config.media_marker.clone(), diff --git a/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs b/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs index a5a2b2b821..d050cfab64 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/context_capacity.rs @@ -1,6 +1,6 @@ //! Context limits admitted by the loaded native workload. -use anyhow::{Context, Result}; +use anyhow::{Result, ensure}; use skippy_runtime::{ModelWorkload, StageModel}; use super::RuntimeState; @@ -12,32 +12,36 @@ pub(super) struct ContextCapacity { } impl ContextCapacity { - /// Mirror `skippy_context_capacity`: native ctx_size is per execution lane. - /// This runs only after model open has admitted the corresponding config. + /// Native ctx_size is per execution lane; the pool is whatever native + /// allocated for all of them (`StageModel::kv_pool_cells`), which a pool + /// cap may hold below ctx_size × lanes. This runs only after model open + /// has admitted the corresponding config. pub(super) fn for_loaded_model( configured_tokens: u32, - effective_lanes: u32, - has_native_model: bool, + native_pool_cells: Option, ) -> Result { - if !has_native_model { + let Some(pool_tokens) = native_pool_cells else { return Ok(Self::modelless(configured_tokens)); - } + }; let per_lane_tokens = if configured_tokens == 0 { 512 } else { configured_tokens }; - let pool_tokens = per_lane_tokens - .checked_mul(effective_lanes.max(1)) - .context( - "ctx_size multiplied by admitted lane_count exceeds the native context range", - )?; + ensure!( + pool_tokens >= per_lane_tokens, + "native KV pool of {pool_tokens} cells cannot hold one lane of {per_lane_tokens}" + ); Ok(Self { per_lane_tokens, pool_tokens, }) } + pub(super) const fn pool_tokens(self) -> u32 { + self.pool_tokens + } + /// Modelless fixtures supply an aggregate pool directly, without native /// per-lane allocation or native defaults. pub(super) const fn modelless(pool_tokens: u32) -> Self { @@ -88,7 +92,7 @@ mod tests { #[test] fn native_pool_includes_every_lane_without_enlarging_request_history() { - let capacity = ContextCapacity::for_loaded_model(131_072, 4, true).unwrap(); + let capacity = ContextCapacity::for_loaded_model(131_072, Some(524_288)).unwrap(); let mut runtime = RuntimeState::new_modelless_for_test(4); runtime.context_capacity = capacity; assert_eq!(runtime.kv_pool_tokens(), 524_288); @@ -124,6 +128,8 @@ mod tests { min_tokens: 1, shared_prefix_stride_tokens: 1, shared_prefix_record_limit: 1, + prefill_admission: Default::default(), + retention: Default::default(), }), ..Default::default() }; @@ -142,7 +148,8 @@ mod tests { .unwrap() .unwrap(); let mut runtime = RuntimeState::new_modelless_for_test(4); - runtime.context_capacity = ContextCapacity::for_loaded_model(131_072, 4, true).unwrap(); + runtime.context_capacity = + ContextCapacity::for_loaded_model(131_072, Some(524_288)).unwrap(); let _reservations = (0..4) .map(|lane| { cache @@ -167,23 +174,30 @@ mod tests { assert_eq!(understated.admission_deficit_tokens, 244_928); } + /// The pool is native's answer, not ctx_size times lanes: a capped pool + /// stays below that product while every lane keeps its window. #[test] - fn native_pool_uses_effective_workload_lanes_and_native_defaults() { - let lanes = lane_count_for_workload(4, ModelWorkload::EncoderDecoder); - let capacity = ContextCapacity::for_loaded_model(2048, lanes, true).unwrap(); + fn native_pool_is_taken_as_reported_and_lanes_keep_their_window() { + let capacity = ContextCapacity::for_loaded_model(2048, Some(2048)).unwrap(); assert_eq!(capacity.pool_tokens, 2048); assert_eq!(capacity.per_lane_tokens, 2048); - let capacity = ContextCapacity::for_loaded_model(0, 0, true).unwrap(); - assert_eq!(capacity.pool_tokens, 512); + let capacity = ContextCapacity::for_loaded_model(8192, Some(32_768)).unwrap(); + assert_eq!(capacity.pool_tokens, 32_768); + assert_eq!(capacity.per_lane_tokens, 8192); + let capacity = ContextCapacity::for_loaded_model(0, Some(512)).unwrap(); + assert_eq!(capacity.per_lane_tokens, 512); + assert_eq!(lane_count_for_workload(4, ModelWorkload::EncoderDecoder), 1); assert_eq!( lane_count_for_workload(0, ModelWorkload::CausalGeneration), 1 ); } + /// A pool that cannot hold one lane's window is a configuration error, + /// not a capacity to admit against. #[test] - fn native_pool_rejects_overflow_instead_of_understating_capacity() { - assert!(ContextCapacity::for_loaded_model(u32::MAX, 2, true).is_err()); + fn native_pool_smaller_than_a_lane_is_rejected() { + assert!(ContextCapacity::for_loaded_model(8192, Some(4096)).is_err()); } #[test] @@ -191,7 +205,7 @@ mod tests { for tokens in [0, 131_072] { let runtime = RuntimeState::new_modelless_with_capacity_for_test(4, tokens); assert_eq!(runtime.kv_pool_tokens(), tokens); - let capacity = ContextCapacity::for_loaded_model(tokens, 4, false).unwrap(); + let capacity = ContextCapacity::for_loaded_model(tokens, None).unwrap(); assert_eq!(capacity.pool_tokens, tokens); } } diff --git a/skippy/crates/skippy-serving/src/telemetry.rs b/skippy/crates/skippy-serving/src/telemetry.rs index 62dd43b26a..7a6e65f12e 100644 --- a/skippy/crates/skippy-serving/src/telemetry.rs +++ b/skippy/crates/skippy-serving/src/telemetry.rs @@ -1,52 +1,63 @@ #[cfg(test)] use std::sync::mpsc as std_mpsc; use std::{ - collections::{BTreeMap, VecDeque}, + collections::BTreeMap, sync::{ Arc, atomic::{AtomicU64, Ordering}, }, - thread, - time::{Duration, Instant, SystemTime, UNIX_EPOCH}, + time::{Duration, SystemTime, UNIX_EPOCH}, }; -use opentelemetry_proto::tonic::collector::trace::v1::{ - ExportTraceServiceRequest, trace_service_client::TraceServiceClient, -}; +use opentelemetry_proto::tonic::metrics::v1::Metric; use serde::Serialize; use serde_json::{Value, json}; use skippy_metrics::{attr, metric}; use skippy_protocol::StageConfig; -use tokio::{ - sync::mpsc, - time::{sleep, timeout}, -}; pub(crate) mod active_span; mod gpu_commands; pub(crate) mod log_events; mod native_calls; mod native_spans; +mod otlp_collector; mod otlp_encoding; mod otlp_file; mod resource_attrs; pub(crate) mod resource_metrics; mod resource_usage; +pub(crate) mod sink; mod span_components; mod stderr_sink; pub(crate) mod trace_context; +#[cfg(feature = "tracy")] +mod tracy_sink; -use otlp_encoding::{event_to_span, resource_spans_by_component}; -use stderr_sink::{StderrTelemetryEvent, StderrTelemetrySink, stderr_sink_enabled}; +#[cfg(test)] +pub(crate) use sink::CapturedEvent; +use sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}; use trace_context::{Frame, SpanContext, SpanEvent}; /// How long shutdown waits for queued spans to reach their sinks. const FLUSH_TIMEOUT: Duration = Duration::from_secs(5); /// Bound on delivering a span that ends after the process span. const LATE_SPAN_FLUSH_TIMEOUT: Duration = Duration::from_millis(500); +/// Spans per exported request, for the collector and the file alike. +const EXPORT_BATCH_MAX: usize = 128; + +/// The Tracy sink, when this build carries it and the environment asks. +#[cfg(feature = "tracy")] +fn tracy_sink() -> Option> { + tracy_sink::TracySink::enabled().map(|sink| Box::new(sink) as Box) +} -/// A local debug sink (stderr or OTLP file) acts as a floor on the configured -/// level. +#[cfg(not(feature = "tracy"))] +fn tracy_sink() -> Option> { + None +} + +/// A local debug sink (stderr, OTLP file or Tracy) acts as a floor on the +/// configured level. /// /// It never lowers an explicitly configured level, so a collector-backed /// `Summary` deployment is unaffected by the variable being set. @@ -57,37 +68,16 @@ fn effective_level(configured: TelemetryLevel, local_sink: bool) -> TelemetryLev configured } } -const EXPORT_TIMEOUT: Duration = Duration::from_secs(10); -const EXPORT_BATCH_MAX: usize = 128; -const RETRY_BUFFER_CAPACITY: usize = 8192; -const RETRY_BACKOFF: Duration = Duration::from_millis(100); +/// What happened in this stage, told to every sink as it happens. Spans +/// begin and end here; what each sink makes of them is its own business +/// (see [`sink::TraceSink`]). #[derive(Clone)] pub struct Telemetry { - tx: Option>, - stderr: Option>, - otlp_file: Option<&'static otlp_file::OtlpFileSink>, + sinks: Arc<[Box]>, stats: Arc, config: Arc, level: TelemetryLevel, - /// Test-only in-process capture channel; `None` in production. Sibling - /// tests receive events here instead of the private stderr sink, so - /// `StderrTelemetryEvent` and its fields stay module-private. - #[cfg(test)] - capture: Option>, -} - -/// Test-only emission shape handed to sibling-module tests. Mirrors -/// `StderrTelemetryEvent` without exposing the production struct or its -/// fields beyond this module. -#[cfg(test)] -pub(crate) struct CapturedEvent { - pub event: String, - pub attributes: BTreeMap, - pub start_time_unix_nanos: u64, - pub end_time_unix_nanos: u64, - /// The exported span's identity and parent; `None` for a point event. - pub span: Option<(SpanContext, Option<[u8; 8]>)>, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -98,11 +88,11 @@ pub enum TelemetryLevel { } #[derive(Default)] -struct TelemetryCounters { - queued: AtomicU64, - sent: AtomicU64, - dropped: AtomicU64, - export_errors: AtomicU64, +pub(crate) struct TelemetryCounters { + pub(crate) queued: AtomicU64, + pub(crate) sent: AtomicU64, + pub(crate) dropped: AtomicU64, + pub(crate) export_errors: AtomicU64, } #[derive(Clone, Debug, Serialize)] @@ -113,39 +103,8 @@ pub struct TelemetryStats { pub export_errors: u64, } -/// One finished span, placed in the process trace. -#[derive(Clone)] -struct TelemetryEvent { - context: SpanContext, - parent: Option<[u8; 8]>, - name: String, - attributes: BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, - links: Vec, - events: Vec, -} - -impl TelemetryEvent { - fn span( - frame: &Frame, - name: &str, - attributes: BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, - ) -> Self { - Self { - context: frame.context(), - parent: frame.parent_span_id(), - name: name.to_string(), - attributes, - start_time_unix_nanos, - end_time_unix_nanos: end_time_unix_nanos.max(start_time_unix_nanos.saturating_add(1)), - links: Vec::new(), - events: Vec::new(), - } - } -} +/// What every sink keeps for one live span, in sink order. +pub(crate) struct OpenSpans(Vec); impl Telemetry { pub fn new( @@ -161,48 +120,138 @@ impl Telemetry { // single-process case it exists for. Honour it as a level floor, and // the existing level checks then work unchanged. The OTLP file sink // is the same kind of local opt-in. - let otlp_file = otlp_file::configured(); - let level = effective_level(level, stderr_sink_enabled() || otlp_file.is_some()); let stats = Arc::new(TelemetryCounters::default()); let config = Arc::new(config); + let file = otlp_file::OtlpFileTraceSink::configured(config.clone(), stats.clone()); + let tracy = tracy_sink(); + let level = effective_level( + level, + stderr_sink::stderr_sink_enabled() || file.is_some() || tracy.is_some(), + ); let metrics_endpoint = endpoint.clone(); - let tx = (level != TelemetryLevel::Off) + let collector = (level != TelemetryLevel::Off) .then_some(endpoint) .flatten() .map(|endpoint| { - let (tx, rx) = mpsc::channel(capacity); - tokio::spawn(telemetry_export_loop( + otlp_collector::OtlpCollectorSink::start( endpoint, - rx, + capacity, stats.clone(), config.clone(), - )); - tx + ) }); - - let telemetry = Self { - tx, - stderr: stderr_sink_enabled() - .then(|| StderrTelemetrySink::new(capacity)) - .flatten() - .map(Arc::new), - otlp_file, - stats, - config, - level, - #[cfg(test)] - capture: None, - }; + let stderr = stderr_sink::StderrTraceSink::enabled(capacity, stats.clone()); + // Samples are debug telemetry: they go to the metrics file and the + // collector's metrics service, and to any sink that plots them. + let metrics = (level == TelemetryLevel::Debug) + .then(|| { + resource_metrics::OtlpMetricsSink::configured( + config.clone(), + std::env::var_os(resource_metrics::METRICS_FILE_ENV) + .filter(|path| !path.is_empty()), + metrics_endpoint.as_deref(), + ) + }) + .flatten(); + let sinks: Vec> = [ + collector.map(|sink| Box::new(sink) as Box), + stderr.map(|sink| Box::new(sink) as Box), + file.map(|sink| Box::new(sink) as Box), + metrics.map(|sink| Box::new(sink) as Box), + tracy, + ] + .into_iter() + .flatten() + .collect(); + let telemetry = Self::with_sinks(sinks, stats, config, level); log_events::start(&telemetry, metrics_endpoint.as_deref()); if telemetry.is_debug_enabled() && telemetry.has_sink() { native_calls::install(&telemetry); - resource_metrics::start(&telemetry, metrics_endpoint.as_deref()); + resource_metrics::start(&telemetry); } telemetry } + fn with_sinks( + sinks: Vec>, + stats: Arc, + config: Arc, + level: TelemetryLevel, + ) -> Self { + Self { + sinks: sinks.into(), + stats, + config, + level, + } + } + fn has_sink(&self) -> bool { - self.tx.is_some() || self.stderr.is_some() || self.otlp_file.is_some() + !self.sinks.is_empty() + } + + /// Whether some sink wants events inside their span's record. + fn has_trace_sink(&self) -> bool { + self.sinks.iter().any(|sink| sink.folds_events_into_spans()) + } + + /// Whether process samples are worth taking: debug telemetry with a sink. + pub(crate) fn records_metrics(&self) -> bool { + self.level == TelemetryLevel::Debug && self.has_sink() + } + + /// One process sample, to every sink. + pub(crate) fn record_metrics(&self, metrics: &[Metric]) { + self.sinks + .iter() + .for_each(|sink| sink.record_metrics(metrics)); + } + + /// A live span begins now on this thread; `end_span` takes what comes back. + pub(crate) fn begin_span(&self, span: &SpanStart) -> OpenSpans { + OpenSpans( + self.sinks + .iter() + .map(|sink| sink.create_span_with(span)) + .collect(), + ) + } + + /// The live span `begin_span` saw ends: export it with its frame's events. + pub(crate) fn end_span( + &self, + open: OpenSpans, + frame: &Frame, + name: &str, + mut attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + links: Vec, + ) { + let events = frame.take_events(); + self.add_common_attributes(&mut attributes); + let mut record = SpanRecord::of_frame( + frame, + name, + attributes, + start_time_unix_nanos, + end_time_unix_nanos, + ); + record.links = links; + record.events = events; + self.sinks + .iter() + .zip(open.0) + .for_each(|(sink, open)| sink.end_span(open, &record)); + self.after_delivery(); + } + + /// The live span `begin_span` saw is not kept. + pub(crate) fn discard_span(&self, open: OpenSpans) { + self.sinks + .iter() + .zip(open.0) + .for_each(|(sink, open)| sink.discard_span(open)); } /// A point event. Trace sinks record it as an event on the active span; @@ -212,32 +261,40 @@ impl Telemetry { return; } self.add_common_attributes(&mut attributes); - let now = now_unix_nanos() as u64; - #[cfg(test)] - if self.capture(name, &attributes, now, now + 1, None) { - return; - } - self.send_stderr(name, &attributes, now, now + 1); let frame = trace_context::current_frame_or_root(); log_events::record_point_event(&frame, name, &attributes); + self.record_event_on( + &frame, + SpanEvent { + name: name.to_string(), + time_unix_nanos: now_unix_nanos() as u64, + attributes, + }, + ); + } + + /// Tell every sink about `event` as it happens, then fold it into + /// `frame`'s span for the sinks that read events there. When that span + /// already ended or is full, they get it as an instant span beneath it. + pub(crate) fn record_event_on(&self, frame: &Frame, event: SpanEvent) { + self.sinks + .iter() + .for_each(|sink| sink.record_event(&event, frame)); if !self.has_trace_sink() { return; } - let event = SpanEvent { - name: name.to_string(), - time_unix_nanos: now, - attributes, - }; if let Err(event) = frame.record_event(event) { - // The active span already ended or is full: keep the event as an - // instant span beneath it instead of losing it. - self.export(TelemetryEvent::span( + let record = SpanRecord::of_frame( &Frame::child(), &event.name, event.attributes, - now, - now + 1, - )); + event.time_unix_nanos, + event.time_unix_nanos + 1, + ); + self.sinks + .iter() + .filter(|sink| sink.folds_events_into_spans()) + .for_each(|sink| sink.record_span(&record)); } } @@ -253,7 +310,7 @@ impl Telemetry { return; } self.add_common_attributes(&mut attributes); - self.deliver(TelemetryEvent::span( + self.deliver(SpanRecord::of_frame( &Frame::child(), name, attributes, @@ -277,7 +334,7 @@ impl Telemetry { return; } self.add_common_attributes(&mut attributes); - let mut record = TelemetryEvent::span( + let mut record = SpanRecord::of_frame( frame, name, attributes, @@ -337,22 +394,9 @@ impl Telemetry { self.flush(FLUSH_TIMEOUT); } - /// Wait, bounded by `timeout`, for queued spans to reach their sinks. + /// Wait, bounded by `timeout` per sink, for queued spans to leave. fn flush(&self, timeout: Duration) { - let deadline = Instant::now() + timeout; - if let Some(file) = self.otlp_file { - file.flush(timeout); - } - if self.tx.is_some() { - without_starving_runtime(|| { - while self.stats.sent.load(Ordering::Relaxed) - < self.stats.queued.load(Ordering::Relaxed) - && Instant::now() < deadline - { - thread::sleep(Duration::from_millis(20)); - } - }); - } + self.sinks.iter().for_each(|sink| sink.flush(timeout)); } fn add_common_attributes(&self, attributes: &mut BTreeMap) { @@ -372,99 +416,20 @@ impl Telemetry { ); } - fn deliver(&self, record: TelemetryEvent) { - #[cfg(test)] - if self.capture( - &record.name, - &record.attributes, - record.start_time_unix_nanos, - record.end_time_unix_nanos, - Some((record.context, record.parent)), - ) { - return; - } - self.send_stderr( - &record.name, - &record.attributes, - record.start_time_unix_nanos, - record.end_time_unix_nanos, - ); - self.export(record); - // Components that stop after the process span (the scheduler worker, - // say) end their spans during exit; deliver each one immediately - // because the process will not wait for the exporters. - if trace_context::process().is_finished() { - self.flush(LATE_SPAN_FLUSH_TIMEOUT); - } - } - - fn has_trace_sink(&self) -> bool { - self.tx.is_some() || self.otlp_file.is_some() + fn deliver(&self, record: SpanRecord) { + self.sinks.iter().for_each(|sink| sink.record_span(&record)); + self.after_delivery(); } - fn send_stderr( - &self, - name: &str, - attributes: &BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, - ) { - let Some(stderr) = self.stderr.as_ref() else { - return; - }; - if !stderr.try_send(StderrTelemetryEvent { - event: name.to_string(), - attributes: attributes.clone(), - start_time_unix_nanos, - end_time_unix_nanos, - }) { - self.stats.dropped.fetch_add(1, Ordering::Relaxed); - } - } - - fn export(&self, record: TelemetryEvent) { - if let Some(file) = self.otlp_file - && !file.try_send(&self.config, event_to_span(&record, &self.stats)) - { - self.stats.dropped.fetch_add(1, Ordering::Relaxed); - } - let Some(tx) = self.tx.as_ref() else { - return; - }; - match tx.try_send(record) { - Ok(()) => { - self.stats.queued.fetch_add(1, Ordering::Relaxed); - } - Err(_) => { - self.stats.dropped.fetch_add(1, Ordering::Relaxed); - } + /// Components that stop after the process span (the scheduler worker, + /// say) end their spans during exit; deliver each one immediately + /// because the process will not wait for the exporters. + fn after_delivery(&self) { + if trace_context::process().is_finished() { + self.flush(LATE_SPAN_FLUSH_TIMEOUT); } } - /// Test-only capture takes precedence so sibling tests observe exact - /// emissions without a collector or the env-gated stderr sink. - #[cfg(test)] - fn capture( - &self, - name: &str, - attributes: &BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, - span: Option<(SpanContext, Option<[u8; 8]>)>, - ) -> bool { - let Some(capture) = self.capture.as_ref() else { - return false; - }; - let _ = capture.try_send(CapturedEvent { - event: name.to_string(), - attributes: attributes.clone(), - start_time_unix_nanos, - end_time_unix_nanos, - span, - }); - true - } - pub fn emit_debug(&self, name: &str, attributes: BTreeMap) { if self.level == TelemetryLevel::Debug { self.emit(name, attributes); @@ -496,7 +461,7 @@ impl Telemetry { return; } self.add_common_attributes(&mut attributes); - self.deliver(TelemetryEvent::span( + self.deliver(SpanRecord::of_frame( &Frame::under(parent), name, attributes, @@ -535,18 +500,14 @@ impl Telemetry { config: StageConfig, level: TelemetryLevel, ) -> (Self, std_mpsc::Receiver) { - let (tx, rx) = std_mpsc::sync_channel(256); + let (sink, rx) = sink::CaptureSink::channel(); ( - Self { - tx: None, - stderr: None, - otlp_file: None, - stats: Arc::new(TelemetryCounters::default()), - config: Arc::new(config), + Self::with_sinks( + vec![Box::new(sink)], + Arc::new(TelemetryCounters::default()), + Arc::new(config), level, - #[cfg(test)] - capture: Some(tx), - }, + ), rx, ) } @@ -610,20 +571,6 @@ mod capture_tests { } } -/// Run a blocking `wait` for the gRPC exporter, a task on the caller's -/// runtime. Blocking a runtime worker in place can starve that task: woken -/// from this worker, it sits in the worker's LIFO slot, which other workers -/// never steal. `block_in_place` hands the worker's queue to another thread -/// first. A current-thread runtime cannot run the exporter while blocked, so -/// waiting there would only stall. -fn without_starving_runtime(wait: impl FnOnce()) { - match tokio::runtime::Handle::try_current().map(|handle| handle.runtime_flavor()) { - Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(wait), - Ok(_) => {} - Err(_) => wait(), - } -} - pub fn lifecycle_attrs(config: &StageConfig) -> BTreeMap { BTreeMap::from([ (attr::RUN_ID.to_string(), json!(config.run_id)), @@ -647,192 +594,9 @@ pub fn now_unix_nanos() -> i64 { .as_nanos() as i64 } -async fn telemetry_export_loop( - endpoint: String, - mut rx: mpsc::Receiver, - stats: Arc, - config: Arc, -) { - let mut client = None; - let mut retry_buffer = VecDeque::new(); - - loop { - let Some(first_event) = next_export_event(&mut rx, &mut retry_buffer).await else { - break; - }; - let mut batch = Vec::with_capacity(EXPORT_BATCH_MAX); - batch.push(first_event); - fill_export_batch(&mut rx, &mut retry_buffer, &mut batch); - - let event_count = batch.len() as u64; - if export_batch(&endpoint, &mut client, &config, &stats, &batch).await { - stats.sent.fetch_add(event_count, Ordering::Relaxed); - } else { - stats - .export_errors - .fetch_add(event_count, Ordering::Relaxed); - let dropped = requeue_failed_batch(&mut retry_buffer, batch); - if dropped > 0 { - stats.dropped.fetch_add(dropped as u64, Ordering::Relaxed); - } - sleep(RETRY_BACKOFF).await; - } - } -} - -async fn next_export_event( - rx: &mut mpsc::Receiver, - retry_buffer: &mut VecDeque, -) -> Option { - match retry_buffer.pop_front() { - Some(event) => Some(event), - None => rx.recv().await, - } -} - -fn fill_export_batch( - rx: &mut mpsc::Receiver, - retry_buffer: &mut VecDeque, - batch: &mut Vec, -) { - while batch.len() < EXPORT_BATCH_MAX { - if let Some(event) = retry_buffer.pop_front() { - batch.push(event); - continue; - } - match rx.try_recv() { - Ok(event) => batch.push(event), - Err(_) => break, - } - } -} - -async fn export_batch( - endpoint: &str, - client: &mut Option>, - config: &StageConfig, - stats: &TelemetryCounters, - events: &[TelemetryEvent], -) -> bool { - if client.is_none() { - match timeout( - EXPORT_TIMEOUT, - TraceServiceClient::connect(endpoint.to_string()), - ) - .await - { - Ok(Ok(connected)) => { - *client = Some(connected); - } - Ok(Err(_)) | Err(_) => return false, - } - } - - let request = ExportTraceServiceRequest { - resource_spans: resource_spans_by_component( - config, - events - .iter() - .map(|event| event_to_span(event, stats)) - .collect(), - ), - }; - - let export = client - .as_mut() - .expect("client is connected above") - .export(request); - match timeout(EXPORT_TIMEOUT, export).await { - Ok(Ok(_)) => true, - Ok(Err(_)) | Err(_) => { - *client = None; - false - } - } -} - -fn requeue_failed_batch( - retry_buffer: &mut VecDeque, - batch: Vec, -) -> usize { - let overflow = retry_buffer - .len() - .saturating_add(batch.len()) - .saturating_sub(RETRY_BUFFER_CAPACITY); - for _ in 0..overflow { - retry_buffer.pop_back(); - } - for event in batch.into_iter().rev() { - retry_buffer.push_front(event); - } - overflow -} - #[cfg(test)] mod tests { - use super::{TelemetryLevel, effective_level, without_starving_runtime}; - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::time::{Duration, Instant}; - - /// Block on a one-worker runtime until a task spawned from that worker - /// runs, or `patience` passes; true when the task ran. - fn spawned_task_runs_while_waiting( - patience: Duration, - wait: fn(Box), - ) -> bool { - let runtime = tokio::runtime::Builder::new_multi_thread() - .worker_threads(1) - .build() - .unwrap(); - runtime.block_on(async move { - tokio::spawn(async move { - let ran = Arc::new(AtomicBool::new(false)); - let task_ran = Arc::clone(&ran); - tokio::spawn(async move { task_ran.store(true, Ordering::SeqCst) }); - let deadline = Instant::now() + patience; - wait(Box::new(|| { - while !ran.load(Ordering::SeqCst) && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(1)); - } - })); - ran.load(Ordering::SeqCst) - }) - .await - .unwrap() - }) - } - - #[test] - fn waiting_on_a_runtime_worker_lets_the_workers_tasks_run() { - assert!(spawned_task_runs_while_waiting( - Duration::from_secs(5), - |wait| without_starving_runtime(wait) - )); - } - - #[test] - fn waiting_in_place_on_a_runtime_worker_starves_its_tasks() { - // The failure the helper exists for; if this ever passes, tokio has - // made the LIFO slot stealable. - assert!(!spawned_task_runs_while_waiting( - Duration::from_millis(200), - |wait| wait() - )); - } - - #[test] - fn a_current_thread_runtime_does_not_stall_waiting() { - let runtime = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - let started = Instant::now(); - runtime.block_on(async { - without_starving_runtime(|| std::thread::sleep(Duration::from_secs(5))); - }); - assert!(started.elapsed() < Duration::from_secs(1)); - } - + use super::{TelemetryLevel, effective_level}; /// `SKIPPY_TELEMETRY_STDERR` is the only way to see record/lookup /// decisions in a single-process embedded run, and the embedded runtime /// defaults to `Off`. If the variable does not raise the level, the sink diff --git a/skippy/crates/skippy-serving/src/telemetry/active_span.rs b/skippy/crates/skippy-serving/src/telemetry/active_span.rs index af0887fc0d..8befb94670 100644 --- a/skippy/crates/skippy-serving/src/telemetry/active_span.rs +++ b/skippy/crates/skippy-serving/src/telemetry/active_span.rs @@ -9,7 +9,9 @@ use std::{ use serde_json::Value; use super::{ - Telemetry, TelemetryLevel, now_unix_nanos, + OpenSpans, Telemetry, TelemetryLevel, now_unix_nanos, + resource_metrics::SpanWindow, + sink::SpanStart, trace_context::{self, Entered, Frame, SpanContext}, }; @@ -33,6 +35,10 @@ pub(crate) struct ActiveSpan { /// `None` when not recorded: the frame then passes the parent through, so /// children never point at a span that is not exported. telemetry: Option, + /// What the sinks kept at the start; taken back when the span ends. + open: Option, + /// The process's resource counters at the start, for `with_metrics`. + window: Option, frame: Frame, name: &'static str, start_unix_nanos: u64, @@ -80,17 +86,39 @@ impl ActiveSpan { } else { parent.clone() }; + let start_unix_nanos = u64::try_from(now_unix_nanos()).unwrap_or_default(); + let open = telemetry.as_ref().map(|telemetry| { + telemetry.begin_span(&SpanStart { + name, + level, + context: frame.context(), + parent: frame.parent_span_id(), + start_time_unix_nanos: start_unix_nanos, + }) + }); Self { telemetry, + open, + window: None, frame, name, - start_unix_nanos: u64::try_from(now_unix_nanos()).unwrap_or_default(), + start_unix_nanos, started: Instant::now(), attributes: BTreeMap::new(), links: Vec::new(), } } + /// Charge the span what the process used while it was open: CPU time, + /// GPU execution, footprint change and live KV cells, as `skippy.span.*` + /// attributes when it ends. Process-wide figures, not this thread's. + pub(crate) fn with_metrics(mut self) -> Self { + if self.telemetry.is_some() { + self.window = Some(SpanWindow::open()); + } + self + } + /// Make this the active span on this thread (synchronous code). pub(crate) fn enter(&self) -> Entered { self.frame.enter() @@ -124,15 +152,21 @@ impl ActiveSpan { /// Drop without exporting, for a section that turned out to do no work. pub(crate) fn discard(mut self) { - self.telemetry = None; + if let Some((telemetry, open)) = self.telemetry.take().zip(self.open.take()) { + telemetry.discard_span(open); + } } fn finish(&mut self) { - let Some(telemetry) = self.telemetry.take() else { + let Some((telemetry, open)) = self.telemetry.take().zip(self.open.take()) else { return; }; + if let Some(window) = self.window.take() { + self.attributes.extend(window.close()); + } let elapsed = u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX); - telemetry.emit_frame_span( + telemetry.end_span( + open, &self.frame, self.name, std::mem::take(&mut self.attributes), @@ -217,6 +251,34 @@ mod tests { ); } + #[test] + fn a_span_with_metrics_carries_its_resource_window() { + let (telemetry, rx) = Telemetry::captured(config(), TelemetryLevel::Debug); + ActiveSpan::start(Some(&telemetry), "stage.measured", SpanLevel::Debug) + .with_metrics() + .end(); + ActiveSpan::start(Some(&telemetry), "stage.plain", SpanLevel::Debug).end(); + let events: Vec<_> = rx.try_iter().collect(); + let measured = events.iter().find(|e| e.event == "stage.measured").unwrap(); + assert!( + measured + .attributes + .contains_key("skippy.span.gpu_execute_ms") + ); + assert!( + measured + .attributes + .contains_key("skippy.span.gpu_command_buffers") + ); + let plain = events.iter().find(|e| e.event == "stage.plain").unwrap(); + assert!( + !plain + .attributes + .keys() + .any(|key| key.starts_with("skippy.span.")) + ); + } + #[test] fn an_unrecorded_span_passes_its_parent_through() { let (telemetry, rx) = Telemetry::captured(config(), TelemetryLevel::Summary); diff --git a/skippy/crates/skippy-serving/src/telemetry/otlp_collector.rs b/skippy/crates/skippy-serving/src/telemetry/otlp_collector.rs new file mode 100644 index 0000000000..f2a684e037 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/otlp_collector.rs @@ -0,0 +1,293 @@ +//! The OTLP/gRPC collector sink: finished spans, batched by an exporter task +//! on the caller's runtime, retried from a bounded buffer. + +use std::{ + collections::VecDeque, + sync::{Arc, atomic::Ordering}, + thread, + time::{Duration, Instant}, +}; + +use opentelemetry_proto::tonic::collector::trace::v1::{ + ExportTraceServiceRequest, trace_service_client::TraceServiceClient, +}; +use opentelemetry_proto::tonic::metrics::v1::Metric; +use skippy_protocol::StageConfig; +use tokio::{ + sync::mpsc, + time::{sleep, timeout}, +}; + +use super::{ + TelemetryCounters, + otlp_encoding::{event_to_span, resource_spans_by_component}, + sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}, + trace_context::{Frame, SpanEvent}, +}; + +const EXPORT_TIMEOUT: Duration = Duration::from_secs(10); +const EXPORT_BATCH_MAX: usize = 128; +const RETRY_BUFFER_CAPACITY: usize = 8192; +const RETRY_BACKOFF: Duration = Duration::from_millis(100); + +pub(super) struct OtlpCollectorSink { + tx: mpsc::Sender, + stats: Arc, +} + +impl OtlpCollectorSink { + /// Start exporting to `endpoint` from a task on the current runtime. + pub(super) fn start( + endpoint: String, + capacity: usize, + stats: Arc, + config: Arc, + ) -> Self { + let (tx, rx) = mpsc::channel(capacity); + tokio::spawn(telemetry_export_loop(endpoint, rx, stats.clone(), config)); + Self { tx, stats } + } +} + +impl TraceSink for OtlpCollectorSink { + fn create_span_with(&self, _: &SpanStart) -> OpenSpan { + OpenSpan::NONE + } + + fn end_span(&self, _: OpenSpan, span: &SpanRecord) { + self.record_span(span); + } + + fn discard_span(&self, _: OpenSpan) {} + + fn record_span(&self, span: &SpanRecord) { + match self.tx.try_send(span.clone()) { + Ok(()) => { + self.stats.queued.fetch_add(1, Ordering::Relaxed); + } + Err(_) => { + self.stats.dropped.fetch_add(1, Ordering::Relaxed); + } + } + } + + /// Events reach the collector inside their span. + fn record_event(&self, _: &SpanEvent, _: &Frame) {} + + /// Metrics have their own OTLP sink. + fn record_metrics(&self, _: &[Metric]) {} + + fn folds_events_into_spans(&self) -> bool { + true + } + + fn flush(&self, timeout: Duration) { + let deadline = Instant::now() + timeout; + without_starving_runtime(|| { + while self.stats.sent.load(Ordering::Relaxed) + < self.stats.queued.load(Ordering::Relaxed) + && Instant::now() < deadline + { + thread::sleep(Duration::from_millis(20)); + } + }); + } +} + +/// Run a blocking `wait` for the gRPC exporter, a task on the caller's +/// runtime. Blocking a runtime worker in place can starve that task: woken +/// from this worker, it sits in the worker's LIFO slot, which other workers +/// never steal. `block_in_place` hands the worker's queue to another thread +/// first. A current-thread runtime cannot run the exporter while blocked, so +/// waiting there would only stall. +fn without_starving_runtime(wait: impl FnOnce()) { + match tokio::runtime::Handle::try_current().map(|handle| handle.runtime_flavor()) { + Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(wait), + Ok(_) => {} + Err(_) => wait(), + } +} + +async fn telemetry_export_loop( + endpoint: String, + mut rx: mpsc::Receiver, + stats: Arc, + config: Arc, +) { + let mut client = None; + let mut retry_buffer = VecDeque::new(); + + loop { + let Some(first_event) = next_export_event(&mut rx, &mut retry_buffer).await else { + break; + }; + let mut batch = Vec::with_capacity(EXPORT_BATCH_MAX); + batch.push(first_event); + fill_export_batch(&mut rx, &mut retry_buffer, &mut batch); + + let event_count = batch.len() as u64; + if export_batch(&endpoint, &mut client, &config, &stats, &batch).await { + stats.sent.fetch_add(event_count, Ordering::Relaxed); + } else { + stats + .export_errors + .fetch_add(event_count, Ordering::Relaxed); + let dropped = requeue_failed_batch(&mut retry_buffer, batch); + if dropped > 0 { + stats.dropped.fetch_add(dropped as u64, Ordering::Relaxed); + } + sleep(RETRY_BACKOFF).await; + } + } +} + +async fn next_export_event( + rx: &mut mpsc::Receiver, + retry_buffer: &mut VecDeque, +) -> Option { + match retry_buffer.pop_front() { + Some(event) => Some(event), + None => rx.recv().await, + } +} + +fn fill_export_batch( + rx: &mut mpsc::Receiver, + retry_buffer: &mut VecDeque, + batch: &mut Vec, +) { + while batch.len() < EXPORT_BATCH_MAX { + if let Some(event) = retry_buffer.pop_front() { + batch.push(event); + continue; + } + match rx.try_recv() { + Ok(event) => batch.push(event), + Err(_) => break, + } + } +} + +async fn export_batch( + endpoint: &str, + client: &mut Option>, + config: &StageConfig, + stats: &TelemetryCounters, + events: &[SpanRecord], +) -> bool { + if client.is_none() { + match timeout( + EXPORT_TIMEOUT, + TraceServiceClient::connect(endpoint.to_string()), + ) + .await + { + Ok(Ok(connected)) => { + *client = Some(connected); + } + Ok(Err(_)) | Err(_) => return false, + } + } + + let request = ExportTraceServiceRequest { + resource_spans: resource_spans_by_component( + config, + events + .iter() + .map(|event| event_to_span(event, stats)) + .collect(), + ), + }; + + let export = client + .as_mut() + .expect("client is connected above") + .export(request); + match timeout(EXPORT_TIMEOUT, export).await { + Ok(Ok(_)) => true, + Ok(Err(_)) | Err(_) => { + *client = None; + false + } + } +} + +fn requeue_failed_batch(retry_buffer: &mut VecDeque, batch: Vec) -> usize { + let overflow = retry_buffer + .len() + .saturating_add(batch.len()) + .saturating_sub(RETRY_BUFFER_CAPACITY); + for _ in 0..overflow { + retry_buffer.pop_back(); + } + for event in batch.into_iter().rev() { + retry_buffer.push_front(event); + } + overflow +} + +#[cfg(test)] +mod tests { + use super::without_starving_runtime; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + /// Block on a one-worker runtime until a task spawned from that worker + /// runs, or `patience` passes; true when the task ran. + fn spawned_task_runs_while_waiting( + patience: Duration, + wait: fn(Box), + ) -> bool { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .build() + .unwrap(); + runtime.block_on(async move { + tokio::spawn(async move { + let ran = Arc::new(AtomicBool::new(false)); + let task_ran = Arc::clone(&ran); + tokio::spawn(async move { task_ran.store(true, Ordering::SeqCst) }); + let deadline = Instant::now() + patience; + wait(Box::new(|| { + while !ran.load(Ordering::SeqCst) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + })); + ran.load(Ordering::SeqCst) + }) + .await + .unwrap() + }) + } + + #[test] + fn waiting_on_a_runtime_worker_lets_the_workers_tasks_run() { + assert!(spawned_task_runs_while_waiting( + Duration::from_secs(5), + |wait| without_starving_runtime(wait) + )); + } + + #[test] + fn waiting_in_place_on_a_runtime_worker_starves_its_tasks() { + // The failure the helper exists for; if this ever passes, tokio has + // made the LIFO slot stealable. + assert!(!spawned_task_runs_while_waiting( + Duration::from_millis(200), + |wait| wait() + )); + } + + #[test] + fn a_current_thread_runtime_does_not_stall_waiting() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let started = Instant::now(); + runtime.block_on(async { + without_starving_runtime(|| std::thread::sleep(Duration::from_secs(5))); + }); + assert!(started.elapsed() < Duration::from_secs(1)); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs b/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs index cffeac4953..28a741e555 100644 --- a/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs +++ b/skippy/crates/skippy-serving/src/telemetry/otlp_encoding.rs @@ -12,7 +12,7 @@ use skippy_metrics::metric; use skippy_protocol::StageConfig; use super::{ - TelemetryCounters, TelemetryEvent, resource_attrs::resource_attrs, span_components::component, + TelemetryCounters, resource_attrs::resource_attrs, sink::SpanRecord, span_components::component, }; /// One stage's spans, one resource per system component (see @@ -56,7 +56,7 @@ fn resource_spans(config: &StageConfig, service: &str, spans: Vec) -> Reso } } -pub(super) fn event_to_span(event: &TelemetryEvent, stats: &TelemetryCounters) -> Span { +pub(super) fn event_to_span(event: &SpanRecord, stats: &TelemetryCounters) -> Span { let mut attributes = event.attributes.clone(); attributes.insert( metric::OTEL_DROPPED_EVENTS.to_string(), diff --git a/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs b/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs index 05e1464251..c3ed5464c5 100644 --- a/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs +++ b/skippy/crates/skippy-serving/src/telemetry/otlp_file.rs @@ -10,17 +10,23 @@ use std::{ fs::OpenOptions, io::{self, BufWriter, Write}, path::{Path, PathBuf}, - sync::{Arc, OnceLock, mpsc as std_mpsc}, + sync::{Arc, OnceLock, atomic::Ordering, mpsc as std_mpsc}, thread::{self, JoinHandle}, time::Duration, }; +use opentelemetry_proto::tonic::metrics::v1::Metric; use opentelemetry_proto::tonic::{ collector::trace::v1::ExportTraceServiceRequest, trace::v1::Span, }; use skippy_protocol::StageConfig; -use super::{EXPORT_BATCH_MAX, resource_spans_by_component}; +use super::{ + EXPORT_BATCH_MAX, TelemetryCounters, + otlp_encoding::{event_to_span, resource_spans_by_component}, + sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}, + trace_context::{Frame, SpanEvent}, +}; const PATH_ENV: &str = "SKIPPY_TELEMETRY_OTLP_FILE"; const QUEUE_CAPACITY: usize = 8192; @@ -108,6 +114,61 @@ impl Drop for OtlpFileSink { } } +/// The process-wide file, written as one `Telemetry`'s sink. +pub(super) struct OtlpFileTraceSink { + file: &'static OtlpFileSink, + config: Arc, + stats: Arc, +} + +impl OtlpFileTraceSink { + pub(super) fn configured( + config: Arc, + stats: Arc, + ) -> Option { + configured().map(|file| Self { + file, + config, + stats, + }) + } +} + +impl TraceSink for OtlpFileTraceSink { + fn create_span_with(&self, _: &SpanStart) -> OpenSpan { + OpenSpan::NONE + } + + fn end_span(&self, _: OpenSpan, span: &SpanRecord) { + self.record_span(span); + } + + fn discard_span(&self, _: OpenSpan) {} + + fn record_span(&self, span: &SpanRecord) { + if !self + .file + .try_send(&self.config, event_to_span(span, &self.stats)) + { + self.stats.dropped.fetch_add(1, Ordering::Relaxed); + } + } + + /// Events reach the file inside their span. + fn record_event(&self, _: &SpanEvent, _: &Frame) {} + + /// Metrics have their own OTLP sink. + fn record_metrics(&self, _: &[Metric]) {} + + fn folds_events_into_spans(&self) -> bool { + true + } + + fn flush(&self, timeout: Duration) { + self.file.flush(timeout); + } +} + /// Write each drained batch as one flushed line, so a killed server leaves /// only whole requests behind. fn write_loop(rx: &std_mpsc::Receiver, mut out: impl Write) { @@ -165,7 +226,9 @@ mod tests { use super::{FileItem, FileSpan, OtlpFileSink, path_from_value, write_loop}; use crate::telemetry::{ - TelemetryCounters, TelemetryEvent, event_to_span, + TelemetryCounters, + otlp_encoding::event_to_span, + sink::SpanRecord, trace_context::{Frame, SpanEvent}, }; @@ -187,9 +250,9 @@ mod tests { ) } - fn record(frame: &Frame) -> TelemetryEvent { + fn record(frame: &Frame) -> SpanRecord { let attributes = BTreeMap::from([("skippy.scheduler.step_ms".to_string(), json!(2.5))]); - TelemetryEvent::span( + SpanRecord::of_frame( frame, "stage.scheduler_iteration", attributes, @@ -198,7 +261,7 @@ mod tests { ) } - fn file_span(config: &Arc, record: &TelemetryEvent) -> FileSpan { + fn file_span(config: &Arc, record: &SpanRecord) -> FileSpan { FileSpan { config: config.clone(), span: event_to_span(record, &TelemetryCounters::default()), diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs index 8e8a69a6b5..9274134e17 100644 --- a/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs +++ b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs @@ -1,26 +1,53 @@ -//! The resource every signal carries: the stage's lifecycle attributes, the -//! serving configuration that changes what the GPU does (KV precision, flash -//! attention, context, lanes, batch sizes), and whatever the operator set in -//! `OTEL_RESOURCE_ATTRIBUTES`, so runs with different settings can be told -//! apart and compared from their telemetry alone. +//! The resource every signal carries: the keys that make runs comparable +//! across machines, backends and commits, the stage's lifecycle attributes, +//! the serving configuration that changes what the GPU does (KV precision, +//! flash attention, context, lanes, batch sizes), and whatever the operator +//! set in `OTEL_RESOURCE_ATTRIBUTES`, so runs with different settings can be +//! told apart and compared from their telemetry alone. use std::{collections::BTreeMap, env, sync::OnceLock}; use serde_json::{Value, json}; -use skippy_protocol::StageConfig; +use skippy_protocol::{StageConfig, StageKvRetention}; +use skippy_runtime::{BackendDeviceType, backend_devices_untraced}; use super::{lifecycle_attrs, span_components::SERVICE_NAMESPACE}; /// The standard OpenTelemetry variable for extra resource attributes. const RESOURCE_ATTRIBUTES_ENV: &str = "OTEL_RESOURCE_ATTRIBUTES"; -/// Resource attributes for `service`. Operator attributes come first, so the -/// stage's own identity and configuration win over a conflicting key. +/// The run this process is: the stage's run id. +pub const RUN_ID: &str = "run.id"; +/// The backend the runtime computes on (`MTL`, `CUDA`, `CPU`), once it has +/// computed anything; spans exported before that carry no backend. +pub const BACKEND_NAME: &str = "backend.name"; +/// The commit skippy-serving was built from. `test.name`, the workload that +/// compares across runs, is the operator's alone and passes through. +pub const GIT_COMMIT_SHA: &str = "git.commit.sha"; +/// The machine the run happened on; the host name unless the operator sets it. +pub const MACHINE_ID: &str = "machine.id"; +/// `warmup` or `measured`; `measured` unless the operator sets it. +pub const RUN_PHASE: &str = "run.phase"; + +/// Resource attributes for `service`. Operator attributes override the +/// defaults for the machine and phase; the stage's own identity, build and +/// configuration win over a conflicting key. pub(super) fn resource_attrs(config: &StageConfig, service: &str) -> BTreeMap { - let mut attributes = operator_attributes() - .iter() - .map(|(key, value)| (key.clone(), json!(value))) - .collect::>(); + resource_attrs_with(operator_attributes(), config, service) +} + +fn resource_attrs_with( + operator: &[(String, String)], + config: &StageConfig, + service: &str, +) -> BTreeMap { + let mut attributes = run_defaults(); + attributes.extend( + operator + .iter() + .map(|(key, value)| (key.clone(), json!(value))), + ); + attributes.extend(run_identity(config)); attributes.extend(lifecycle_attrs(config)); attributes.extend(serving_config_attrs(config)); attributes.insert("service.name".to_string(), json!(service)); @@ -28,6 +55,74 @@ pub(super) fn resource_attrs(config: &StageConfig, service: &str) -> BTreeMap BTreeMap { + let mut attributes = BTreeMap::from([(RUN_PHASE.to_string(), json!("measured"))]); + attributes.extend(host_name().map(|name| (MACHINE_ID.to_string(), json!(name)))); + attributes +} + +/// What the process knows about itself: its run, its build and, once known, +/// its backend. +fn run_identity(config: &StageConfig) -> BTreeMap { + let mut attributes = BTreeMap::from([ + (RUN_ID.to_string(), json!(config.run_id)), + (GIT_COMMIT_SHA.to_string(), json!(env!("SKIPPY_GIT_COMMIT"))), + ]); + attributes.extend(backend_name().map(|name| (BACKEND_NAME.to_string(), json!(name)))); + attributes +} + +/// The backend of the first GPU the runtime reports, else of its first +/// device, named as GPU command spans name it: the device name without its +/// index (`MTL0` is `MTL`). Devices are queried once the runtime has made a +/// traced native call, so the query is never the call that starts it. +fn backend_name() -> Option<&'static str> { + static NAME: OnceLock = OnceLock::new(); + if let Some(name) = NAME.get() { + return Some(name); + } + if !skippy_runtime::native_tracing::native_tracing_active() { + return None; + } + let devices = backend_devices_untraced().ok()?; + let device = devices + .iter() + .find(|device| { + matches!( + device.device_type, + BackendDeviceType::Gpu | BackendDeviceType::IntegratedGpu + ) + }) + .or_else(|| devices.first())?; + let name = device + .name + .trim_end_matches(|c: char| c.is_ascii_digit()) + .to_string(); + Some(NAME.get_or_init(|| name)) +} + +/// The host name from the kernel, as `machine.id` when the operator sets none. +#[cfg(unix)] +fn host_name() -> Option { + let mut bytes = [0_u8; 256]; + // SAFETY: bytes is writable for the exact length passed to libc. + if unsafe { libc::gethostname(bytes.as_mut_ptr().cast(), bytes.len()) } != 0 { + return None; + } + let end = bytes.iter().position(|byte| *byte == 0)?; + let name = std::str::from_utf8(&bytes[..end]).ok()?.trim(); + (!name.is_empty()).then(|| name.to_string()) +} + +#[cfg(not(unix))] +fn host_name() -> Option { + env::var("COMPUTERNAME") + .or_else(|_| env::var("HOSTNAME")) + .ok() + .filter(|name| !name.trim().is_empty()) +} + /// The settings that decide which kernels run and how much KV they read. fn serving_config_attrs(config: &StageConfig) -> BTreeMap { let mut attributes = BTreeMap::from([ @@ -55,6 +150,33 @@ fn serving_config_attrs(config: &StageConfig) -> BTreeMap { ("skippy.kv.unified", config.kv_unified.map(Value::from)), ("skippy.kv.offload", config.kv_offload.map(Value::from)), ("skippy.kv.swa_full", config.swa_full.map(Value::from)), + ( + "skippy.kv.pool_tokens", + config.kv_pool_tokens.map(|tokens| Value::from(tokens.get())), + ), + ("skippy.kv.lazy_clear", config.kv_lazy_clear.map(Value::from)), + ( + "skippy.kv.release_pages", + config.kv_release_pages.map(Value::from), + ), + ( + "skippy.kv.row_attention", + config.kv_row_attention.map(Value::from), + ), + ( + "skippy.kv.retention_tokens", + config + .kv_cache + .as_ref() + .map(|cache| match cache.retention { + StageKvRetention::Tokens(tokens) => Value::from(tokens), + StageKvRetention::Unbounded => Value::from("unbounded"), + }), + ), + ( + "skippy.scheduler.prefill_coalesce_max_ms", + config.prefill_coalesce_max_ms.map(Value::from), + ), ]; attributes.extend( optional @@ -136,6 +258,32 @@ mod tests { .expect("stage config") } + #[test] + fn the_resource_identifies_the_run_build_and_machine() { + let attributes = resource_attrs_with(&[], &stage_config(), "skippy"); + assert_eq!(attributes[RUN_ID], json!("run")); + assert_eq!(attributes[RUN_PHASE], json!("measured")); + assert!(!attributes[GIT_COMMIT_SHA].as_str().unwrap().is_empty()); + assert!(!attributes.contains_key("test.name")); + assert!(!attributes.contains_key(BACKEND_NAME)); + assert_eq!(attributes.contains_key(MACHINE_ID), host_name().is_some()); + } + + #[test] + fn the_operator_sets_the_test_phase_and_machine_but_not_the_run() { + let operator = [ + ("test.name".to_string(), "benchy-pp512-tg128-c4".to_string()), + (RUN_PHASE.to_string(), "warmup".to_string()), + (MACHINE_ID.to_string(), "spark-137".to_string()), + (RUN_ID.to_string(), "not-this-run".to_string()), + ]; + let attributes = resource_attrs_with(&operator, &stage_config(), "skippy"); + assert_eq!(attributes["test.name"], json!("benchy-pp512-tg128-c4")); + assert_eq!(attributes[RUN_PHASE], json!("warmup")); + assert_eq!(attributes[MACHINE_ID], json!("spark-137")); + assert_eq!(attributes[RUN_ID], json!("run")); + } + #[test] fn the_resource_names_the_kv_and_attention_configuration() { let attributes = resource_attrs(&stage_config(), "skippy"); diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs index b31c28a0dc..d2e2274251 100644 --- a/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics.rs @@ -36,7 +36,8 @@ mod otlp_metrics; use gpu_op_classes::{GraphShape, OpClassCounters}; use kv_tiers::KvTiers; -use otlp_metrics::{MetricSinks, gauge, point}; +pub(super) use otlp_metrics::OtlpMetricsSink; +use otlp_metrics::{gauge, point}; /// Where sampled metrics are appended, one OTLP/JSON request per line. pub(super) const METRICS_FILE_ENV: &str = "SKIPPY_TELEMETRY_OTLP_METRICS_FILE"; @@ -56,6 +57,7 @@ static SCHEDULER_RUNNING: AtomicU64 = AtomicU64::new(UNSET); static SCHEDULER_WAITING: AtomicU64 = AtomicU64::new(UNSET); static SCHEDULER_BATCH: AtomicU64 = AtomicU64::new(UNSET); static KV_USED_CELLS: AtomicU64 = AtomicU64::new(UNSET); +static KV_POOL_CELLS: AtomicU64 = AtomicU64::new(UNSET); /// One GPU command buffer: how long the GPU ran it, and how long it waited /// between being committed and starting. @@ -85,6 +87,11 @@ pub(crate) fn record_kv_used_cells(cells: u64) { KV_USED_CELLS.store(cells, Ordering::Relaxed); } +/// The native KV pool, once the runtime has loaded it. +pub(crate) fn record_kv_pool_cells(cells: u64) { + KV_POOL_CELLS.store(cells, Ordering::Relaxed); +} + fn nanos(duration: Duration) -> u64 { u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) } @@ -94,6 +101,64 @@ fn current(gauge: &AtomicU64) -> Option { (value != UNSET).then_some(value) } +/// What a span's resource window starts from; see [`SpanWindow::close`]. +pub(crate) struct SpanWindow { + counters: Counters, + process: Option, +} + +impl SpanWindow { + pub(crate) fn open() -> Self { + Self { + counters: Counters::now(), + process: process_usage(), + } + } + + /// What the whole process used while the window was open, as + /// `skippy.span.*` attributes: CPU seconds charged to the process, GPU + /// command execution that completed, the change in footprint, and the + /// live KV cells at the end. Process-wide, not this thread's alone. + pub(crate) fn close(self) -> BTreeMap { + let counters = Counters::now(); + let ms = |nanos: u64| nanos as f64 / 1e6; + let mut attributes = BTreeMap::from([ + ( + "skippy.span.gpu_execute_ms".to_string(), + json!(ms( + counters.gpu_execute_nanos - self.counters.gpu_execute_nanos + )), + ), + ( + "skippy.span.gpu_command_buffers".to_string(), + json!(counters.gpu_commands - self.counters.gpu_commands), + ), + ( + "skippy.span.runtime_busy_ms".to_string(), + json!(ms( + counters.runtime_busy_nanos - self.counters.runtime_busy_nanos + )), + ), + ]); + if let Some((before, after)) = self.process.zip(process_usage()) { + let cpu = + after.user.saturating_sub(before.user) + after.system.saturating_sub(before.system); + attributes.insert( + "skippy.span.cpu_ms".to_string(), + json!(cpu.as_secs_f64() * 1_000.0), + ); + attributes.insert( + "skippy.span.footprint_delta_bytes".to_string(), + json!(after.footprint_bytes as i64 - before.footprint_bytes as i64), + ); + } + if let Some(cells) = current(&KV_USED_CELLS) { + attributes.insert("skippy.span.kv_used_cells".to_string(), json!(cells)); + } + attributes + } +} + /// Monotonic counters at one instant. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct Counters { @@ -508,10 +573,9 @@ fn runtime_gauges( )); } -/// The running sampler: its sinks and the reading the next sample starts at. +/// The running sampler and the reading the next sample starts at. struct Sampler { telemetry: Telemetry, - sinks: MetricSinks, last: Mutex, stopped: AtomicBool, } @@ -526,7 +590,7 @@ impl Sampler { *last = now; drop(last); if !metrics.is_empty() { - self.sinks.send(&self.telemetry.config, metrics); + self.telemetry.record_metrics(&metrics); } } } @@ -541,18 +605,14 @@ fn interval_from_value(value: Option<&str>) -> Duration { }) } -/// Start sampling for the process, if there is anywhere to send it. The first -/// debug handle with a destination serves the whole process. -pub(super) fn start(telemetry: &Telemetry, endpoint: Option<&str>) { - let Some(sinks) = MetricSinks::open( - env::var_os(METRICS_FILE_ENV).filter(|path| !path.is_empty()), - endpoint, - ) else { +/// Start sampling for the process, if some sink takes samples. The first +/// debug handle with a sink serves the whole process. +pub(super) fn start(telemetry: &Telemetry) { + if !telemetry.records_metrics() { return; - }; + } let sampler = Sampler { telemetry: telemetry.clone(), - sinks, last: Mutex::new(Reading::take(None)), stopped: AtomicBool::new(false), }; @@ -576,13 +636,13 @@ pub(super) fn start(telemetry: &Telemetry, endpoint: Option<&str>) { } } -/// Take a last sample and stop; called as the process span ends. +/// Take a last sample and stop; called as the process span ends, whose +/// flush then reaches every sink. pub(super) fn finish() { if let Some(sampler) = SAMPLER.get() && !sampler.stopped.swap(true, Ordering::AcqRel) { sampler.tick(); - sampler.sinks.flush(); } } @@ -632,6 +692,7 @@ fn snapshot(point: &str) -> BTreeMap { ("scheduler.running", current(&SCHEDULER_RUNNING)), ("scheduler.waiting", current(&SCHEDULER_WAITING)), ("kv.used_cells", current(&KV_USED_CELLS)), + ("kv.pool_cells", current(&KV_POOL_CELLS)), ]; for (name, value) in gauges { if let Some(value) = value { @@ -673,6 +734,27 @@ mod tests { use super::*; use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point}; + #[test] + fn a_span_window_charges_what_the_process_used_while_it_was_open() { + let window = SpanWindow::open(); + record_gpu_command(Duration::from_millis(8), Duration::from_millis(1)); + record_gpu_command(Duration::from_millis(2), Duration::ZERO); + record_runtime_busy(Duration::from_millis(3)); + // Burn some CPU so the charged time is visible on every platform. + let spin = Instant::now(); + while spin.elapsed() < Duration::from_millis(5) { + std::hint::black_box(0); + } + let attributes = window.close(); + assert_eq!(attributes["skippy.span.gpu_execute_ms"], json!(10.0)); + assert_eq!(attributes["skippy.span.gpu_command_buffers"], json!(2)); + assert_eq!(attributes["skippy.span.runtime_busy_ms"], json!(3.0)); + if let Some(cpu) = attributes.get("skippy.span.cpu_ms") { + assert!(cpu.as_f64().unwrap() >= 0.0); + assert!(attributes.contains_key("skippy.span.footprint_delta_bytes")); + } + } + fn reading(at: Instant, cpu_ms: u64, counters: Counters) -> Reading { Reading { at, diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs index 23b6f5de70..190bfb8509 100644 --- a/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs +++ b/skippy/crates/skippy-serving/src/telemetry/resource_metrics/otlp_metrics.rs @@ -6,7 +6,7 @@ use std::{ ffi::OsString, fs::{File, OpenOptions}, io::{BufWriter, Write}, - sync::{Mutex, PoisonError}, + sync::{Arc, Mutex, PoisonError}, time::Duration, }; @@ -23,7 +23,12 @@ use opentelemetry_proto::tonic::{ use skippy_protocol::StageConfig; use tokio::{sync::mpsc, time::timeout}; -use super::super::{otlp_encoding::key_values, resource_attrs::resource_attrs}; +use super::super::{ + otlp_encoding::key_values, + resource_attrs::resource_attrs, + sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}, + trace_context::{Frame, SpanEvent}, +}; const EXPORT_TIMEOUT: Duration = Duration::from_secs(5); /// Samples queued for the gRPC exporter before new ones are dropped. @@ -144,6 +149,49 @@ impl MetricSinks { } } +/// The metric destinations as one of `Telemetry`'s sinks: samples only, so +/// spans and events pass it by. +pub(in crate::telemetry) struct OtlpMetricsSink { + sinks: MetricSinks, + config: Arc, +} + +impl OtlpMetricsSink { + pub(in crate::telemetry) fn configured( + config: Arc, + path: Option, + endpoint: Option<&str>, + ) -> Option { + MetricSinks::open(path, endpoint).map(|sinks| Self { sinks, config }) + } +} + +impl TraceSink for OtlpMetricsSink { + fn create_span_with(&self, _: &SpanStart) -> OpenSpan { + OpenSpan::NONE + } + + fn end_span(&self, _: OpenSpan, _: &SpanRecord) {} + + fn discard_span(&self, _: OpenSpan) {} + + fn record_span(&self, _: &SpanRecord) {} + + fn record_event(&self, _: &SpanEvent, _: &Frame) {} + + fn record_metrics(&self, metrics: &[Metric]) { + self.sinks.send(&self.config, metrics.to_vec()); + } + + fn folds_events_into_spans(&self) -> bool { + false + } + + fn flush(&self, _: Duration) { + self.sinks.flush(); + } +} + /// Export samples in order, reconnecting after a failure; a sample that /// fails is dropped rather than retried, since the next one supersedes it. async fn export_loop(endpoint: String, mut rx: mpsc::Receiver) { diff --git a/skippy/crates/skippy-serving/src/telemetry/sink.rs b/skippy/crates/skippy-serving/src/telemetry/sink.rs new file mode 100644 index 0000000000..25a3694d32 --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/sink.rs @@ -0,0 +1,285 @@ +//! Where telemetry goes. `Telemetry` says what happened, as it happens; each +//! sink decides what to do with it. A sink that only wants finished spans +//! (OTLP) ignores the live calls; one that must act at the moment a span +//! begins on a thread (Tracy, whose zones cannot be backdated) acts in +//! `create_span_with` and `end_span`. + +use std::{any::Any, collections::BTreeMap, time::Duration}; + +use opentelemetry_proto::tonic::metrics::v1::Metric; +use serde_json::Value; + +use super::{ + active_span::SpanLevel, + trace_context::{Frame, SpanContext, SpanEvent}, +}; + +/// A finished span, placed in the process trace. +#[derive(Clone)] +pub(crate) struct SpanRecord { + pub(crate) context: SpanContext, + pub(crate) parent: Option<[u8; 8]>, + pub(crate) name: String, + pub(crate) attributes: BTreeMap, + pub(crate) start_time_unix_nanos: u64, + pub(crate) end_time_unix_nanos: u64, + pub(crate) links: Vec, + pub(crate) events: Vec, +} + +impl SpanRecord { + pub(crate) fn of_frame( + frame: &Frame, + name: &str, + attributes: BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + ) -> Self { + Self { + context: frame.context(), + parent: frame.parent_span_id(), + name: name.to_string(), + attributes, + start_time_unix_nanos, + end_time_unix_nanos: end_time_unix_nanos.max(start_time_unix_nanos.saturating_add(1)), + links: Vec::new(), + events: Vec::new(), + } + } +} + +/// A span that has just begun on the calling thread. Its attributes, links +/// and events arrive with the [`SpanRecord`] at `end_span`. +// Read by sinks that act on live spans, which is the Tracy sink. +#[cfg_attr(not(feature = "tracy"), allow(dead_code))] +pub(crate) struct SpanStart { + pub(crate) name: &'static str, + pub(crate) level: SpanLevel, + pub(crate) context: SpanContext, + pub(crate) parent: Option<[u8; 8]>, + pub(crate) start_time_unix_nanos: u64, +} + +/// What a sink keeps from a span's start to its end. A sink whose state is +/// bound to the starting thread keeps it there, keyed by the span id, since +/// `end_span` may run on another thread. +pub(crate) struct OpenSpan(Option>); + +// Kept by sinks that act on live spans, which is the Tracy sink. +#[cfg_attr(not(feature = "tracy"), allow(dead_code))] +impl OpenSpan { + pub(crate) const NONE: Self = Self(None); + + pub(crate) fn keep(state: impl Any + Send) -> Self { + Self(Some(Box::new(state))) + } + + pub(crate) fn take(self) -> Option { + self.0 + .and_then(|state| state.downcast::().ok()) + .map(|state| *state) + } +} + +pub(crate) trait TraceSink: Send + Sync { + /// A span begins now, on this thread. What is returned comes back to + /// `end_span`. + fn create_span_with(&self, span: &SpanStart) -> OpenSpan; + + /// The span `create_span_with` saw ends, with everything learnt about it. + fn end_span(&self, open: OpenSpan, span: &SpanRecord); + + /// The span `create_span_with` saw turned out to do no work and is not + /// kept; a sink that already shows it closes it here. + fn discard_span(&self, open: OpenSpan); + + /// A span measured elsewhere, on its own clock: a native call, a GPU + /// command, a span that ended after its frame was gone. + fn record_span(&self, span: &SpanRecord); + + /// A point event, as it happens, on the frame it belongs to. + fn record_event(&self, event: &SpanEvent, frame: &Frame); + + /// One sample of the process: CPU, GPU, memory, scheduler and KV gauges, + /// taken together at one instant. + fn record_metrics(&self, metrics: &[Metric]); + + /// Whether events are also wanted folded into their span's record, the + /// OTLP shape; a sink that keeps its own line per event says no. + fn folds_events_into_spans(&self) -> bool; + + /// Block until what was queued has left the process, or `timeout` passes. + fn flush(&self, timeout: Duration); +} + +/// Test-only emission shape handed to sibling-module tests. +#[cfg(test)] +pub(crate) struct CapturedEvent { + pub event: String, + pub attributes: BTreeMap, + pub start_time_unix_nanos: u64, + pub end_time_unix_nanos: u64, + /// The exported span's identity and parent; `None` for a point event. + pub span: Option<(SpanContext, Option<[u8; 8]>)>, +} + +/// Test-only: hands every emission to an in-process receiver, so tests +/// assert exact emissions and level gating without a collector or stderr. +#[cfg(test)] +pub(crate) struct CaptureSink { + tx: std::sync::mpsc::SyncSender, +} + +#[cfg(test)] +impl CaptureSink { + pub(crate) fn channel() -> (Self, std::sync::mpsc::Receiver) { + let (tx, rx) = std::sync::mpsc::sync_channel(256); + (Self { tx }, rx) + } +} + +#[cfg(test)] +impl TraceSink for CaptureSink { + fn create_span_with(&self, _: &SpanStart) -> OpenSpan { + OpenSpan::NONE + } + + fn end_span(&self, _: OpenSpan, span: &SpanRecord) { + self.record_span(span); + } + + fn discard_span(&self, _: OpenSpan) {} + + fn record_span(&self, span: &SpanRecord) { + let _ = self.tx.try_send(CapturedEvent { + event: span.name.clone(), + attributes: span.attributes.clone(), + start_time_unix_nanos: span.start_time_unix_nanos, + end_time_unix_nanos: span.end_time_unix_nanos, + span: Some((span.context, span.parent)), + }); + } + + fn record_event(&self, event: &SpanEvent, _: &Frame) { + let _ = self.tx.try_send(CapturedEvent { + event: event.name.clone(), + attributes: event.attributes.clone(), + start_time_unix_nanos: event.time_unix_nanos, + end_time_unix_nanos: event.time_unix_nanos + 1, + span: None, + }); + } + + fn record_metrics(&self, _: &[Metric]) {} + + fn folds_events_into_spans(&self) -> bool { + false + } + + fn flush(&self, _: Duration) {} +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use super::*; + use crate::telemetry::{ + Telemetry, TelemetryCounters, TelemetryLevel, active_span::ActiveSpan, + capture_stage_config, trace_context, + }; + + #[test] + fn an_open_span_returns_what_the_sink_kept() { + assert_eq!(OpenSpan::keep(7_u32).take::(), Some(7)); + assert_eq!(OpenSpan::keep(7_u32).take::(), None); + assert_eq!(OpenSpan::NONE.take::(), None); + } + + /// A sink that acts at both ends of a live span, as Tracy must. + #[derive(Default)] + struct Seen { + started: Mutex)>>, + ended: Mutex)>>, + discarded: Mutex>>, + } + + struct LiveSink(Arc); + + impl TraceSink for LiveSink { + fn create_span_with(&self, span: &SpanStart) -> OpenSpan { + self.0 + .started + .lock() + .unwrap() + .push((span.name, span.level, span.context, span.parent)); + OpenSpan::keep(span.start_time_unix_nanos) + } + + fn end_span(&self, open: OpenSpan, span: &SpanRecord) { + self.0.ended.lock().unwrap().push(( + span.name.clone(), + span.context, + open.take::(), + )); + } + + fn discard_span(&self, open: OpenSpan) { + self.0.discarded.lock().unwrap().push(open.take::()); + } + + fn record_span(&self, _: &SpanRecord) {} + + fn record_event(&self, _: &SpanEvent, _: &Frame) {} + + fn record_metrics(&self, _: &[Metric]) {} + + fn folds_events_into_spans(&self) -> bool { + false + } + + fn flush(&self, _: Duration) {} + } + + #[test] + fn a_live_span_reaches_its_sink_at_both_ends() { + let seen = Arc::new(Seen::default()); + let telemetry = Telemetry::with_sinks( + vec![Box::new(LiveSink(seen.clone()))], + Arc::new(TelemetryCounters::default()), + Arc::new(capture_stage_config()), + TelemetryLevel::Summary, + ); + let root = trace_context::process().root().context(); + + let span = ActiveSpan::start(Some(&telemetry), "stage.kept", SpanLevel::Summary); + let kept = span.frame().context(); + span.end(); + let span = ActiveSpan::start(Some(&telemetry), "stage.dropped", SpanLevel::Summary); + let dropped = span.frame().context(); + span.discard(); + ActiveSpan::start(Some(&telemetry), "stage.unrecorded", SpanLevel::Debug).end(); + + let started = seen.started.lock().unwrap(); + assert_eq!(started.len(), 2, "an unrecorded span never reaches a sink"); + assert_eq!( + started[0], + ("stage.kept", SpanLevel::Summary, kept, Some(root.span_id)) + ); + assert_eq!(started[1].2, dropped); + let ended = seen.ended.lock().unwrap(); + assert_eq!(ended.len(), 1); + assert_eq!(ended[0].0, "stage.kept"); + assert_eq!(ended[0].1, kept); + assert!( + ended[0].2.is_some(), + "what the sink kept comes back at the end" + ); + let discarded = seen.discarded.lock().unwrap(); + assert_eq!(discarded.len(), 1); + assert!( + discarded[0].is_some(), + "a discarded span returns what was kept too" + ); + } +} diff --git a/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs b/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs index 517f15b1a1..8c3f7927fa 100644 --- a/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs +++ b/skippy/crates/skippy-serving/src/telemetry/stderr_sink.rs @@ -5,13 +5,21 @@ use std::{ collections::BTreeMap, env, io::{BufWriter, Write}, - sync::{OnceLock, mpsc as std_mpsc}, + sync::{Arc, OnceLock, atomic::Ordering, mpsc as std_mpsc}, thread::{self, JoinHandle}, + time::Duration, }; +use opentelemetry_proto::tonic::metrics::v1::Metric; use serde::Serialize; use serde_json::Value; +use super::{ + TelemetryCounters, + sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}, + trace_context::{Frame, SpanEvent}, +}; + static STDERR_SINK: OnceLock = OnceLock::new(); /// Whether the stderr debug sink is enabled via `SKIPPY_TELEMETRY_STDERR`. /// @@ -86,6 +94,78 @@ impl Drop for StderrTelemetrySink { } } +/// The stderr writer as a trace sink: one line per span and per event. +pub(super) struct StderrTraceSink { + sink: StderrTelemetrySink, + stats: Arc, +} + +impl StderrTraceSink { + pub(super) fn enabled(capacity: usize, stats: Arc) -> Option { + stderr_sink_enabled() + .then(|| StderrTelemetrySink::new(capacity)) + .flatten() + .map(|sink| Self { sink, stats }) + } + + fn line( + &self, + name: &str, + attributes: &BTreeMap, + start_time_unix_nanos: u64, + end_time_unix_nanos: u64, + ) { + if !self.sink.try_send(StderrTelemetryEvent { + event: name.to_string(), + attributes: attributes.clone(), + start_time_unix_nanos, + end_time_unix_nanos, + }) { + self.stats.dropped.fetch_add(1, Ordering::Relaxed); + } + } +} + +impl TraceSink for StderrTraceSink { + fn create_span_with(&self, _: &SpanStart) -> OpenSpan { + OpenSpan::NONE + } + + fn end_span(&self, _: OpenSpan, span: &SpanRecord) { + self.record_span(span); + } + + fn discard_span(&self, _: OpenSpan) {} + + fn record_span(&self, span: &SpanRecord) { + self.line( + &span.name, + &span.attributes, + span.start_time_unix_nanos, + span.end_time_unix_nanos, + ); + } + + fn record_event(&self, event: &SpanEvent, _: &Frame) { + self.line( + &event.name, + &event.attributes, + event.time_unix_nanos, + event.time_unix_nanos + 1, + ); + } + + /// Samples are not lines. + fn record_metrics(&self, _: &[Metric]) {} + + fn folds_events_into_spans(&self) -> bool { + false + } + + /// Lines are best effort; shutdown never waited on them. + fn flush(&self, _: Duration) {} +} + fn stderr_telemetry_loop(rx: std_mpsc::Receiver) { while let Ok(event) = rx.recv() { let stderr = std::io::stderr(); diff --git a/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs b/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs new file mode 100644 index 0000000000..07437d908b --- /dev/null +++ b/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs @@ -0,0 +1,518 @@ +//! Tracy as a trace sink: build with `--features tracy`, set +//! `SKIPPY_TELEMETRY_TRACY=1`, and connect a Tracy profiler from this +//! machine; nothing is recorded until one connects. +//! +//! Tracy stamps time only when it is told, so this sink acts at both ends of +//! a live span. Every span runs on a Tracy fiber, which any thread may resume, +//! so a span may end on a thread other than the one it began on: a request's +//! spans share a lane taken for that request (`request-N`, returned when the +//! request ends) and every other span runs on a lane named after the thread +//! that began it. Metal command execution becomes GPU zones in a context +//! whose clock is Unix nanoseconds, process samples and resource snapshots +//! become plots, a span's own resource window becomes its zone text, and +//! other events become messages. + +use std::{ + collections::{BTreeMap, HashMap}, + env, + ffi::{CStr, CString}, + sync::Mutex, + thread::{self, ThreadId}, + time::Duration, +}; + +use opentelemetry_proto::tonic::metrics::v1::{Metric, metric, number_data_point}; +use serde_json::Value; +use tracy_client::{Client, GpuContext, GpuContextType, PlotName, sys}; + +use super::{ + now_unix_nanos, + sink::{OpenSpan, SpanRecord, SpanStart, TraceSink}, + trace_context::{Frame, SpanEvent}, +}; + +const ENV: &str = "SKIPPY_TELEMETRY_TRACY"; +const REQUEST_ROOT: &str = "stage.openai_http_request"; +const RESOURCES_EVENT: &str = "skippy.resources"; +const RESOURCES_PREFIX: &str = "skippy.resources."; +const KV_CELLS: &str = "skippy.kv.used_cells"; +const SPAN_WINDOW_PREFIX: &str = "skippy.span."; +const GPU_EXECUTE_SUFFIX: &str = ".execute"; + +/// Whether `SKIPPY_TELEMETRY_TRACY` asks for this sink. +pub(super) fn tracy_enabled() -> bool { + enabled_from_value(env::var(ENV).ok().as_deref()) +} + +fn enabled_from_value(value: Option<&str>) -> bool { + value.is_some_and(|value| { + !matches!( + value.trim().to_ascii_lowercase().as_str(), + "" | "0" | "false" | "no" | "off" + ) + }) +} + +/// A Tracy fiber. Tracy knows a fiber by its name's address, so the name +/// lives as long as the process. +#[derive(Clone, Copy)] +struct Lane(&'static CStr); + +impl Lane { + fn named(name: String) -> Self { + Self(Box::leak( + CString::new(name).unwrap_or_default().into_boxed_c_str(), + )) + } + + /// Run `act` with this lane as the calling thread's current fiber. + fn resume(self, act: impl FnOnce()) { + // SAFETY: the name outlives the process; enter and leave pair on this thread. + unsafe { sys::___tracy_fiber_enter(self.0.as_ptr()) }; + act(); + unsafe { sys::___tracy_fiber_leave() }; + } +} + +#[derive(Default)] +struct Lanes { + /// The lane each live span runs on, by span id. + by_span: HashMap<[u8; 8], Lane>, + by_thread: HashMap, + free_requests: Vec, + requests_made: usize, +} + +impl Lanes { + /// A child joins its parent's lane; a request root takes a request + /// lane; anything else runs on the lane of the thread that began it. + fn assign(&mut self, span: &SpanStart) -> Lane { + let parent_lane = span + .parent + .and_then(|parent| self.by_span.get(&parent).copied()); + let lane = match parent_lane { + Some(lane) => lane, + None if span.name == REQUEST_ROOT => self.request_lane(), + None => self.thread_lane(), + }; + self.by_span.insert(span.context.span_id, lane); + lane + } + + fn request_lane(&mut self) -> Lane { + self.free_requests.pop().unwrap_or_else(|| { + let lane = Lane::named(format!("request-{}", self.requests_made)); + self.requests_made += 1; + lane + }) + } + + fn thread_lane(&mut self) -> Lane { + let thread = thread::current(); + *self.by_thread.entry(thread.id()).or_insert_with(|| { + Lane::named(format!( + "{} {:?}", + thread.name().unwrap_or("thread"), + thread.id() + )) + }) + } + + /// Forget a span that ended; a request root hands its lane back. + fn release(&mut self, span_id: [u8; 8], name: &str) { + if let Some(lane) = self.by_span.remove(&span_id) + && name == REQUEST_ROOT + { + self.free_requests.push(lane); + } + } +} + +/// What the sink keeps while a span is live. +struct Open { + zone: sys::___tracy_c_zone_context, + lane: Lane, +} + +pub(super) struct TracySink { + client: Client, + lanes: Mutex, + plots: Mutex>, + /// Metal execution, timed in Unix nanoseconds like every span here. + gpu: Option, +} + +impl TracySink { + pub(super) fn enabled() -> Option { + tracy_enabled().then(Self::start) + } + + fn start() -> Self { + let client = Client::start(); + let gpu = client + .clone() + .new_gpu_context( + Some("metal"), + GpuContextType::Invalid, + now_unix_nanos(), + 1.0, + ) + .ok(); + Self { + client, + lanes: Mutex::new(Lanes::default()), + plots: Mutex::new(HashMap::new()), + gpu, + } + } + + fn lanes(&self) -> std::sync::MutexGuard<'_, Lanes> { + self.lanes + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn zone_begin(name: &str) -> sys::___tracy_c_zone_context { + // SAFETY: Tracy copies the location strings; the zone is active (1). + unsafe { + let location = sys::___tracy_alloc_srcloc_name( + 0, + c"".as_ptr(), + 0, + name.as_ptr().cast(), + name.len(), + name.as_ptr().cast(), + name.len(), + 0, + ); + sys::___tracy_emit_zone_begin_alloc(location, 1) + } + } + + fn zone_end(zone: sys::___tracy_c_zone_context) { + // SAFETY: `zone` came from `zone_begin` and ends once, on its lane. + unsafe { sys::___tracy_emit_zone_end(zone) }; + } + + fn zone_text(zone: sys::___tracy_c_zone_context, text: &str) { + // SAFETY: Tracy copies the text; the zone is still open on its lane. + unsafe { sys::___tracy_emit_zone_text(zone, text.as_ptr().cast(), text.len()) }; + } + + fn close(&self, open: OpenSpan, span: &SpanRecord) { + let Some(open) = open.take::() else { + return; + }; + let window = span_window_text(&span.attributes); + open.lane.resume(|| { + if let Some(text) = window.as_deref() { + Self::zone_text(open.zone, text); + } + Self::zone_end(open.zone); + }); + self.lanes().release(span.context.span_id, &span.name); + } + + fn plot(&self, name: &str, value: f64) { + let plot = *self + .plots + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .entry(name.to_string()) + .or_insert_with(|| PlotName::new_leak(name.to_string())); + self.client.plot(plot, value); + } + + /// Plot every number under `prefix`, named without it. + fn plot_numbers(&self, prefix: &str, attributes: &BTreeMap) { + attributes + .iter() + .filter_map(|(key, value)| Some((key.strip_prefix(prefix)?, value.as_f64()?))) + .for_each(|(name, value)| self.plot(name, value)); + } + + /// A span whose GPU execution window is already known, as a GPU zone. + fn gpu_zone(&self, span: &SpanRecord) { + let Some(gpu) = self.gpu.as_ref() else { + return; + }; + let Ok(mut zone) = gpu.span_alloc(&span.name, "", "", 0) else { + return; + }; + zone.end_zone(); + zone.upload_timestamp_start(span.start_time_unix_nanos as i64); + zone.upload_timestamp_end(span.end_time_unix_nanos as i64); + } +} + +impl TraceSink for TracySink { + fn create_span_with(&self, span: &SpanStart) -> OpenSpan { + let lane = self.lanes().assign(span); + let mut zone = None; + lane.resume(|| zone = Some(Self::zone_begin(span.name))); + zone.map_or(OpenSpan::NONE, |zone| OpenSpan::keep(Open { zone, lane })) + } + + fn end_span(&self, open: OpenSpan, span: &SpanRecord) { + self.close(open, span); + if let Some(cells) = span.attributes.get(KV_CELLS).and_then(Value::as_f64) { + self.plot("kv.used_cells", cells); + } + } + + fn discard_span(&self, open: OpenSpan) { + if let Some(open) = open.take::() { + open.lane.resume(|| Self::zone_end(open.zone)); + } + } + + /// Only Metal execution is shown after the fact; native call spans are + /// nested, which a GPU context cannot take out of order. + fn record_span(&self, span: &SpanRecord) { + if span.name.ends_with(GPU_EXECUTE_SUFFIX) { + self.gpu_zone(span); + } + } + + fn record_event(&self, event: &SpanEvent, _: &Frame) { + if event.name == RESOURCES_EVENT { + self.plot_numbers(RESOURCES_PREFIX, &event.attributes); + } else { + self.client.message(&event.name, 0); + } + } + + /// Every gauge point becomes a plot, named by the metric and the point's + /// attributes (`skippy.gpu.busy{device=MTL0}`), one curve per series. + fn record_metrics(&self, metrics: &[Metric]) { + metrics + .iter() + .flat_map(|metric| { + gauge_points(metric) + .map(move |(series, value)| (plot_name(&metric.name, &series), value)) + }) + .for_each(|(name, value)| self.plot(&name, value)); + } + + fn folds_events_into_spans(&self) -> bool { + false + } + + /// Tracy streams as it goes; there is no queue to wait on. + fn flush(&self, _: Duration) {} +} + +/// A span's own resource window (`skippy.span.*`), as one line of zone text. +fn span_window_text(attributes: &BTreeMap) -> Option { + let parts = attributes + .iter() + .filter_map(|(key, value)| Some((key.strip_prefix(SPAN_WINDOW_PREFIX)?, value.as_f64()?))) + .map(|(name, value)| format!("{name} {value:.2}")) + .collect::>(); + (!parts.is_empty()).then(|| parts.join(" ")) +} + +/// The number points of a gauge, each with its attributes as `key=value`. +fn gauge_points(metric: &Metric) -> impl Iterator, f64)> + '_ { + let points = match metric.data.as_ref() { + Some(metric::Data::Gauge(gauge)) => gauge.data_points.as_slice(), + _ => &[], + }; + points.iter().filter_map(|point| { + let value = match point.value.as_ref()? { + number_data_point::Value::AsDouble(value) => *value, + number_data_point::Value::AsInt(value) => *value as f64, + }; + let series = point + .attributes + .iter() + .map(|attribute| { + let value = attribute + .value + .as_ref() + .and_then(|value| value.value.as_ref()) + .map_or_else(String::new, |value| match value { + opentelemetry_proto::tonic::common::v1::any_value::Value::StringValue( + text, + ) => text.clone(), + other => format!("{other:?}"), + }); + format!("{}={value}", attribute.key) + }) + .collect(); + Some((series, value)) + }) +} + +fn plot_name(metric: &str, series: &[String]) -> String { + if series.is_empty() { + metric.to_string() + } else { + format!("{metric}{{{}}}", series.join(",")) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use opentelemetry_proto::tonic::{ + common::v1::{AnyValue, KeyValue, any_value}, + metrics::v1::{Gauge, NumberDataPoint}, + }; + use serde_json::json; + + use super::*; + use crate::telemetry::{ + Telemetry, TelemetryCounters, TelemetryLevel, + active_span::{ActiveSpan, SpanLevel}, + capture_stage_config, + trace_context::SpanContext, + }; + + fn start(name: &'static str, span_id: u8, parent: Option) -> SpanStart { + SpanStart { + name, + level: SpanLevel::Summary, + context: SpanContext { + trace_id: [1; 16], + span_id: [span_id; 8], + }, + parent: parent.map(|parent| [parent; 8]), + start_time_unix_nanos: 1, + } + } + + #[test] + fn a_request_and_its_children_share_a_lane_that_is_reused_after_it_ends() { + let mut lanes = Lanes::default(); + let request = lanes.assign(&start(REQUEST_ROOT, 1, None)); + let child = lanes.assign(&start("stage.openai_prefill", 2, Some(1))); + let worker = lanes.assign(&start("stage.scheduler_feature_iteration", 3, None)); + assert!(std::ptr::eq(request.0, child.0)); + assert!(!std::ptr::eq(request.0, worker.0)); + assert_eq!(lanes.requests_made, 1); + + lanes.release([2; 8], "stage.openai_prefill"); + lanes.release([1; 8], REQUEST_ROOT); + let next = lanes.assign(&start(REQUEST_ROOT, 4, None)); + assert!( + std::ptr::eq(request.0, next.0), + "a freed request lane is taken again" + ); + assert_eq!(lanes.requests_made, 1); + } + + #[test] + fn two_live_requests_take_two_lanes() { + let mut lanes = Lanes::default(); + let first = lanes.assign(&start(REQUEST_ROOT, 1, None)); + let second = lanes.assign(&start(REQUEST_ROOT, 2, None)); + assert!(!std::ptr::eq(first.0, second.0)); + assert_eq!(lanes.requests_made, 2); + } + + /// The real client, with no profiler attached: every call must be safe + /// to make, from any thread, in any order the span API allows. + #[test] + fn spans_begin_and_end_on_any_thread_through_the_real_client() { + let telemetry = Telemetry::with_sinks( + vec![Box::new(TracySink::start())], + Arc::new(TelemetryCounters::default()), + Arc::new(capture_stage_config()), + TelemetryLevel::Debug, + ); + let request = ActiveSpan::start(Some(&telemetry), REQUEST_ROOT, SpanLevel::Summary); + let child = { + let _request = request.enter(); + ActiveSpan::start(Some(&telemetry), "stage.openai_prefill", SpanLevel::Debug) + }; + let worker = ActiveSpan::start_under_process( + Some(&telemetry), + "stage.scheduler_feature_iteration", + SpanLevel::Debug, + ); + telemetry.emit( + RESOURCES_EVENT, + BTreeMap::from([( + format!("{RESOURCES_PREFIX}process.footprint_bytes"), + json!(1_u64 << 30), + )]), + ); + telemetry.emit("skippy.kv.lookup", BTreeMap::new()); + telemetry.emit_debug_span("mtl.execute", BTreeMap::new(), 10, 20); + let mut worker = worker; + worker.extend_attributes([(KV_CELLS.to_string(), json!(512))]); + worker.end(); + thread::spawn(move || { + child.end(); + request.end(); + }) + .join() + .expect("spans end on another thread"); + ActiveSpan::start(Some(&telemetry), "stage.nothing", SpanLevel::Summary).discard(); + assert!(telemetry.sinks.len() == 1); + } + + fn point(value: f64, attributes: &[(&str, &str)]) -> NumberDataPoint { + NumberDataPoint { + attributes: attributes + .iter() + .map(|(key, value)| KeyValue { + key: (*key).to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue((*value).to_string())), + }), + ..Default::default() + }) + .collect(), + value: Some(number_data_point::Value::AsDouble(value)), + ..Default::default() + } + } + + #[test] + fn a_gauge_point_is_a_plot_named_by_its_series() { + let metric = Metric { + name: "skippy.gpu.busy".to_string(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![point(0.5, &[("device", "MTL0")]), point(0.25, &[])], + })), + ..Default::default() + }; + let plots = gauge_points(&metric) + .map(|(series, value)| (plot_name(&metric.name, &series), value)) + .collect::>(); + assert_eq!( + plots, + vec![ + ("skippy.gpu.busy{device=MTL0}".to_string(), 0.5), + ("skippy.gpu.busy".to_string(), 0.25), + ] + ); + } + + #[test] + fn a_span_window_becomes_one_line_of_text() { + let attributes = BTreeMap::from([ + ("skippy.span.cpu_ms".to_string(), json!(1.25)), + ("skippy.span.gpu_execute_ms".to_string(), json!(8.0)), + ("skippy.other".to_string(), json!(3)), + ]); + assert_eq!( + span_window_text(&attributes).as_deref(), + Some("cpu_ms 1.25 gpu_execute_ms 8.00") + ); + assert_eq!(span_window_text(&BTreeMap::new()), None); + } + + #[test] + fn the_variable_must_be_set_and_truthy() { + assert!(enabled_from_value(Some("1"))); + assert!(enabled_from_value(Some("yes"))); + assert!(!enabled_from_value(Some("0"))); + assert!(!enabled_from_value(Some(" off "))); + assert!(!enabled_from_value(Some(""))); + assert!(!enabled_from_value(None)); + } +} diff --git a/skippy/docs/PROMPT_CACHE.md b/skippy/docs/PROMPT_CACHE.md index 543ebf5648..63a7ec87af 100644 --- a/skippy/docs/PROMPT_CACHE.md +++ b/skippy/docs/PROMPT_CACHE.md @@ -90,6 +90,27 @@ budget merely because it is the last entry. Standalone budget. A zero/unset value selects the bounded 1 GiB native-cache default; disable prefix caching itself to retain no entries. +## Admission + +Prefix lookup and restore run as one cache operation under the runtime lock. +`kv_cache.prefill_admission` decides who prefills the rest of the prompt: + +- `cooperative` (default): the operation restores the prefix only. The suffix + is submitted as iteration batches, chunked at `n_ubatch`, which coalesce + with other requests' prompt chunks and with decode rows in the same native + step. Four prompts arriving together prefill as one wave, and running + requests keep decoding between chunks. +- `serialized`: the operation prefills the whole prompt itself. One prompt + enters at a time and every other request's decode waits for it. This was + the implicit behaviour for attention models before the policy existed; keep + it for a runtime whose cache operation must capture state mid-prompt. + +`SKIPPY_PREFILL_ADMISSION=serialized|cooperative` overrides the configured +policy for a benchmark or an incident without a replan. Whether a step mixed +prompt chunks with decode rows is visible per native batch on the +`stage.scheduler_feature_iteration` span (`skippy.scheduler.batch_size`, +`skippy.scheduler.token_count`). + ## Persistence boundary The resident path does not eagerly export complete KV state into a blob store diff --git a/skippy/docs/SERVING_SETTINGS.md b/skippy/docs/SERVING_SETTINGS.md index bc3d48c6b8..7b54703e33 100644 --- a/skippy/docs/SERVING_SETTINGS.md +++ b/skippy/docs/SERVING_SETTINGS.md @@ -214,6 +214,10 @@ with their runtime purpose; existing controls follow in the same sections. | `--kv-cache-offload` | `kv_cache_offload` | Offload live KV memory to the backend | | `--swa-full` | `swa_full` | Use a full cache window for sliding-window attention | | `--cache-idle-slots` | `cache_idle_slots` | Maximum retained idle sessions; zero retains none | +| `--kv-pool-tokens` | `kv_pool_tokens` | Cells in the KV pool the lanes share, at least ctx-size; unset reserves ctx-size for every lane | +| `--kv-lazy-clear` | `kv_lazy_clear` | Zero KV cells as they are first used instead of all at load | +| `--kv-release-pages` | `kv_release_pages` | Return the memory of freed KV cells to the system | +| `--kv-row-attention` | `kv_row_attention` | Read the shared KV pool through per-request row lists where the backend supports them | | `--ctx-size` | `ctx_size` | See `skippy serve --help` for values and defaults. | ### [cache] @@ -228,6 +232,8 @@ with their runtime purpose; existing controls follow in the same sections. | `--prefix-cache-min-tokens` | `prefix_cache_min_tokens` | Minimum prefix length to record or reuse | | `--prefix-cache-stride-tokens` | `prefix_cache_stride_tokens` | Shared-prefix checkpoint spacing in tokens | | `--prefix-cache-record-limit` | `prefix_cache_record_limit` | Maximum shared-prefix checkpoints per recording | +| `--prefix-cache-retention-tokens` | `prefix_cache_retention_tokens` | KV cells finished requests keep resident for reuse: a token count or unbounded | +| `--prefill-admission` | `prefill_admission` | How a prompt's uncached suffix is prefilled: cooperative or serialized | | `--prefix-cache-exact-budget` | `prefix_cache_exact_budget` | Exact-state retention ceiling: auto, unbounded, or IEC size; one snapshot may exceed it | | `--kv-cache-disk` | `kv_cache_disk` | See `skippy serve --help` for values and defaults. | | `--kv-cache-disk-dir` | `kv_cache_disk_dir` | See `skippy serve --help` for values and defaults. | @@ -239,6 +245,7 @@ with their runtime purpose; existing controls follow in the same sections. |---|---|---| | `--continuous-batching` | `continuous_batching` | Allow the iteration scheduler to serve concurrent lanes | | `--pipeline-decode-groups` | `pipeline_decode_groups` | Number of decode dispatch groups | +| `--prefill-coalesce-max-ms` | `prefill_coalesce_max_ms` | Longest a prompt waits for others to join its prefill wave, in milliseconds; zero never waits | | `--generation-signal-window` | `generation_signal_window` | Generation signal observation window in tokens | | `--generation-concurrency` | `generation_concurrency` | See `skippy serve --help` for values and defaults. | | `--adaptive-generation-concurrency` | `adaptive_generation_concurrency` | See `skippy serve --help` for values and defaults. | diff --git a/skippy/docs/TELEMETRY_EVENTS.md b/skippy/docs/TELEMETRY_EVENTS.md index 3a289e0a6e..4732b76b05 100644 --- a/skippy/docs/TELEMETRY_EVENTS.md +++ b/skippy/docs/TELEMETRY_EVENTS.md @@ -95,10 +95,26 @@ which kernels run and how much KV they read, as resource attributes: `skippy.kv.swa_full`. The path attention actually took is the `skippy.attention.path` event and span attribute. +Six more resource attributes let one collector compare runs across machines, +backends and commits, the same keys on Skippy and on an instrumented +llama-server: + +| Attribute | Value | +|---|---| +| `run.id` | the stage's run id, one per launch | +| `backend.name` | the backend the runtime computes on, as GPU command spans name it (`MTL`, `CUDA`); set once the runtime has made a traced native call, so startup spans carry none | +| `test.name` | the workload, set by the operator so the same test compares across runs | +| `git.commit.sha` | the commit skippy-serving was built from (`SKIPPY_GIT_COMMIT` at build time overrides the repository's `HEAD`; `unknown` outside a repository) | +| `machine.id` | the host name unless the operator sets it | +| `run.phase` | `warmup` or `measured`; `measured` unless the operator sets it | + `OTEL_RESOURCE_ATTRIBUTES` adds the operator's own resource attributes, as OpenTelemetry SDKs define it: comma-separated `key=value` pairs with -percent-encoded values, such as `skippy.run.label=q8-fa`. The stage's own -attributes win over a conflicting key. +percent-encoded values, such as +`skippy.run.label=q8-fa,test.name=benchy-pp512-tg128-d0_4096-c4,run.phase=warmup`. +It sets `test.name`, `run.phase` and `machine.id`; the stage's own attributes, +including `run.id`, `backend.name` and `git.commit.sha`, win over a +conflicting key. The configurations worth comparing are operator settings: K and V precision (`--kv-cache-type-k`, `--kv-cache-type-v`: `f16`, `q8_0`, `q4_0`; quantized V diff --git a/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch b/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch new file mode 100644 index 0000000000..5489327c7b --- /dev/null +++ b/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch @@ -0,0 +1,2226 @@ +From cac83ac7689cb1b62d8242b498ea7c0307ee2b19 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Tue, 10 Nov 2026 21:00:00 +1100 +Subject: [PATCH 17/32] skippy: restore resident prefixes as shared cells plus + recurrent checkpoints + +The move to the new llama.cpp pin rebuilt the native queue from an older +snapshot and lost the resident-prefix module the Rust side is built against: +skippy_session_export_resident_kv_page, +skippy_session_export_resident_recurrent_state and +skippy_session_resident_prefix_bytes no longer existed, so a runtime built +from the queue failed to load, and hybrid and recurrent models lost resident +prefixes altogether. + +This brings src/skippy/resident_prefix.cpp back as James Dumay left it on +the previous pin. A saved prefix keeps its attention cells in the shared pool under a +cache-owned sequence id; only the fixed-size recurrent state is copied, into +a checkpoint the cache owns, serialized with upstream's host writer +(llama_io_write_host_create). Restores share the retained cells and rebuild a +private recurrent row. The save, restore, create-from-prefix, drop, used +cells and recurrent export/import entry points move back from state.cpp, and +the model again keeps checkpoints per cache sequence rather than one token +list per lane. + +The memory cache capabilities report SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION +and SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT again, recurrent and hybrid +memories advertise resident prefixes, and a non-unified context advertises +none. A model opens with a unified pool even with one lane, so cache-owned +sequence ids share it. + +skippy-sampling-history regains its resident mode, the long GPU checkpoint +proof and the host-writer regression, merged with the verify-window and +exact-checkpoint cases the new pin added. + +ABI inventory (backward compatibility with older runtimes is not kept; the +Rust mirror changes in lockstep): +- added: skippy_session_export_resident_kv_page, + skippy_session_export_resident_recurrent_state, + skippy_session_resident_prefix_bytes (include/skippy/state.h, + src/skippy/resident_prefix.cpp) +- added: SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT (1 << 3), + SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION (1 << 4) +- removed: none + +Bumps the Skippy ABI from 0.1.70 to 0.1.71; the model-support lane's bumps +follow from there. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + include/skippy/common.h | 2 +- + include/skippy/runtime.h | 2 +- + include/skippy/state.h | 46 +- + src/CMakeLists.txt | 10 +- + src/llama-context.cpp | 4 + + src/llama-io.h | 6 + + src/skippy/model_loading.cpp | 6 +- + src/skippy/resident_prefix.cpp | 438 +++++++++++++++++ + src/skippy/runtime_types.h | 13 +- + src/skippy/session.cpp | 22 +- + src/skippy/state.cpp | 443 +----------------- + src/skippy/state_memory.cpp | 21 +- + src/skippy/tests/resident_checkpoint_gpu.cpp | 287 ++++++++++++ + .../tests/resident_checkpoint_writer.cpp | 126 +++++ + src/skippy/tests/sampling_history.cpp | 387 ++++++++++++++- + 15 files changed, 1326 insertions(+), 487 deletions(-) + create mode 100644 src/skippy/resident_prefix.cpp + create mode 100644 src/skippy/tests/resident_checkpoint_gpu.cpp + create mode 100644 src/skippy/tests/resident_checkpoint_writer.cpp + +diff --git a/include/skippy/common.h b/include/skippy/common.h +index 3448095a1..cbba91849 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -46,7 +46,7 @@ extern "C" { + + #define SKIPPY_ABI_VERSION_MAJOR 0 + #define SKIPPY_ABI_VERSION_MINOR 1 +-#define SKIPPY_ABI_VERSION_PATCH 70 ++#define SKIPPY_ABI_VERSION_PATCH 71 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) +diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h +index b570682ef..856c98f97 100644 +--- a/include/skippy/runtime.h ++++ b/include/skippy/runtime.h +@@ -96,7 +96,7 @@ struct skippy_runtime_config { + // Tri-state KV/session controls resolved from `model_fit` config. + /** @brief Whether K/V tensors are offloaded to the compute backend (mirrors upstream `offload_kqv`). */ + int32_t kv_offload; +- /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO derives the setting from lane count; recurrent and hybrid models force it true. */ ++ /** @brief Whether the KV cache is unified across sequences/lanes (mirrors upstream `kv_unified`). AUTO enables unified caching at every lane count. Explicit false selects non-unified caching, except recurrent and hybrid models force it true. */ + int32_t kv_unified; + /** @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`). */ + int32_t swa_full; +diff --git a/include/skippy/state.h b/include/skippy/state.h +index e8d0874a1..6d9028a18 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -17,6 +17,10 @@ enum skippy_memory_cache_capability { + SKIPPY_MEMORY_CACHE_RESIDENT = 1 << 0, + SKIPPY_MEMORY_CACHE_KV_RECURRENT = 1 << 1, + SKIPPY_MEMORY_CACHE_FULL_STATE = 1 << 2, ++ /** Resident prefixes restore only their exact saved recurrent checkpoint boundary. */ ++ SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT = 1 << 3, ++ /** Complete resident prefixes contain attention cells in addition to any recurrent state. */ ++ SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION = 1 << 4, + }; + + /** @brief Returns complete cache representations admitted by the built graph and loaded memory. +@@ -136,7 +140,7 @@ LLAMA_API enum skippy_status skippy_export_full_state( + size_t * out_bytes, + struct skippy_error ** out_error); + +-/** @brief Exports recurrent state for models that maintain recurrent memory. */ ++/** @brief Exports only recurrent memory; attention pages are exported independently. */ + LLAMA_API enum skippy_status skippy_export_recurrent_state( + struct skippy_session * session, + void * output, +@@ -153,7 +157,7 @@ LLAMA_API enum skippy_status skippy_import_full_state( + size_t input_bytes, + struct skippy_error ** out_error); + +-/** @brief Imports recurrent state into a session. */ ++/** @brief Imports recurrent-only state into a session. */ + LLAMA_API enum skippy_status skippy_import_recurrent_state( + struct skippy_session * session, + const void * input, +@@ -217,14 +221,18 @@ LLAMA_API enum skippy_status skippy_import_cachegen_kv_page_v1( + size_t record_count, + struct skippy_error ** out_error); + +-/** @brief Saves a session prefix into a resident cache sequence. */ ++/** @brief Retains shared attention cells and an immutable recurrent checkpoint owned by the cache. ++ * Recurrent memory requires token_count equal to the current session position. ++ */ + LLAMA_API enum skippy_status skippy_session_save_prefix( + struct skippy_session * session, + int32_t cache_seq_id, + uint64_t token_count, + struct skippy_error ** out_error); + +-/** @brief Restores a session prefix from a resident cache sequence. */ ++/** @brief Shares retained attention cells and restores a private mutable recurrent row. ++ * Token identity must match; recurrent prefixes require the exact saved boundary. ++ */ + LLAMA_API enum skippy_status skippy_session_restore_prefix( + struct skippy_session * session, + int32_t cache_seq_id, +@@ -232,6 +240,36 @@ LLAMA_API enum skippy_status skippy_session_restore_prefix( + size_t token_count, + struct skippy_error ** out_error); + ++/** @brief Exports a cache-owned attention page for cold offload without claiming or restoring an execution lane. */ ++LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ int32_t layer_start, ++ int32_t layer_end, ++ uint64_t token_start, ++ uint64_t token_count, ++ struct skippy_kv_page_desc * out_desc, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error); ++ ++/** @brief Copies a cache-owned recurrent-only checkpoint for cold offload; a size query does not read tensors. */ ++LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ void * output, ++ size_t output_capacity, ++ size_t * out_bytes, ++ struct skippy_error ** out_error); ++ ++/** @brief Reports cache-owned recurrent checkpoint and token identity bytes; shared attention cells remain in the native pool. */ ++LLAMA_API enum skippy_status skippy_session_resident_prefix_bytes( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ uint64_t * out_bytes, ++ struct skippy_error ** out_error); ++ + /** @brief Reports physically occupied cells in the session's unified KV cache. */ + LLAMA_API enum skippy_status skippy_session_memory_used_cells( + struct skippy_session * session, +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 4f4fc1cd1..cfd896714 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -89,6 +89,7 @@ add_library(llama + skippy/stage_realization.cpp + skippy/stage_execution_contract.cpp + skippy/state.cpp ++ skippy/resident_prefix.cpp + skippy/state_memory.cpp + skippy/state_effects.cpp + skippy/speculative_decoding.cpp +@@ -434,12 +435,17 @@ if (LLAMA_STAGE_BUILD_TESTS) + add_skippy_verify_rollback_test(qwen4exp qwen4exp-moe.gguf) + # lfm2's fixture slides its attention window, so it checkpoints every window. + add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) +- add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) ++ add_executable(skippy-sampling-history ++ skippy/tests/sampling_history.cpp ++ skippy/tests/resident_checkpoint_gpu.cpp ++ skippy/tests/resident_checkpoint_writer.cpp) + target_include_directories(skippy-sampling-history PRIVATE .) + target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) + target_link_libraries(skippy-sampling-history PRIVATE llama) ++ add_test(NAME skippy_resident_checkpoint_gpu_long COMMAND skippy-sampling-history resident-gpu-long) ++ set_tests_properties(skippy_resident_checkpoint_gpu_long PROPERTIES SKIP_RETURN_CODE 77) + function(add_skippy_sampling_history_tests family fixture state) +- foreach(mode grammar penalty argmax) ++ foreach(mode grammar penalty resident argmax) + add_test(NAME skippy_sampling_history_${family}_${mode} + COMMAND skippy-sampling-history + "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index cb68e7e53..e460d2250 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -3629,6 +3629,10 @@ private: + std::vector winfos; + }; + ++std::unique_ptr llama_io_write_host_create(uint8_t * dst, size_t size) { ++ return std::make_unique(dst, size); ++} ++ + class llama_io_read_host : public llama_io_read_i { + public: + llama_io_read_host(const uint8_t * p, size_t len) : ptr(p), base_ptr(p), buf_size(len) {} +diff --git a/src/llama-io.h b/src/llama-io.h +index 0aca73310..72aa58718 100644 +--- a/src/llama-io.h ++++ b/src/llama-io.h +@@ -2,6 +2,7 @@ + + #include + #include ++#include + #include + + struct ggml_tensor; +@@ -36,3 +37,8 @@ public: + + void read_string(std::string & str); + }; ++ ++// Uses the same host serializer as llama_state_seq_get_data_ext. The caller ++// owns the fixed-size destination and source tensors until writer destruction, ++// which completes the deferred tensor reads before returning. ++std::unique_ptr llama_io_write_host_create(uint8_t * dst, size_t size); +diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp +index db5a69e38..5bfd47c93 100644 +--- a/src/skippy/model_loading.cpp ++++ b/src/skippy/model_loading.cpp +@@ -692,7 +692,8 @@ enum skippy_status skippy_finish_model_open( + params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : params.n_threads; + params.n_seq_max = stage_model->lane_count; +- params.kv_unified = stage_model->lane_count > 1; ++ // Cache-owned sequence IDs share the attention pool even with one lane. ++ params.kv_unified = true; + if (config != nullptr) { + params.kv_unified = skippy_resolve_tristate(config->kv_unified, params.kv_unified); + params.offload_kqv = skippy_resolve_tristate(config->kv_offload, params.offload_kqv); +@@ -878,7 +879,6 @@ enum skippy_status skippy_finish_model_open( + + + stage_model->lane_in_use.assign(stage_model->lane_count, false); +- stage_model->lane_resident_prefix_tokens.resize(stage_model->lane_count); + + const uint64_t native_model_id = reinterpret_cast(stage_model); + if (event_scope != nullptr) { +@@ -1173,7 +1173,7 @@ enum skippy_status skippy_model_attach_mtp_draft_model( + ctx_params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + ctx_params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : ctx_params.n_threads; + ctx_params.n_seq_max = target_model->lane_count; +- ctx_params.kv_unified = target_model->lane_count > 1; ++ ctx_params.kv_unified = true; + if (config != nullptr) { + ctx_params.kv_unified = skippy_resolve_tristate(config->kv_unified, ctx_params.kv_unified); + ctx_params.offload_kqv = skippy_resolve_tristate(config->kv_offload, ctx_params.offload_kqv); +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +new file mode 100644 +index 000000000..317c96b46 +--- /dev/null ++++ b/src/skippy/resident_prefix.cpp +@@ -0,0 +1,438 @@ ++#include "skippy/state.h" ++#include "skippy/state_memory.h" ++#include "skippy/errors.h" ++#include "skippy/runtime_support.h" ++#include "skippy/runtime_types.h" ++#include "skippy-verify-checkpoint.h" ++#include "llama-io.h" ++#include "llama-kv-cache.h" ++#include "llama-kv-cache-iswa.h" ++#include "llama-memory-hybrid.h" ++#include "llama-memory-hybrid-iswa.h" ++#include "llama-memory-recurrent.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace { ++ ++// These adapters cover complete memory objects, not model-family names. Never ++// silently drop auxiliary state belonging to an unknown derived memory type. ++llama_memory_t attention_memory(llama_memory_t memory) { ++ if (auto * hybrid = dynamic_cast(memory)) { ++ return hybrid->get_mem_attn(); ++ } ++ if (auto * hybrid = dynamic_cast(memory)) { ++ return hybrid->get_mem_attn(); ++ } ++ return skippy_memory_recurrent_adapter(memory) ? nullptr : memory; ++} ++ ++skippy_status validate_session(skippy_session * session, int32_t cache_seq_id, ++ skippy_error ** error) { ++ if (!session || !session->ctx || !session->stage_model || !session->ctx->get_memory()) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model-backed session is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (cache_seq_id < static_cast(session->stage_model->lane_count * 2) ++ || cache_seq_id >= LLAMA_MAX_SEQ) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id is outside the resident cache range"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * memory = session->ctx->get_memory(); ++ if (!(skippy_model_memory_cache_capabilities(session->stage_model) & SKIPPY_MEMORY_CACHE_RESIDENT) ++ || (attention_memory(memory) && !session->ctx->get_cparams().kv_unified)) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "memory does not support complete shared resident prefixes"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ return SKIPPY_STATUS_OK; ++} ++ ++// A size query never touches tensor bytes. Export writes directly to the ++// caller's allocation, avoiding an extra full recurrent payload temporary. ++class recurrent_buffer_writer final : public llama_io_write_i { ++public: ++ recurrent_buffer_writer(void * data = nullptr, size_t capacity = 0) ++ : data(static_cast(data)), capacity(capacity) {} ++ void write(const void * source, size_t bytes) override { ++ reserve(bytes); ++ if (data && bytes) { std::memcpy(data + position, source, bytes); } ++ position += bytes; ++ } ++ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ reserve(bytes); ++ if (data && bytes) { ggml_backend_tensor_get(tensor, data + position, offset, bytes); } ++ position += bytes; ++ } ++ size_t n_bytes() override { return position; } ++private: ++ void reserve(size_t bytes) const { ++ if (bytes > std::numeric_limits::max() - position ++ || (data && (position > capacity || bytes > capacity - position))) { ++ throw std::runtime_error("recurrent export buffer is too small"); ++ } ++ } ++ uint8_t * data; ++ size_t capacity; ++ size_t position = 0; ++}; ++ ++class checkpoint_reader final : public llama_io_read_i { ++public: ++ explicit checkpoint_reader(const std::vector & payload) : payload(payload.data()), bytes(payload.size()) {} ++ checkpoint_reader(const uint8_t * payload, size_t bytes) : payload(payload), bytes(bytes) {} ++ void read(void * destination, size_t bytes) override { ++ require(bytes); ++ if (bytes) { std::memcpy(destination, payload + position, bytes); } ++ position += bytes; ++ } ++ void read_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ require(bytes); ++ if (bytes) { ggml_backend_tensor_set(tensor, payload + position, offset, bytes); } ++ position += bytes; ++ } ++ size_t n_bytes() override { return position; } ++private: ++ void require(size_t bytes) const { ++ if (bytes > this->bytes - position) { ++ throw std::runtime_error("resident recurrent checkpoint is truncated"); ++ } ++ } ++ const uint8_t * payload; ++ const size_t bytes; ++ size_t position = 0; ++}; ++ ++skippy_status validate_checkpoint(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ if (count > static_cast(std::numeric_limits::max()) || (count && !tokens)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix tokens are invalid"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto found = checkpoints.find(cache_seq_id); ++ if (found == checkpoints.end() || count > found->second.tokens.size() ++ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) ++ && count != found->second.tokens.size()) ++ || (count && !std::equal(tokens, tokens + count, found->second.tokens.begin()))) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix identity or exact recurrent boundary does not match"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * attention = attention_memory(session->ctx->get_memory()); ++ if (attention && count && attention->seq_pos_max(cache_seq_id) < static_cast(count - 1)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident attention prefix is incomplete"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ return SKIPPY_STATUS_OK; ++} ++ ++skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto status = validate_checkpoint(session, cache_seq_id, tokens, count, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ // Allocate history before clearing live state. Checkpoint bytes stay immutable ++ // while each restoring lane receives its own mutable recurrent row. ++ std::vector history; ++ if (count) { history.assign(tokens, tokens + count); } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ auto * memory = session->ctx->get_memory(); ++ if (!memory->seq_rm(session->seq_id, -1, -1)) { ++ throw std::runtime_error("failed to clear execution lane for resident prefix"); ++ } ++ const auto & checkpoint = session->stage_model->resident_prefixes.at(cache_seq_id); ++ try { ++ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { ++ checkpoint_reader reader(checkpoint.recurrent); ++ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (reader.n_bytes() != checkpoint.recurrent.size()) { ++ throw std::runtime_error("resident recurrent checkpoint has trailing data"); ++ } ++ } ++ if (auto * attention = attention_memory(memory)) { ++ if (count) { attention->seq_cp(cache_seq_id, session->seq_id, 0, static_cast(count)); } ++ } ++ } catch (...) { ++ memory->seq_rm(session->seq_id, -1, -1); ++ session->n_past = 0; ++ session->token_history.clear(); ++ throw; ++ } ++ session->n_past = static_cast(count); ++ session->token_history = std::move(history); ++ session->signal_history.clear(); ++ skippy_mtp_clear_session_state(session); ++ skippy_clear_verify_windows(session); ++ return skippy_success(error); ++} ++ ++skippy_status native_error(skippy_error ** error, const std::exception & exception) { ++ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, exception.what()); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++} ++ ++bool used_attention_cells(llama_memory_t memory, uint64_t * cells) { ++ if (!memory) { *cells = 0; return true; } ++ if (auto * kv = dynamic_cast(memory)) { ++ *cells = kv->get_used_cells(); ++ return true; ++ } ++ if (auto * iswa = dynamic_cast(memory)) { ++ *cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); ++ return true; ++ } ++ return false; ++} ++ ++} // namespace ++ ++extern "C" { ++ ++enum skippy_status skippy_session_save_prefix(skippy_session * session, int32_t cache_seq_id, ++ uint64_t token_count, skippy_error ** error) { ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ if (token_count == 0 || token_count > static_cast(std::max(session->n_past, 0)) ++ || token_count > session->token_history.size() ++ || (skippy_memory_recurrent_adapter(session->ctx->get_memory()) ++ && token_count != static_cast(session->n_past))) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident save requires an available exact checkpoint boundary"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto previous = checkpoints.find(cache_seq_id); ++ if (previous != checkpoints.end()) { ++ if (previous->second.tokens.size() == token_count ++ && std::equal(previous->second.tokens.begin(), previous->second.tokens.end(), session->token_history.begin())) { ++ return skippy_success(error); ++ } ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident cache sequence already owns a different prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ skippy_resident_checkpoint checkpoint; ++ checkpoint.tokens.assign(session->token_history.begin(), session->token_history.begin() + token_count); ++ skippy_synchronize_context_if_pending(session->stage_model); ++ auto * memory = session->ctx->get_memory(); ++ if (auto * recurrent = skippy_memory_recurrent_adapter(memory)) { ++ recurrent_buffer_writer measure; ++ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ checkpoint.recurrent.resize(measure.n_bytes()); ++ auto writer = llama_io_write_host_create(checkpoint.recurrent.data(), checkpoint.recurrent.size()); ++ recurrent->state_write(*writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (writer->n_bytes() != checkpoint.recurrent.size()) { ++ throw std::runtime_error("resident recurrent checkpoint size changed during capture"); ++ } ++ // Upstream's host writer defers tensor reads until destruction. ++ // Finish them while the destination and resident owner are stable, ++ // before publishing either the checkpoint or its attention alias. ++ writer.reset(); ++ } ++ // Allocate metadata first. On allocation failure during seq_cp, remove ++ // every partially attached attention reference and unpublished map node. ++ auto [entry, inserted] = checkpoints.try_emplace(cache_seq_id); ++ GGML_ASSERT(inserted); ++ auto * attention = attention_memory(memory); ++ try { ++ if (attention) { ++ attention->seq_cp(session->seq_id, cache_seq_id, 0, static_cast(token_count)); ++ } ++ entry->second = std::move(checkpoint); ++ } catch (...) { ++ if (attention) { attention->seq_rm(cache_seq_id, -1, -1); } ++ checkpoints.erase(entry); ++ throw; ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_restore_prefix(skippy_session * session, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_error ** error) { ++ try { return restore_checkpoint(session, cache_seq_id, tokens, count, error); } ++ catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_create_from_resident_prefix(skippy_model * model, int32_t cache_seq_id, ++ const llama_token * tokens, size_t count, skippy_session ** output, skippy_error ** error) { ++ if (!model || !model->ctx || !output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and output session are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = nullptr; ++ skippy_session * session = nullptr; ++ auto status = skippy_session_create(model, &session, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ status = skippy_session_restore_prefix(session, cache_seq_id, tokens, count, error); ++ if (status != SKIPPY_STATUS_OK) { ++ skippy_session_free(session, nullptr); ++ return status; ++ } ++ *output = session; ++ return skippy_success(error); ++} ++ ++enum skippy_status skippy_session_drop_sequence(skippy_session * session, int32_t cache_seq_id, ++ skippy_error ** error) { ++ try { ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ skippy_synchronize_context_if_pending(session->stage_model); ++ if (auto * attention = attention_memory(session->ctx->get_memory())) { ++ if (!attention->seq_rm(cache_seq_id, -1, -1)) { ++ skippy_set_error(error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident attention prefix"); ++ return SKIPPY_STATUS_RUNTIME_ERROR; ++ } ++ } ++ session->stage_model->resident_prefixes.erase(cache_seq_id); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_resident_prefix_bytes(skippy_session * session, int32_t cache_seq_id, ++ uint64_t * output, skippy_error ** error) { ++ try { ++ if (!output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident byte count output is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = 0; ++ const auto status = validate_session(session, cache_seq_id, error); ++ if (status != SKIPPY_STATUS_OK) { return status; } ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto & checkpoints = session->stage_model->resident_prefixes; ++ const auto found = checkpoints.find(cache_seq_id); ++ if (found != checkpoints.end()) { ++ *output = found->second.recurrent.capacity() + found->second.tokens.capacity() * sizeof(llama_token); ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_memory_used_cells(skippy_session * session, uint64_t * output, ++ skippy_error ** error) { ++ if (!session || !session->ctx || !output) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and cell count output are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *output = 0; ++ if (!used_attention_cells(attention_memory(session->ctx->get_memory()), output)) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "attention occupancy is unavailable for this memory type"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ return skippy_success(error); ++} ++ ++enum skippy_status skippy_export_recurrent_state(skippy_session * session, void * output, ++ size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (!session || !session->ctx || !bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent byte count are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *bytes = 0; ++ try { ++ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); ++ if (!recurrent) { return skippy_success(error); } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ recurrent_buffer_writer measure; ++ recurrent->state_write(measure, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ *bytes = measure.n_bytes(); ++ if (!output || capacity < *bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ recurrent_buffer_writer writer(output, capacity); ++ recurrent->state_write(writer, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_import_recurrent_state(skippy_session * session, const void * input, ++ size_t bytes, skippy_error ** error) { ++ if (!bytes) { return skippy_success(error); } ++ if (!session || !session->ctx || !input) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and recurrent payload are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ try { ++ auto * recurrent = skippy_memory_recurrent_adapter(session->ctx->get_memory()); ++ if (!recurrent) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ skippy_synchronize_context_if_pending(session->stage_model); ++ checkpoint_reader reader(static_cast(input), bytes); ++ recurrent->state_read(reader, session->seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); ++ if (reader.n_bytes() != bytes) { ++ throw std::runtime_error("recurrent checkpoint has trailing data"); ++ } ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session * session, ++ int32_t cache_seq_id, void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (!bytes) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent byte count is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ *bytes = 0; ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); ++ if (found == session->stage_model->resident_prefixes.end()) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident checkpoint is unavailable"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto & payload = found->second.recurrent; ++ *bytes = payload.size(); ++ if (payload.empty()) { return skippy_success(error); } ++ if (!output || capacity < payload.size()) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent output buffer is too small"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ std::memcpy(output, payload.data(), payload.size()); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++enum skippy_status skippy_session_export_resident_kv_page(skippy_session * session, ++ int32_t cache_seq_id, int32_t layer_start, int32_t layer_end, ++ uint64_t token_start, uint64_t token_count, skippy_kv_page_desc * descriptor, ++ void * output, size_t capacity, size_t * bytes, skippy_error ** error) { ++ if (bytes) { *bytes = 0; } ++ const auto valid = validate_session(session, cache_seq_id, error); ++ if (valid != SKIPPY_STATUS_OK) { return valid; } ++ try { ++ std::lock_guard lock(session->stage_model->resident_prefix_mutex); ++ const auto found = session->stage_model->resident_prefixes.find(cache_seq_id); ++ if (found == session->stage_model->resident_prefixes.end() ++ || token_start > found->second.tokens.size() ++ || token_count > found->second.tokens.size() - token_start) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident KV export exceeds the saved prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ // This stack view neither claims an execution lane nor changes its ++ // state. Only the explicitly requested cold payload is materialized. ++ skippy_session view{}; ++ view.stage_model = session->stage_model; ++ view.ctx = session->ctx; ++ view.seq_id = cache_seq_id; ++ view.n_past = static_cast(found->second.tokens.size()); ++ return skippy_export_kv_page(&view, layer_start, layer_end, token_start, ++ token_count, descriptor, output, capacity, bytes, error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++} // extern "C" +diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h +index ec9fb94b1..3a2e3147e 100644 +--- a/src/skippy/runtime_types.h ++++ b/src/skippy/runtime_types.h +@@ -10,6 +10,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -84,6 +85,13 @@ struct skippy_glm_dsa_op_timing { + skippy_glm_dsa_hot_tensor hot_tensors[SKIPPY_GLM_DSA_HOT_TENSOR_LIMIT] = {}; + }; + ++// Cache-owned checkpoints outlive execution lanes. Attention remains in the ++// native shared cell pool; only the fixed-size recurrent component is copied. ++struct skippy_resident_checkpoint { ++ std::vector tokens; ++ std::vector recurrent; ++}; ++ + struct skippy_model { + llama_model * model = nullptr; + llama_context * ctx = nullptr; +@@ -111,7 +119,8 @@ struct skippy_model { + uint32_t lane_count = 1; + std::mutex lane_mutex; + std::vector lane_in_use; +- std::vector> lane_resident_prefix_tokens; ++ std::mutex resident_prefix_mutex; ++ std::map resident_prefixes; + std::mutex chat_templates_mutex; + void * chat_templates = nullptr; + void (*chat_templates_free)(void *) = nullptr; +@@ -142,8 +151,6 @@ struct skippy_session { + int32_t n_past = 0; + bool borrowed_sequence = false; + int32_t borrowed_prefix_tokens = 0; +- bool preserve_prefix_on_free = false; +- int32_t preserve_prefix_tokens = 0; + std::vector token_history; + std::vector signal_history; + std::vector prefill_positions; +diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp +index 9d0ba6ee5..d5ac795e9 100644 +--- a/src/skippy/session.cpp ++++ b/src/skippy/session.cpp +@@ -147,9 +147,6 @@ enum skippy_status skippy_session_create( + if (skippy_mtp_available(session)) { + skippy_mtp_clear_session_state(session); + } +- if (static_cast(seq_id) < model->lane_resident_prefix_tokens.size()) { +- model->lane_resident_prefix_tokens[static_cast(seq_id)].clear(); +- } + if (llama_memory_t memory = model->ctx->get_memory()) { + if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { + skippy_release_execution_lane(model, seq_id); +@@ -420,24 +417,7 @@ enum skippy_status skippy_session_free( + g_skippy_external_decode_session = nullptr; + } + if (session->ctx != nullptr) { +- if (session->preserve_prefix_on_free && !session->borrowed_sequence && session->stage_model != nullptr) { +- skippy_synchronize_context_if_pending(session->stage_model); +- if (llama_memory_t memory = session->ctx->get_memory()) { +- llama_memory_seq_rm( +- memory, +- session->seq_id, +- static_cast(session->preserve_prefix_tokens), +- -1); +- } +- } else { +- skippy_session_reset(session, nullptr); +- if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { +- const size_t lane = static_cast(session->seq_id); +- if (lane < session->stage_model->lane_resident_prefix_tokens.size()) { +- session->stage_model->lane_resident_prefix_tokens[lane].clear(); +- } +- } +- } ++ skippy_session_reset(session, nullptr); + } + skippy_clear_chat_sampling(session); + if (!session->borrowed_sequence) { +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +index 45a53c4ba..075326333 100644 +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -18,6 +18,7 @@ + #include + #include + #include ++#include + #include + + extern "C" { +@@ -281,121 +282,6 @@ enum skippy_status skippy_import_full_state( + return skippy_success(out_error); + } + +-static llama_memory_recurrent * skippy_get_recurrent_memory( +- skippy_session * session, +- skippy_error ** out_error) { +- if (session == nullptr || session->ctx == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); +- return nullptr; +- } +- +- llama_memory_t memory = session->ctx->get_memory(); +- if (memory == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); +- return nullptr; +- } +- +- return skippy_memory_recurrent_adapter(memory); +-} +- +-enum skippy_status skippy_export_recurrent_state( +- struct skippy_session * session, +- void * output, +- size_t output_capacity, +- size_t * out_bytes, +- struct skippy_error ** out_error) { +- if (out_bytes == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_bytes is required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- *out_bytes = 0; +- skippy_error * recurrent_error = nullptr; +- llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); +- if (recurrent_error != nullptr) { +- if (out_error != nullptr) { +- *out_error = recurrent_error; +- } else { +- skippy_error_free(recurrent_error); +- } +- return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (recurrent == nullptr) { +- return skippy_success(out_error); +- } +- +- session->ctx->synchronize(); +- const size_t bytes = llama_state_seq_get_size_ext( +- session->ctx, +- session->seq_id, +- LLAMA_STATE_SEQ_FLAGS_NONE); +- *out_bytes = bytes; +- if (bytes == 0) { +- return skippy_success(out_error); +- } +- if (output == nullptr || output_capacity < bytes) { +- skippy_set_error(out_error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "recurrent state output buffer is too small"); +- return SKIPPY_STATUS_BUFFER_TOO_SMALL; +- } +- +- const size_t written = llama_state_seq_get_data_ext( +- session->ctx, +- static_cast(output), +- output_capacity, +- session->seq_id, +- LLAMA_STATE_SEQ_FLAGS_NONE); +- if (written != bytes) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to export recurrent state"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- +- return skippy_success(out_error); +-} +- +-enum skippy_status skippy_import_recurrent_state( +- struct skippy_session * session, +- const void * input, +- size_t input_bytes, +- struct skippy_error ** out_error) { +- if (input_bytes == 0) { +- return skippy_success(out_error); +- } +- if (input == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent state input is required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- skippy_error * recurrent_error = nullptr; +- llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); +- if (recurrent_error != nullptr) { +- if (out_error != nullptr) { +- *out_error = recurrent_error; +- } else { +- skippy_error_free(recurrent_error); +- } +- return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (recurrent == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "runtime has no recurrent memory"); +- return SKIPPY_STATUS_UNSUPPORTED; +- } +- +- session->ctx->synchronize(); +- const size_t read = llama_state_seq_set_data_ext( +- session->ctx, +- static_cast(input), +- input_bytes, +- session->seq_id, +- LLAMA_STATE_SEQ_FLAGS_NONE); +- if (read != input_bytes) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to import recurrent state"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- session->ctx->synchronize(); +- +- return skippy_success(out_error); +-} +- + static llama_kv_cache * skippy_get_kv_cache( + skippy_session * session, + skippy_error ** out_error) { +@@ -889,331 +775,4 @@ enum skippy_status skippy_trim_session( + return skippy_success(out_error); + } + +-static bool skippy_is_reserved_sequence_id( +- const skippy_session * session, +- int32_t seq_id) { +- if (session == nullptr || session->stage_model == nullptr || seq_id < 0) { +- return true; +- } +- const int32_t reserved = static_cast(session->stage_model->lane_count) * 2; +- return seq_id < reserved; +-} +- +-static bool skippy_is_reserved_sequence_id_for_model( +- const skippy_model * model, +- int32_t seq_id) { +- if (model == nullptr || seq_id < 0) { +- return true; +- } +- const int32_t reserved = static_cast(model->lane_count) * 2; +- return seq_id < reserved; +-} +- +-static enum skippy_status skippy_get_resident_prefix_memory( +- skippy_session * session, +- llama_memory_t * out_memory, +- struct skippy_error ** out_error) { +- if (session == nullptr || session->ctx == nullptr || out_memory == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- llama_memory_t memory = session->ctx->get_memory(); +- if (memory == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "runtime memory is unavailable"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- +- skippy_error * recurrent_error = nullptr; +- llama_memory_recurrent * recurrent = skippy_get_recurrent_memory(session, &recurrent_error); +- if (recurrent_error != nullptr) { +- if (out_error != nullptr) { +- *out_error = recurrent_error; +- } else { +- skippy_error_free(recurrent_error); +- } +- return out_error != nullptr && *out_error != nullptr ? (*out_error)->status : SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (recurrent != nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "resident prefix cache is not enabled for recurrent memory"); +- return SKIPPY_STATUS_UNSUPPORTED; +- } +- +- *out_memory = memory; +- return SKIPPY_STATUS_OK; +-} +- +-enum skippy_status skippy_session_save_prefix( +- struct skippy_session * session, +- int32_t cache_seq_id, +- uint64_t token_count, +- struct skippy_error ** out_error) { +- if (token_count > static_cast(std::numeric_limits::max())) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (session == nullptr || token_count > static_cast(session->n_past)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cannot save prefix beyond current session position"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- llama_memory_t memory = nullptr; +- enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); +- if (status != SKIPPY_STATUS_OK) { +- return status; +- } +- +- skippy_synchronize_context_if_pending(session->stage_model); +- if (!llama_memory_seq_rm(memory, cache_seq_id, -1, -1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear resident prefix sequence"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (token_count > 0) { +- llama_memory_seq_cp(memory, session->seq_id, cache_seq_id, 0, static_cast(token_count)); +- } +- if (!session->borrowed_sequence && session->stage_model != nullptr && session->seq_id >= 0) { +- const size_t lane = static_cast(session->seq_id); +- if (lane < session->stage_model->lane_resident_prefix_tokens.size() +- && session->token_history.size() >= static_cast(token_count)) { +- auto & lane_tokens = session->stage_model->lane_resident_prefix_tokens[lane]; +- lane_tokens.assign( +- session->token_history.begin(), +- session->token_history.begin() + static_cast(token_count)); +- session->preserve_prefix_on_free = true; +- session->preserve_prefix_tokens = static_cast(token_count); +- } +- } +- return skippy_success(out_error); +-} +- +-enum skippy_status skippy_session_restore_prefix( +- struct skippy_session * session, +- int32_t cache_seq_id, +- const llama_token * token_ids, +- size_t token_count, +- struct skippy_error ** out_error) { +- if (token_count > static_cast(std::numeric_limits::max())) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds llama position range"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (token_count > 0 && token_ids == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (skippy_is_reserved_sequence_id(session, cache_seq_id)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- llama_memory_t memory = nullptr; +- enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); +- if (status != SKIPPY_STATUS_OK) { +- return status; +- } +- +- skippy_synchronize_context_if_pending(session->stage_model); +- if (token_count > 0) { +- const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); +- if (max_pos < static_cast(token_count - 1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- } +- if (!llama_memory_seq_rm(memory, session->seq_id, -1, -1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear execution lane"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (token_count > 0) { +- llama_memory_seq_cp(memory, cache_seq_id, session->seq_id, 0, static_cast(token_count)); +- } +- session->n_past = static_cast(token_count); +- if (token_count == 0) { +- session->token_history.clear(); +- } else { +- session->token_history.assign(token_ids, token_ids + token_count); +- } +- session->signal_history.clear(); +- skippy_mtp_clear_session_state(session); +- skippy_clear_verify_windows(session); +- return skippy_success(out_error); +-} +- +-enum skippy_status skippy_session_create_from_resident_prefix( +- struct skippy_model * model, +- int32_t cache_seq_id, +- const llama_token * token_ids, +- size_t token_count, +- struct skippy_session ** out_session, +- struct skippy_error ** out_error) { +- if (model == nullptr || model->model == nullptr || model->ctx == nullptr || out_session == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "model and out_session are required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- *out_session = nullptr; +- if (token_count > static_cast(std::numeric_limits::max()) +- || token_count > static_cast(std::numeric_limits::max())) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_count exceeds supported position range"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (token_count > 0 && token_ids == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "token_ids are required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- if (skippy_is_reserved_sequence_id_for_model(model, cache_seq_id)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "cache sequence id overlaps execution lanes"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- const int32_t seq_id = skippy_claim_execution_lane(model); +- if (seq_id < 0) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "no skippy execution lane is available"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- +- skippy_session temp{}; +- temp.stage_model = model; +- temp.ctx = model->ctx; +- llama_memory_t memory = nullptr; +- enum skippy_status status = skippy_get_resident_prefix_memory(&temp, &memory, out_error); +- if (status != SKIPPY_STATUS_OK) { +- skippy_release_execution_lane(model, seq_id); +- return status; +- } +- +- skippy_synchronize_context_if_pending(model); +- if (token_count > 0) { +- const llama_pos max_pos = llama_memory_seq_pos_max(memory, cache_seq_id); +- if (max_pos < static_cast(token_count - 1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident prefix sequence is incomplete"); +- skippy_release_execution_lane(model, seq_id); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- } +- bool lane_prefix_hit = false; +- const size_t lane = static_cast(seq_id); +- if (lane < model->lane_resident_prefix_tokens.size()) { +- const auto & lane_tokens = model->lane_resident_prefix_tokens[lane]; +- lane_prefix_hit = lane_tokens.size() == token_count +- && (token_count == 0 || std::equal(lane_tokens.begin(), lane_tokens.end(), token_ids)); +- } +- if (!lane_prefix_hit) { +- if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to clear borrowed execution lane"); +- skippy_release_execution_lane(model, seq_id); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- if (token_count > 0) { +- llama_memory_seq_cp(memory, cache_seq_id, seq_id, 0, static_cast(token_count)); +- } +- } +- if (!llama_memory_seq_rm(memory, seq_id, static_cast(token_count), -1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to trim borrowed execution lane"); +- skippy_release_execution_lane(model, seq_id); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- +- skippy_session * session = new skippy_session{}; +- session->stage_model = model; +- session->ctx = model->ctx; +- session->seq_id = seq_id; +- session->n_past = static_cast(token_count); +- session->borrowed_sequence = false; +- session->borrowed_prefix_tokens = 0; +- if (token_count > 0) { +- session->token_history.assign(token_ids, token_ids + token_count); +- } +- skippy_mtp_clear_session_state(session); +- *out_session = session; +- return skippy_success(out_error); +-} +- +-enum skippy_status skippy_session_drop_sequence( +- struct skippy_session * session, +- int32_t seq_id, +- struct skippy_error ** out_error) { +- if (skippy_is_reserved_sequence_id(session, seq_id)) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "sequence id overlaps execution lanes"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- +- llama_memory_t memory = nullptr; +- enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); +- if (status != SKIPPY_STATUS_OK) { +- return status; +- } +- skippy_synchronize_context_if_pending(session->stage_model); +- if (!llama_memory_seq_rm(memory, seq_id, -1, -1)) { +- skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to drop resident prefix sequence"); +- return SKIPPY_STATUS_RUNTIME_ERROR; +- } +- return skippy_success(out_error); +-} +- +-static bool skippy_memory_used_cells(llama_memory_t memory, uint64_t * out_used_cells) { +- if (auto * cache = dynamic_cast(memory)) { +- *out_used_cells = cache->get_used_cells(); +- return true; +- } +- if (auto * dsa = dynamic_cast(memory)) { +- *out_used_cells = std::max(dsa->get_mla()->get_used_cells(), dsa->get_lid()->get_used_cells()); +- return true; +- } +- if (auto * iswa = dynamic_cast(memory)) { +- *out_used_cells = std::max(iswa->get_base()->get_used_cells(), iswa->get_swa()->get_used_cells()); +- return true; +- } +- if (auto * dsa_iswa = dynamic_cast(memory)) { +- uint64_t dsa_used_cells = 0; +- if (!skippy_memory_used_cells(dsa_iswa->get_dsa(), &dsa_used_cells)) { +- return false; +- } +- *out_used_cells = std::max(dsa_used_cells, dsa_iswa->get_swa()->get_used_cells()); +- return true; +- } +- if (auto * msa = dynamic_cast(memory)) { +- *out_used_cells = std::max(msa->get_base()->get_used_cells(), msa->get_idx()->get_used_cells()); +- return true; +- } +- if (auto * dsv4 = dynamic_cast(memory)) { +- uint64_t raw_used_cells = 0; +- if (!skippy_memory_used_cells(dsv4->get_raw(), &raw_used_cells)) { +- return false; +- } +- *out_used_cells = std::max({ +- raw_used_cells, +- dsv4->get_csa()->get_used_cells(), +- dsv4->get_hca()->get_used_cells(), +- dsv4->get_lid()->get_used_cells(), +- }); +- return true; +- } +- return false; +-} +- +-enum skippy_status skippy_session_memory_used_cells( +- struct skippy_session * session, +- uint64_t * out_used_cells, +- struct skippy_error ** out_error) { +- if (out_used_cells == nullptr) { +- skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "out_used_cells is required"); +- return SKIPPY_STATUS_INVALID_ARGUMENT; +- } +- *out_used_cells = 0; +- +- llama_memory_t memory = nullptr; +- enum skippy_status status = skippy_get_resident_prefix_memory(session, &memory, out_error); +- if (status != SKIPPY_STATUS_OK) { +- return status; +- } +- if (!skippy_memory_used_cells(memory, out_used_cells)) { +- skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "physical occupancy is unavailable for this memory type"); +- return SKIPPY_STATUS_UNSUPPORTED; +- } +- return skippy_success(out_error); +-} +- + } // extern "C" +diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp +index e271852ff..806e79d72 100644 +--- a/src/skippy/state_memory.cpp ++++ b/src/skippy/state_memory.cpp +@@ -56,16 +56,16 @@ uint32_t skippy_memory_cache_capabilities(llama_memory_t memory) { + // coverage merely from a successful dynamic_cast or a nonempty export. + const auto & type = typeid(*memory); + if (type == typeid(llama_kv_cache) || type == typeid(llama_kv_cache_iswa)) { +- return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; ++ return SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_recurrent)) { + return skippy_memory_recurrent_adapter(memory) +- ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + if (type == typeid(llama_memory_hybrid) || type == typeid(llama_memory_hybrid_iswa)) { + return skippy_memory_recurrent_adapter(memory) && + (skippy_memory_kv_adapter(memory) || skippy_memory_iswa_adapter(memory)) +- ? SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; ++ ? SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | SKIPPY_MEMORY_CACHE_FULL_STATE : SKIPPY_MEMORY_CACHE_FULL_STATE; + } + // DSA/MSA memories include an indexer tier. Until a real-model resident + // save/restore proves that tier survives, use complete state snapshots. +@@ -89,7 +89,7 @@ uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result) { + } + // A phase with no persistent effects adds no cache restrictions. It must + // not be confused with failed graph admission or unexported context state. +- uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | ++ uint32_t supported = SKIPPY_MEMORY_CACHE_RESIDENT | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT | SKIPPY_MEMORY_CACHE_KV_RECURRENT | + SKIPPY_MEMORY_CACHE_FULL_STATE; + for (const auto & effect : effects) { + switch (effect.kind) { +@@ -98,7 +98,6 @@ uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result) { + break; + case skippy_state_kind::recurrent_conv: + case skippy_state_kind::recurrent_ssm: +- supported &= ~SKIPPY_MEMORY_CACHE_RESIDENT; + break; + case skippy_state_kind::derived_persistent: + supported &= SKIPPY_MEMORY_CACHE_FULL_STATE; +@@ -109,8 +108,18 @@ uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result) { + } + + extern "C" uint32_t skippy_model_memory_cache_capabilities(const skippy_model * model) { +- return model && model->ctx ++ uint32_t capabilities = model && model->ctx + ? model->ctx->admit_skippy_cache_capabilities( + skippy_memory_cache_capabilities(model->ctx->get_memory())) + : 0; ++ // Explicit non-unified attention contexts cannot admit the resident API. ++ // Preserve their complete export representations, but never advertise ++ // cache ownership that resident_prefix::validate_session will refuse. ++ if (model && model->ctx && !model->ctx->get_cparams().kv_unified ++ && (capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION)) { ++ capabilities &= ~(SKIPPY_MEMORY_CACHE_RESIDENT ++ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION ++ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); ++ } ++ return capabilities; + } +diff --git a/src/skippy/tests/resident_checkpoint_gpu.cpp b/src/skippy/tests/resident_checkpoint_gpu.cpp +new file mode 100644 +index 000000000..691e92c37 +--- /dev/null ++++ b/src/skippy/tests/resident_checkpoint_gpu.cpp +@@ -0,0 +1,287 @@ ++// Opt-in real-model GPU proof: separate checkpoint ownership from HTTP scheduling. ++#include "skippy.h" ++#include "../runtime_types.h" ++#include "llama-model.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); ++ ++namespace { ++constexpr size_t lanes = 4; ++constexpr size_t suffix_steps = 32; ++constexpr size_t pressure_tokens = 4096; ++using Sessions = std::array; ++using Prefixes = std::array, lanes>; ++ ++#define REQUIRE(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "long GPU checkpoint failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++void ok(skippy_status status, skippy_error * error) { ++ if (status != SKIPPY_STATUS_OK) { ++ std::fprintf(stderr, "long GPU native error: %s\n", error ? error->message : "no detail"); ++ std::exit(1); ++ } ++ skippy_error_free(error); ++} ++ ++size_t prefix_tokens() { ++ const char * value = std::getenv("SKIPPY_NATIVE_TEST_PREFIX_TOKENS"); ++ if (!value) { return 23497; } ++ REQUIRE(*value && std::strspn(value, "0123456789") == std::strlen(value)); ++ const unsigned long count = std::strtoul(value, nullptr, 10); ++ REQUIRE(count >= 128 && count <= 65536); ++ return static_cast(count); ++} ++ ++Sessions create(skippy_model * model) { ++ Sessions sessions{}; ++ for (auto & session : sessions) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_create(model, &session, &error); ++ ok(status, error); ++ } ++ return sessions; ++} ++ ++void release(Sessions & sessions) { ++ for (auto & session : sessions) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_free(session, &error); ++ ok(status, error); ++ session = nullptr; ++ } ++} ++ ++void prefill(Sessions & sessions, const Prefixes & prefixes) { ++ // Identical explicit chunk and lane order in every cold reference arm. ++ for (size_t offset = 0; offset < prefixes[0].size(); offset += 512) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ const size_t count = std::min(512, prefixes[lane].size() - offset); ++ skippy_error * error = nullptr; ++ size_t bytes = 0; ++ const auto status = skippy_prefill_chunk(sessions[lane], prefixes[lane].data() + offset, ++ count, nullptr, 0, nullptr, 0, &bytes, &error); ++ ok(status, error); ++ } ++ } ++} ++ ++Prefixes tokens(size_t count, int32_t vocab_size, int32_t salt) { ++ REQUIRE(vocab_size > 64); ++ const int32_t span = std::min(vocab_size - 32, 4096); ++ Prefixes prefixes; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ prefixes[lane].reserve(count); ++ for (size_t i = 0; i < count; ++i) { ++ prefixes[lane].push_back(32 + static_cast((i * 17 + lane * 101 + salt) % span)); ++ } ++ } ++ return prefixes; ++} ++ ++struct Components { ++ std::vector kv; ++ std::vector recurrent; ++}; ++ ++Components components(skippy_session * session) { ++ const int32_t layers = static_cast(session->stage_model->model->hparams.n_layer()); ++ skippy_kv_page_desc desc{}; ++ size_t bytes = 0; ++ skippy_error * error = nullptr; ++ auto status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &desc, nullptr, 0, &bytes, &error); ++ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); ++ skippy_error_free(error); ++ Components result; ++ result.kv.resize(bytes); ++ error = nullptr; ++ status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &desc, result.kv.data(), result.kv.size(), &bytes, &error); ++ ok(status, error); ++ result.kv.resize(bytes); ++ error = nullptr; ++ status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); ++ REQUIRE(status == SKIPPY_STATUS_BUFFER_TOO_SMALL && bytes > 0); ++ skippy_error_free(error); ++ result.recurrent.resize(bytes); ++ error = nullptr; ++ status = skippy_export_recurrent_state(session, result.recurrent.data(), ++ result.recurrent.size(), &bytes, &error); ++ ok(status, error); ++ result.recurrent.resize(bytes); ++ return result; ++} ++ ++struct DecodeRows { ++ std::array greedy; ++ std::array, lanes> logits; ++}; ++ ++using DecodeTrace = std::vector; ++ ++DecodeTrace decode_fixed_suffix(Sessions & sessions, int32_t vocab_size) { ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.repeat_penalty = 1.0f; ++ sampling.temperature = 0; ++ sampling.top_k = 1; ++ sampling.reasoning_budget_tokens = -1; ++ DecodeTrace trace; ++ trace.reserve(suffix_steps); ++ for (size_t step = 0; step < suffix_steps; ++step) { ++ std::array input{}; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ input[lane] = 32 + static_cast((step * 11 + lane * 37) % (vocab_size - 32)); ++ } ++ DecodeRows rows; ++ skippy_error * error = nullptr; ++ std::array requests{}; ++ std::array sampled_indexes{}; ++ size_t sampled_count = 0; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ requests[lane].session = sessions[lane]; ++ requests[lane].token_ids = &input[lane]; ++ requests[lane].token_count = 1; ++ requests[lane].sampling = &sampling; ++ requests[lane].sample_last = true; ++ } ++ const auto status = skippy_iteration_batch_sampled(requests.data(), requests.size(), ++ nullptr, nullptr, nullptr, nullptr, sampled_indexes.data(), rows.greedy.data(), ++ rows.greedy.size(), &sampled_count, &error); ++ ok(status, error); ++ REQUIRE(sampled_count == lanes); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ REQUIRE(sampled_indexes[lane] == lane); ++ const float * logits = llama_get_logits_ith(sessions[lane]->ctx, static_cast(lane)); ++ REQUIRE(logits != nullptr); ++ rows.logits[lane].assign(logits, logits + vocab_size); ++ REQUIRE(std::all_of(rows.logits[lane].begin(), rows.logits[lane].end(), ++ [](float value) { return std::isfinite(value); })); ++ } ++ trace.push_back(std::move(rows)); ++ } ++ return trace; ++} ++ ++bool compare(const char * arm, const DecodeTrace & reference, const DecodeTrace & actual) { ++ REQUIRE(reference.size() == actual.size()); ++ float max_delta = 0; ++ size_t mismatched_greedy = 0; ++ for (size_t step = 0; step < reference.size(); ++step) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ mismatched_greedy += reference[step].greedy[lane] != actual[step].greedy[lane]; ++ REQUIRE(reference[step].logits[lane].size() == actual[step].logits[lane].size()); ++ for (size_t token = 0; token < reference[step].logits[lane].size(); ++token) { ++ max_delta = std::max(max_delta, ++ std::fabs(reference[step].logits[lane][token] - actual[step].logits[lane][token])); ++ } ++ } ++ } ++ std::fprintf(stderr, "%s: batch=4 steps=%zu max_logit_delta=%.9g greedy_mismatches=%zu\n", ++ arm, reference.size(), max_delta, mismatched_greedy); ++ return max_delta <= 1e-6f && mismatched_greedy == 0; ++} ++ ++void save(Sessions & sessions, size_t count) { ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_save_prefix(sessions[lane], static_cast(8 + lane), count, &error); ++ ok(status, error); ++ } ++} ++ ++Sessions restore(skippy_model * model, const Prefixes & prefixes) { ++ Sessions sessions{}; ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_create_from_resident_prefix(model, static_cast(8 + lane), ++ prefixes[lane].data(), prefixes[lane].size(), &sessions[lane], &error); ++ ok(status, error); ++ } ++ return sessions; ++} ++ ++void require_gpu_weights(skippy_model * model) { ++ REQUIRE(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), ++ [](const auto & item) { ++ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } ++ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( ++ ggml_backend_buffer_get_type(item.second->buffer))); ++ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; ++ })); ++} ++ ++} // namespace ++ ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config) { ++ REQUIRE(model_path && *model_path && config.n_gpu_layers > 0); ++ const size_t count = prefix_tokens(); ++ config.ctx_size = static_cast(count + pressure_tokens + suffix_steps + 64); ++ config.lane_count = lanes; ++ config.kv_unified = 1; ++ config.n_batch = 512; ++ config.n_ubatch = 512; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ auto status = skippy_model_open(model_path, &config, &model, &error); ++ ok(status, error); ++ require_gpu_weights(model); ++ REQUIRE(config.ctx_size <= llama_model_n_ctx_train(model->model)); ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); ++ REQUIRE(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT); ++ const int32_t vocab_size = llama_vocab_n_tokens(llama_model_get_vocab(model->model)); ++ const auto prefixes = tokens(count, vocab_size, 0); ++ auto source = create(model); ++ prefill(source, prefixes); ++ save(source, count); ++ std::array expected; ++ for (size_t lane = 0; lane < lanes; ++lane) { expected[lane] = components(source[lane]); } ++ const auto reference = decode_fixed_suffix(source, vocab_size); ++ release(source); ++ ++ auto pressure = create(model); ++ prefill(pressure, tokens(pressure_tokens, vocab_size, 503)); ++ release(pressure); ++ auto warm = restore(model, prefixes); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ const auto restored = components(warm[lane]); ++ std::fprintf(stderr, "checkpoint lane=%zu tokens=%zu kv_bytes=%zu recurrent_bytes=%zu kv_exact=%d recurrent_exact=%d\n", ++ lane, count, restored.kv.size(), restored.recurrent.size(), ++ restored.kv == expected[lane].kv, restored.recurrent == expected[lane].recurrent); ++ REQUIRE(restored.kv == expected[lane].kv); ++ REQUIRE(restored.recurrent == expected[lane].recurrent); ++ } ++ const auto restored_trace = decode_fixed_suffix(warm, vocab_size); ++ const bool passed = compare("resident restore vs reference", reference, restored_trace); ++ for (size_t lane = 0; lane < lanes; ++lane) { ++ error = nullptr; ++ status = skippy_session_drop_sequence(warm[0], static_cast(8 + lane), &error); ++ ok(status, error); ++ } ++ release(warm); ++ if (!passed) { ++ // Preserve the strict failure. A same-shape second cold reference ++ // distinguishes backend drift before any tolerance change is proposed. ++ auto repeated = create(model); ++ prefill(repeated, prefixes); ++ compare("cold reference vs repeated cold reference", reference, decode_fixed_suffix(repeated, vocab_size)); ++ release(repeated); ++ } ++ error = nullptr; ++ status = skippy_model_free(model, &error); ++ ok(status, error); ++ return passed ? 0 : 1; ++} +diff --git a/src/skippy/tests/resident_checkpoint_writer.cpp b/src/skippy/tests/resident_checkpoint_writer.cpp +new file mode 100644 +index 000000000..d08029062 +--- /dev/null ++++ b/src/skippy/tests/resident_checkpoint_writer.cpp +@@ -0,0 +1,126 @@ ++#include "llama-io.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++#include "ggml-cpu.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++int skippy_test_resident_checkpoint_writer(); ++ ++namespace { ++ ++#define CHECK(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "resident writer check failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++// Preserve the previous resident writer as the byte-layout oracle. Both paths ++// consume the same metadata and actual backend tensor ranges in serialize(). ++class previous_resident_writer final : public llama_io_write_i { ++public: ++ void write(const void * source, size_t bytes) override { ++ const auto * data = static_cast(source); ++ if (bytes) { payload.insert(payload.end(), data, data + bytes); } ++ } ++ void write_tensor(ggml_tensor * tensor, size_t offset, size_t bytes) override { ++ const size_t start = payload.size(); ++ payload.resize(start + bytes); ++ if (bytes) { ggml_backend_tensor_get(tensor, payload.data() + start, offset, bytes); } ++ } ++ size_t n_bytes() override { return payload.size(); } ++ std::vector payload; ++}; ++ ++struct source_tensor { ++ ggml_context * context; ++ ggml_backend_buffer_t buffer; ++ ggml_tensor * tensor; ++ ++ source_tensor() { ++ context = ggml_init({ggml_tensor_overhead() + 1024, nullptr, true}); ++ CHECK(context != nullptr); ++ tensor = ggml_new_tensor_1d(context, GGML_TYPE_I8, 16); ++ buffer = ggml_backend_alloc_ctx_tensors_from_buft(context, ggml_backend_cpu_buffer_type()); ++ CHECK(buffer != nullptr); ++ const std::array bytes = {1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 0}; ++ ggml_backend_tensor_set(tensor, bytes.data(), 0, bytes.size()); ++ } ++ ~source_tensor() { ++ ggml_backend_buffer_free(buffer); ++ ggml_free(context); ++ } ++}; ++ ++void serialize(llama_io_write_i & writer, ggml_tensor * tensor) { ++ const uint32_t header = 0x17294381; ++ const uint16_t separator = 0x5317; ++ writer.write(&header, sizeof(header)); ++ writer.write_tensor(tensor, 4, 8); ++ writer.write(&separator, sizeof(separator)); ++ writer.write_tensor(tensor, 0, 4); ++} ++ ++void byte_layout_and_deferred_reads(ggml_tensor * tensor) { ++ previous_resident_writer previous; ++ serialize(previous, tensor); ++ std::vector actual(previous.n_bytes(), 0xa5); ++ const auto * destination = actual.data(); ++ auto writer = llama_io_write_host_create(actual.data(), actual.size()); ++ serialize(*writer, tensor); ++ CHECK(writer->n_bytes() == previous.n_bytes()); ++ CHECK(actual.data() == destination); ++ // Metadata is already written, while both queued tensor spans remain ++ // untouched until the explicit destruction that precedes publication. ++ CHECK(std::memcmp(actual.data(), previous.payload.data(), sizeof(uint32_t)) == 0); ++ CHECK(std::memcmp(actual.data() + 12, previous.payload.data() + 12, sizeof(uint16_t)) == 0); ++ for (size_t i : {4u, 5u, 6u, 7u, 8u, 9u, 10u, 11u, 14u, 15u, 16u, 17u}) { ++ CHECK(actual[i] == 0xa5); ++ } ++ writer.reset(); ++ CHECK(actual == previous.payload); ++} ++ ++void bounded_writes_and_error_flush(ggml_tensor * tensor) { ++ std::array guarded; ++ guarded.fill(0xa5); ++ auto writer = llama_io_write_host_create(guarded.data() + 2, 12); ++ const uint32_t header = 0x17294381; ++ writer->write(&header, sizeof(header)); ++ writer->write_tensor(tensor, 4, 8); ++ bool metadata_rejected = false; ++ try { writer->write(&header, sizeof(header)); } ++ catch (const std::runtime_error &) { metadata_rejected = true; } ++ CHECK(metadata_rejected && writer->n_bytes() == 12); ++ bool tensor_rejected = false; ++ try { writer->write_tensor(tensor, 0, 1); } ++ catch (const std::runtime_error &) { tensor_rejected = true; } ++ CHECK(tensor_rejected && writer->n_bytes() == 12); ++ writer.reset(); ++ previous_resident_writer previous; ++ previous.write(&header, sizeof(header)); ++ previous.write_tensor(tensor, 4, 8); ++ CHECK(std::memcmp(guarded.data() + 2, previous.payload.data(), previous.n_bytes()) == 0); ++ CHECK(guarded[0] == 0xa5 && guarded[1] == 0xa5 && guarded[14] == 0xa5 && guarded[15] == 0xa5); ++ ++ // n_bytes is the actual serialized count, not the supplied capacity: the ++ // resident caller can reject a changed measurement before publication. ++ writer = llama_io_write_host_create(guarded.data() + 2, 12); ++ writer->write(&header, sizeof(header)); ++ CHECK(writer->n_bytes() == sizeof(header) && writer->n_bytes() != 12); ++ writer.reset(); ++} ++ ++} // namespace ++ ++int skippy_test_resident_checkpoint_writer() { ++ source_tensor source; ++ byte_layout_and_deferred_reads(source.tensor); ++ bounded_writes_and_error_flush(source.tensor); ++ std::puts("resident checkpoint writer: byte layout, deferred reads and bounds passed"); ++ return 0; ++} +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index f092b75b0..2f1899797 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -5,23 +5,112 @@ + #include "../runtime_support.h" + #include "../verify_window.h" + #include "llama-model.h" ++#include "llama-graph.h" ++#include "ggml-backend.h" + #include "../../../common/sampling.h" + + #include ++#include + #include + #include + #include + #include + #include ++#include + + #define CHECK(condition) do { if (!(condition)) { \ + std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ + std::exit(1); } } while (0) + ++int skippy_test_resident_checkpoint_gpu(const char * model_path, skippy_runtime_config config); ++int skippy_test_resident_checkpoint_writer(); ++ + namespace { + + bool require_recurrent = false; + ++int32_t cache_type(const char * name) { ++ for (const auto type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, ++ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q8_0}) { ++ if (std::strcmp(name, ggml_type_name(type)) == 0) { return type; } ++ } ++ CHECK(false && "unsupported test KV type"); ++ return -1; ++} ++ ++ggml_type verify_attention_read(skippy_model * model, ggml_tensor * input, int32_t stored_type) { ++ if (stored_type != GGML_TYPE_F32) { ++ CHECK(input->type == stored_type); ++ return input->type; ++ } ++ // Ordinary FA reads explicitly convert an F32 cache on its selected backend. ++ CHECK(input->type == GGML_TYPE_F16 && input->op == GGML_OP_CPY); ++ CHECK(input->src[0] && input->src[0]->type == GGML_TYPE_F32); ++ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), input); ++ CHECK(backend && std::strcmp(ggml_backend_name(backend), model->config.selected_backend_device) == 0); ++ return input->type; ++} ++ ++void verify_typed_attention(skippy_model * model, const skippy_kv_page_desc & page) { ++ const auto & config = model->config; ++ const auto check_types = [&](uint32_t k, uint32_t v) { ++ CHECK(k == static_cast(config.cache_type_k)); ++ CHECK(v == static_cast(config.cache_type_v)); ++ }; ++ if (page.component_count) { ++ CHECK(page.component_count <= std::size(page.components)); ++ for (uint32_t i = 0; i < page.component_count; ++i) { ++ check_types(page.components[i].k_type, page.components[i].v_type); ++ } ++ } else { ++ check_types(page.k_type, page.v_type); ++ } ++ auto * result = model->ctx->get_gf_res_prev_active(); ++ CHECK(result && result->get_gf()); ++ auto * graph = result->get_gf(); ++ int attention = 0; ++ int row_attention = 0; ++ ggml_type actual_k = GGML_TYPE_COUNT; ++ ggml_type actual_v = GGML_TYPE_COUNT; ++ for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { ++ auto * node = ggml_graph_node(graph, i); ++ if (node->op != GGML_OP_FLASH_ATTN_EXT) { continue; } ++ auto * backend = ggml_backend_sched_get_tensor_backend(model->ctx->get_sched(), node); ++ CHECK(backend && std::strcmp(ggml_backend_name(backend), config.selected_backend_device) == 0); ++ CHECK(node->src[6] == nullptr); ++ CHECK(ggml_backend_supports_op(backend, node)); ++ if (const auto * rows = node->src[5]) { ++ CHECK(rows->type == GGML_TYPE_I32 && rows->buffer && rows->data); ++ CHECK(rows->ne[0] > 0 && rows->ne[0] % 256 == 0); ++ CHECK(rows->ne[1] == node->src[0]->ne[3] && rows->ne[2] == 1 && rows->ne[3] == 1); ++ CHECK(rows->ne[0] <= node->src[1]->ne[1]); ++ CHECK(node->src[1]->ne[3] == 1 && node->src[2]->ne[3] == 1); ++ CHECK(node->src[3] && node->src[3]->type == GGML_TYPE_F16); ++ CHECK(node->src[3]->ne[0] == rows->ne[0]); ++ CHECK(node->src[3]->ne[3] == node->src[0]->ne[3]); ++ CHECK(rows->nb[0] == sizeof(int32_t) && ggml_is_contiguous(rows)); ++ std::vector physical(ggml_nelements(rows)); ++ ggml_backend_tensor_get(rows, physical.data(), 0, ggml_nbytes(rows)); ++ for (const auto row : physical) { ++ CHECK(row >= -1 && row < node->src[1]->ne[1]); ++ } ++ ++row_attention; ++ } ++ actual_k = verify_attention_read(model, node->src[1], config.cache_type_k); ++ actual_v = verify_attention_read(model, node->src[2], config.cache_type_v); ++ ++attention; ++ } ++ int expected_attention = 0; ++ for (uint32_t layer = 0; layer < model->model->hparams.n_layer(); ++layer) { ++ expected_attention += !model->model->hparams.is_recr(layer); ++ } ++ CHECK(attention > 0 && attention == expected_attention); ++ std::fprintf(stderr, "typed resident: backend=%s stored_K=%s stored_V=%s FA_K=%s FA_V=%s attention=%d expected=%d components=%u ordinary_nodes=%d rows_nodes=%d\n", ++ config.selected_backend_device, ggml_type_name(static_cast(config.cache_type_k)), ++ ggml_type_name(static_cast(config.cache_type_v)), ggml_type_name(actual_k), ggml_type_name(actual_v), ++ attention, expected_attention, page.component_count, attention - row_attention, row_attention); ++} ++ + void ok(skippy_status status, skippy_error * error) { + if (status != SKIPPY_STATUS_OK) { + std::fprintf(stderr, "native failure: %s\n", error ? error->message : "no detail"); +@@ -30,6 +119,31 @@ void ok(skippy_status status, skippy_error * error) { + skippy_error_free(error); + } + ++void configure_test_gpu(skippy_runtime_config & config) { ++ config.n_gpu_layers = 0; ++ const char * value = std::getenv("SKIPPY_NATIVE_TEST_GPU_LAYERS"); ++ if (!value) { return; } ++ CHECK(*value && std::strspn(value, "0123456789") == std::strlen(value)); ++ const unsigned long layers = std::strtoul(value, nullptr, 10); ++ CHECK(layers <= static_cast(std::numeric_limits::max())); ++ if (!layers) { return; } ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ auto status = skippy_backend_device_count(&count, &error); ++ ok(status, error); ++ for (size_t i = 0; i < count; ++i) { ++ skippy_backend_device device{}; ++ error = nullptr; ++ status = skippy_backend_device_at(i, &device, &error); ++ ok(status, error); ++ if (device.type != SKIPPY_BACKEND_DEVICE_TYPE_GPU && device.type != SKIPPY_BACKEND_DEVICE_TYPE_IGPU) { continue; } ++ config.selected_backend_device = device.name; ++ config.n_gpu_layers = static_cast(layers); ++ return; ++ } ++ CHECK(false && "GPU layers requested but no GPU backend is available"); ++} ++ + void prefill(skippy_session * session, const std::vector & tokens) { + size_t bytes = 0; + skippy_error * error = nullptr; +@@ -567,6 +681,174 @@ void state_round_trip(skippy_model * model) { + CHECK(max_delta == 0.0f); + } + ++void resident_prefix_ownership(skippy_model * model, bool typed = false) { ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT); ++ CHECK(bool(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT) == require_recurrent); ++ const std::vector prefix(128, 1); ++ const std::vector suffix_a{2, 3, 4}; ++ const std::vector suffix_b{5, 6, 7}; ++ constexpr int32_t cache_id = 8; ++ auto * source = create(model); ++ prefill(source, prefix); ++ skippy_error * error = nullptr; ++ uint64_t before_cells = 0; ++ ok(skippy_session_memory_used_cells(source, &before_cells, &error), error); ++ error = nullptr; ++ ok(skippy_session_save_prefix(source, cache_id, prefix.size(), &error), error); ++ uint64_t after_cells = 0; ++ error = nullptr; ++ ok(skippy_session_memory_used_cells(source, &after_cells, &error), error); ++ CHECK(before_cells == after_cells); // Sharing must not allocate attention cells. ++ uint64_t checkpoint_bytes = 0; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(source, cache_id, &checkpoint_bytes, &error), error); ++ CHECK(checkpoint_bytes >= prefix.size() * sizeof(llama_token)); ++ const auto source_page = export_page(source, prefix.size()); ++ snapshot persistent(source, false); ++ if (typed) { verify_typed_attention(model, persistent.page); } ++ if (require_recurrent) { ++ CHECK(checkpoint_bytes > prefix.size() * sizeof(llama_token)); ++ error = nullptr; ++ CHECK(skippy_session_save_prefix(source, cache_id, prefix.size() - 1, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ uint64_t unchanged_bytes = 0; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(source, cache_id, &unchanged_bytes, &error), error); ++ CHECK(unchanged_bytes == checkpoint_bytes); ++ } ++ for (const auto token : suffix_a) { prefill(source, {token}); } ++ const auto expected_a = decode_logits(source, suffix_a.back()); ++ const auto expected_page_a = export_page(source, source->n_past); ++ release(source); // Originating lane and mutable recurrent row are gone. ++ ++ auto * recycled = create(model); ++ prefill(recycled, std::vector(32, 9)); ++ decode_logits(recycled, 10); ++ release(recycled); ++ auto * cold_b = create(model); ++ prefill(cold_b, prefix); ++ for (const auto token : suffix_b) { prefill(cold_b, {token}); } ++ const auto expected_b = decode_logits(cold_b, suffix_b.back()); ++ const auto expected_page_b = export_page(cold_b, cold_b->n_past); ++ release(cold_b); ++ ++ // Invalid identity and boundary must neither claim a lane nor damage the ++ // cached checkpoint; repeatedly exercising create catches leaked claims. ++ auto wrong_tokens = prefix; ++ wrong_tokens.back() = 12; ++ for (int attempt = 0; attempt < 4; ++attempt) { ++ skippy_session * invalid = nullptr; ++ error = nullptr; ++ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, ++ wrong_tokens.data(), wrong_tokens.size(), &invalid, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(invalid == nullptr); ++ } ++ if (require_recurrent) { ++ skippy_session * invalid = nullptr; ++ error = nullptr; ++ CHECK(skippy_session_create_from_resident_prefix(model, cache_id, ++ prefix.data(), prefix.size() - 1, &invalid, &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(invalid == nullptr); ++ } ++ auto restore = [&]() { ++ skippy_session * restored = nullptr; ++ error = nullptr; ++ ok(skippy_session_create_from_resident_prefix(model, cache_id, ++ prefix.data(), prefix.size(), &restored, &error), error); ++ CHECK(restored->token_history == prefix); ++ CHECK(export_page(restored, prefix.size()) == source_page); ++ return restored; ++ }; ++ auto * a = restore(); ++ auto * b = restore(); ++ // All execution lanes are occupied. Cold offload exports the cache-owned ++ // state directly, without restoring over either live borrower. ++ const auto history_a = a->token_history; ++ const auto history_b = b->token_history; ++ size_t kv_bytes = 0; ++ error = nullptr; ++ CHECK(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, ++ 0, prefix.size(), &persistent.page, nullptr, 0, &kv_bytes, &error) ++ == SKIPPY_STATUS_BUFFER_TOO_SMALL); ++ skippy_error_free(error); ++ CHECK(kv_bytes == persistent.payload.size()); ++ error = nullptr; ++ ok(skippy_session_export_resident_kv_page(a, cache_id, 0, persistent.layers, ++ 0, prefix.size(), &persistent.page, persistent.payload.data(), kv_bytes, ++ &kv_bytes, &error), error); ++ CHECK(persistent.payload == source_page); ++ size_t recurrent_bytes = 0; ++ error = nullptr; ++ const auto recurrent_status = skippy_session_export_resident_recurrent_state(a, ++ cache_id, nullptr, 0, &recurrent_bytes, &error); ++ CHECK(recurrent_status == (require_recurrent ? SKIPPY_STATUS_BUFFER_TOO_SMALL : SKIPPY_STATUS_OK)); ++ skippy_error_free(error); ++ CHECK(recurrent_bytes == persistent.recurrent.size()); ++ if (recurrent_bytes) { ++ std::vector retained_recurrent(recurrent_bytes); ++ error = nullptr; ++ ok(skippy_session_export_resident_recurrent_state(a, cache_id, ++ retained_recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); ++ CHECK(retained_recurrent == persistent.recurrent); ++ } ++ CHECK(a->token_history == history_a && b->token_history == history_b); ++ CHECK(a->n_past == static_cast(prefix.size()) && b->n_past == a->n_past); ++ for (size_t i = 0; i < suffix_a.size(); ++i) { ++ prefill(a, {suffix_a[i]}); ++ prefill(b, {suffix_b[i]}); ++ } ++ // Evicting radix ownership must leave both active borrowers valid. ++ error = nullptr; ++ ok(skippy_session_drop_sequence(a, cache_id, &error), error); ++ uint64_t dropped_bytes = 1; ++ error = nullptr; ++ ok(skippy_session_resident_prefix_bytes(a, cache_id, &dropped_bytes, &error), error); ++ CHECK(dropped_bytes == 0); ++ const auto actual_a = decode_logits(a, suffix_a.back()); ++ const auto actual_b = decode_logits(b, suffix_b.back()); ++ float delta_a = 0, delta_b = 0; ++ for (size_t i = 0; i < actual_a.size(); ++i) { ++ delta_a = std::max(delta_a, std::fabs(actual_a[i] - expected_a[i])); ++ delta_b = std::max(delta_b, std::fabs(actual_b[i] - expected_b[i])); ++ } ++ std::fprintf(stderr, "resident fork: max delta a=%.9g b=%.9g page a=%d b=%d\n", delta_a, delta_b, ++ export_page(a, a->n_past) == expected_page_a, export_page(b, b->n_past) == expected_page_b); ++ // Different shared-pool occupancy changes the CPU attention reduction ++ // shape. Measured drift is below 2e-7; reject nonfinite or larger errors ++ // and require the selected greedy token to remain identical. ++ for (const auto value : actual_a) { CHECK(std::isfinite(value)); } ++ for (const auto value : actual_b) { CHECK(std::isfinite(value)); } ++ CHECK(delta_a <= 1e-6f && delta_b <= 1e-6f); ++ CHECK(std::max_element(actual_a.begin(), actual_a.end()) - actual_a.begin() ++ == std::max_element(expected_a.begin(), expected_a.end()) - expected_a.begin()); ++ CHECK(std::max_element(actual_b.begin(), actual_b.end()) - actual_b.begin() ++ == std::max_element(expected_b.begin(), expected_b.end()) - expected_b.begin()); ++ if (require_recurrent) { ++ CHECK(export_page(a, a->n_past) == expected_page_a); ++ CHECK(export_page(b, b->n_past) == expected_page_b); ++ } ++ release(a); ++ release(b); ++ // The resident owner has been evicted. The independently exported payload ++ // still reconstructs both attention and recurrent state in a new lane. ++ auto * persisted = create(model); ++ persistent.restore(persisted, prefix); ++ CHECK(export_page(persisted, prefix.size()) == source_page); ++ for (const auto token : suffix_a) { prefill(persisted, {token}); } ++ const auto persisted_logits = decode_logits(persisted, suffix_a.back()); ++ for (size_t i = 0; i < persisted_logits.size(); ++i) { ++ CHECK(std::isfinite(persisted_logits[i])); ++ CHECK(std::fabs(persisted_logits[i] - expected_a[i]) <= 1e-6f); ++ } ++ release(persisted); ++ } ++ + void adapter_contracts(skippy_model * model) { + auto * session = create(model); + prefill(session, {1, 2}); +@@ -623,24 +905,118 @@ void adapter_contracts(skippy_model * model) { + release(session); + } + ++void dense_resident_configuration(const char * path, skippy_runtime_config config) { ++ config.lane_count = 1; ++ config.kv_unified = SKIPPY_TRISTATE_AUTO; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ ok(skippy_model_open(path, &config, &model, &error), error); ++ CHECK(model->ctx->get_cparams().kv_unified); ++ CHECK(skippy_model_memory_cache_capabilities(model) & SKIPPY_MEMORY_CACHE_RESIDENT); ++ constexpr int32_t cache_id = 8; ++ const std::vector tokens(16, 1); ++ auto * source = create(model); ++ prefill(source, tokens); ++ const auto page = export_page(source, tokens.size()); ++ error = nullptr; ++ ok(skippy_session_save_prefix(source, cache_id, tokens.size(), &error), error); ++ const auto expected = decode_logits(source, 2); ++ release(source); ++ skippy_session * restored = nullptr; ++ error = nullptr; ++ ok(skippy_session_create_from_resident_prefix(model, cache_id, ++ tokens.data(), tokens.size(), &restored, &error), error); ++ CHECK(export_page(restored, tokens.size()) == page); ++ CHECK(decode_logits(restored, 2) == expected); ++ release(restored); ++ error = nullptr; ++ ok(skippy_model_free(model, &error), error); ++ ++ // Explicit overrides remain supported, but must not claim resident APIs ++ // that reject this context. Cover both one stream and real multi-stream. ++ for (const uint32_t lanes : {1u, 2u}) { ++ config.lane_count = lanes; ++ config.kv_unified = SKIPPY_TRISTATE_FALSE; ++ model = nullptr; ++ error = nullptr; ++ ok(skippy_model_open(path, &config, &model, &error), error); ++ CHECK(!model->ctx->get_cparams().kv_unified); ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(!(capabilities & (SKIPPY_MEMORY_CACHE_RESIDENT ++ | SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION ++ | SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT))); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_KV_RECURRENT); ++ source = create(model); ++ prefill(source, tokens); ++ error = nullptr; ++ CHECK(skippy_session_save_prefix(source, cache_id, tokens.size(), &error) ++ == SKIPPY_STATUS_UNSUPPORTED); ++ skippy_error_free(error); ++ release(source); ++ error = nullptr; ++ ok(skippy_model_free(model, &error), error); ++ } ++} ++ + } // namespace + + int main(int argc, char ** argv) { +- CHECK(argc == 4); ++ // Keep this CPU-only serialization regression in the existing canonical ++ // sampling/resident fixture roster as well as its focused invocation. ++ skippy_test_resident_checkpoint_writer(); ++ if (argc == 2 && std::strcmp(argv[1], "resident-writer") == 0) { ++ return 0; ++ } ++ if (argc == 2 && std::strcmp(argv[1], "resident-gpu-long") == 0) { ++ const char * model_path = std::getenv("SKIPPY_NATIVE_TEST_REAL_MODEL"); ++ if (!model_path) { std::fprintf(stderr, "SKIPPY_NATIVE_TEST_REAL_MODEL is unset; skipping real GPU checkpoint proof\n"); return 77; } ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = "CPU"; ++ configure_test_gpu(config); ++ return skippy_test_resident_checkpoint_gpu(model_path, config); ++ } ++ CHECK(argc == 4 || argc == 6); + const bool grammar = std::strcmp(argv[2], "grammar") == 0; + const bool state = std::strcmp(argv[2], "state") == 0; + const bool argmax = std::strcmp(argv[2], "argmax") == 0; +- CHECK(grammar || state || argmax || std::strcmp(argv[2], "penalty") == 0); +- CHECK(std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); ++ const bool resident = std::strcmp(argv[2], "resident") == 0; ++ CHECK(grammar || state || resident || argmax || std::strcmp(argv[2], "penalty") == 0); ++ const bool automatic = resident && std::strcmp(argv[3], "auto") == 0; ++ CHECK(automatic || std::strcmp(argv[3], "dense") == 0 || std::strcmp(argv[3], "recurrent") == 0); ++ CHECK(argc == 4 || resident); + require_recurrent = std::strcmp(argv[3], "recurrent") == 0; + auto config = skippy_runtime_config_default(); + config.selected_backend_device = "CPU"; ++ configure_test_gpu(config); ++ if (argc == 6) { ++ config.cache_type_k = cache_type(argv[4]); ++ config.cache_type_v = cache_type(argv[5]); ++ config.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; ++ } + config.ctx_size = 512; ++ if (resident) { config.lane_count = 2; config.kv_unified = 1; } + skippy_model * model = nullptr; + skippy_error * error = nullptr; + const auto status = skippy_model_open(argv[1], &config, &model, &error); + ok(status, error); +- if (state) { ++ if (automatic) { ++ const auto capabilities = skippy_model_memory_cache_capabilities(model); ++ CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); ++ require_recurrent = capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_CHECKPOINT; ++ } ++ if (config.n_gpu_layers > 0) { ++ CHECK(std::any_of(model->model->tensors_by_name.begin(), model->model->tensors_by_name.end(), ++ [](const auto & item) { ++ if (!item.second->buffer || ggml_backend_buffer_is_host(item.second->buffer)) { return false; } ++ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( ++ ggml_backend_buffer_get_type(item.second->buffer))); ++ return type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; ++ })); ++ std::fprintf(stderr, "GPU ownership test: device=%s requested_layers=%d\n", config.selected_backend_device, config.n_gpu_layers); ++ } ++ if (resident) { ++ resident_prefix_ownership(model, argc == 6); ++ } else if (state) { + // A dense stage's page already carries its whole checkpoint, so the + // partial side payload is intentionally empty there. + CHECK(require_recurrent); +@@ -670,5 +1046,8 @@ int main(int argc, char ** argv) { + error = nullptr; + const auto freed = skippy_model_free(model, &error); + ok(freed, error); ++ if (resident && !require_recurrent) { ++ dense_resident_configuration(argv[1], config); ++ } + return 0; + } +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0018-skippy-open-models-without-rollback-snapshots-unless.patch b/skippy/llama_cpp/patches/0018-skippy-open-models-without-rollback-snapshots-unless.patch new file mode 100644 index 0000000000..56d089ceec --- /dev/null +++ b/skippy/llama_cpp/patches/0018-skippy-open-models-without-rollback-snapshots-unless.patch @@ -0,0 +1,761 @@ +From 4a207402e5e01a3378235f2042211e1b85918f14 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Tue, 10 Nov 2026 21:05:00 +1100 +Subject: [PATCH 18/32] skippy: open models without rollback snapshots unless a + plan needs them + +Restores three changes James Dumay made on the previous pin that the +rebuilt queue lost. + +Ordinary decoding keeps no recurrent rollback snapshots. A caller that +passes recurrent_rollback_tokens = 0, as serving does when no speculative +plan is attached, now gets n_rs_seq = 0; the native side had forced at +least 2, so every lane of a recurrent or hybrid model kept and refreshed two +extra copies of its recurrent state. skippy_runtime_config_default sets the +depth to 2 for C callers that want the old behaviour, and SKIPPY_RS_SEQ may +now name 0. + +Backend samplers serve one output row per sequence +(n_outputs_max_per_seq = 1): upstream builds a sampler chain per row it may +have to sample, which otherwise means one per row of the whole batch. Only +sequences with an attached backend sampler are held to it, so verify windows +and raw readouts keep their multi-row outputs. The MTP sidecar consumes raw +rows and keeps no cap. + +skippy_decode_batch_sampled rejects a batch that names a session twice +before it touches any verification window, instead of decoding two tokens +into one lane. + +skippy-backend-sample-capacity and skippy-recurrent-retention cover the +output cap and explicit snapshot retention on dense and hybrid fixtures. + +No ABI change: skippy_runtime_config keeps its layout. + +Co-Authored-By: Claude Opus 5.5 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + include/skippy/runtime.h | 4 +- + src/CMakeLists.txt | 26 ++ + src/skippy/execution-single.cpp | 11 + + src/skippy/model_loading.cpp | 14 +- + src/skippy/tests/backend_sample_capacity.cpp | 251 ++++++++++++++ + src/skippy/tests/recurrent_retention.cpp | 326 +++++++++++++++++++ + 6 files changed, 627 insertions(+), 5 deletions(-) + create mode 100644 src/skippy/tests/backend_sample_capacity.cpp + create mode 100644 src/skippy/tests/recurrent_retention.cpp + +diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h +index 856c98f97..10ea60e7c 100644 +--- a/include/skippy/runtime.h ++++ b/include/skippy/runtime.h +@@ -125,11 +125,11 @@ struct skippy_runtime_config { + int32_t host_expert_layer_end; + + // Speculative-decoding controls resolved from the attached plan. +- /** @brief Recurrent-state rollback depth (mirrors upstream `n_rs_seq`) for recurrent and hybrid models. Verifying an N-token speculative window in place needs at least N. 0 keeps the default of 2; `SKIPPY_RS_SEQ` overrides either. */ ++ /** @brief Recurrent-state rollback depth (mirrors upstream `n_rs_seq`) for recurrent and hybrid models. 0 disables rollback snapshots; positive values request that depth, bounded to 64. Verifying an N-token speculative input window, including its committed anchor, in place needs at least N; otherwise verification uses a host checkpoint and replay while model computation remains on its selected backend. `SKIPPY_RS_SEQ` overrides the depth, including explicit 0. The native default configuration and a NULL configuration request 2 for legacy C callers. */ + uint32_t recurrent_rollback_tokens; + }; + +-/** @brief Returns a C-safe runtime configuration with all derived-default controls set to auto. */ ++/** @brief Returns a C-safe runtime configuration with derived-default controls set to auto and recurrent rollback depth explicitly set to 2. Set recurrent_rollback_tokens to 0 when no speculative rollback snapshots are wanted. */ + LLAMA_API struct skippy_runtime_config skippy_runtime_config_default(void); + + /** @brief Sentinel for `skippy_runtime_config` tri-state fields: keep the derived default. */ +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index cfd896714..75cb30503 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -435,6 +435,32 @@ if (LLAMA_STAGE_BUILD_TESTS) + add_skippy_verify_rollback_test(qwen4exp qwen4exp-moe.gguf) + # lfm2's fixture slides its attention window, so it checkpoints every window. + add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) ++ add_executable(skippy-backend-sample-capacity skippy/tests/backend_sample_capacity.cpp) ++ target_include_directories(skippy-backend-sample-capacity PRIVATE .) ++ target_compile_features(skippy-backend-sample-capacity PRIVATE cxx_std_17) ++ target_link_libraries(skippy-backend-sample-capacity PRIVATE llama) ++ add_test(NAME skippy_backend_sample_capacity_gemma ++ COMMAND skippy-backend-sample-capacity "${SKIPPY_MODEL_FIXTURE_DIR}/gemma-dense.gguf") ++ set_tests_properties(skippy_backend_sample_capacity_gemma PROPERTIES ++ FIXTURES_REQUIRED skippy-model-loader-fixtures) ++ add_test(NAME skippy_backend_sample_capacity_qwen35 ++ COMMAND skippy-backend-sample-capacity "${SKIPPY_MODEL_FIXTURE_DIR}/qwen35-dense.gguf") ++ set_tests_properties(skippy_backend_sample_capacity_qwen35 PROPERTIES ++ FIXTURES_REQUIRED skippy-noalloc-qwen35-fixture) ++ ++ add_executable(skippy-recurrent-retention skippy/tests/recurrent_retention.cpp) ++ target_include_directories(skippy-recurrent-retention PRIVATE .) ++ target_compile_features(skippy-recurrent-retention PRIVATE cxx_std_17) ++ target_link_libraries(skippy-recurrent-retention PRIVATE llama) ++ add_test(NAME skippy_recurrent_retention_gemma ++ COMMAND skippy-recurrent-retention "${SKIPPY_MODEL_FIXTURE_DIR}/gemma-dense.gguf") ++ set_tests_properties(skippy_recurrent_retention_gemma PROPERTIES ++ FIXTURES_REQUIRED skippy-model-loader-fixtures ENVIRONMENT "SKIPPY_RS_SEQ=") ++ add_test(NAME skippy_recurrent_retention_qwen35 ++ COMMAND skippy-recurrent-retention "${SKIPPY_MODEL_FIXTURE_DIR}/qwen35-dense.gguf") ++ set_tests_properties(skippy_recurrent_retention_qwen35 PROPERTIES ++ FIXTURES_REQUIRED skippy-noalloc-qwen35-fixture ENVIRONMENT "SKIPPY_RS_SEQ=") ++ + add_executable(skippy-sampling-history + skippy/tests/sampling_history.cpp + skippy/tests/resident_checkpoint_gpu.cpp +diff --git a/src/skippy/execution-single.cpp b/src/skippy/execution-single.cpp +index 8a1b320ff..965880071 100644 +--- a/src/skippy/execution-single.cpp ++++ b/src/skippy/execution-single.cpp +@@ -195,6 +195,17 @@ enum skippy_status skippy_decode_batch_sampled( + return SKIPPY_STATUS_UNSUPPORTED; + } + ++ // A legacy decode batch still samples only one row per session. Reject ++ // duplicate lanes before settling any pending verification window. ++ std::unordered_set unique_sessions; ++ for (size_t i = 0; i < request_count; ++i) { ++ if (!unique_sessions.insert(sessions[i]).second) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, ++ "batched token decode requires unique sessions"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ } ++ + const int32_t n_tokens = static_cast(request_count); + llama_batch batch = llama_batch_init(n_tokens, 0, 1); + batch.n_tokens = n_tokens; +diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp +index 5bfd47c93..bbc1c2d42 100644 +--- a/src/skippy/model_loading.cpp ++++ b/src/skippy/model_loading.cpp +@@ -590,6 +590,7 @@ struct skippy_runtime_config skippy_runtime_config_default(void) { + config.swa_full = SKIPPY_TRISTATE_AUTO; + config.op_offload = SKIPPY_TRISTATE_AUTO; + config.split_mode = SKIPPY_TRISTATE_AUTO; ++ config.recurrent_rollback_tokens = 2; + return config; + } + +@@ -692,6 +693,11 @@ enum skippy_status skippy_finish_model_open( + params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); + params.n_threads_batch = config != nullptr && config->n_threads_batch > 0 ? config->n_threads_batch : params.n_threads; + params.n_seq_max = stage_model->lane_count; ++ // Ordinary session APIs sample only the final output row per sequence. ++ // Keep the separate global output capacity for raw verification/readouts. ++ constexpr uint32_t backend_sampled_rows_per_sequence = 1; ++ params.n_outputs_max_per_seq = backend_sampled_rows_per_sequence; ++ + // Cache-owned sequence IDs share the attention pool even with one lane. + params.kv_unified = true; + if (config != nullptr) { +@@ -738,9 +744,9 @@ enum skippy_status skippy_finish_model_open( + // tokens needs N, or verify falls back to a host copy. Each snapshot + // is another copy of the recurrent state per sequence, so the caller + // sizes it from its speculative plan. SKIPPY_RS_SEQ overrides it. +- const uint32_t planned_rs_seq = config != nullptr ? config->recurrent_rollback_tokens : 0; +- const uint32_t default_rs_seq = std::min(std::max(planned_rs_seq, 2), 64); +- params.n_rs_seq = std::max(params.n_rs_seq, skippy_env_u32("SKIPPY_RS_SEQ", default_rs_seq, 2, 64)); ++ const uint32_t planned_rs_seq = config != nullptr ? config->recurrent_rollback_tokens : 2; ++ const uint32_t default_rs_seq = std::min(planned_rs_seq, 64); ++ params.n_rs_seq = skippy_env_u32("SKIPPY_RS_SEQ", default_rs_seq, 0, 64); + params.kv_unified = true; + } + // Multi-lane activation exports rely on the shared KV pool's batch order. +@@ -862,6 +868,8 @@ enum skippy_status skippy_finish_model_open( + if (skippy_should_create_native_mtp_sidecar(model, config)) { + llama_context_params mtp_params = params; + mtp_params.ctx_type = LLAMA_CONTEXT_TYPE_MTP; ++ // MTP consumes raw multirow outputs, without session backend samplers. ++ mtp_params.n_outputs_max_per_seq = 0; + mtp_params.embeddings = false; + stage_model->mtp_ctx = llama_init_from_model_with_graph_inputs(model, mtp_params, graph_build_inputs); + if (stage_model->mtp_ctx != nullptr) { +diff --git a/src/skippy/tests/backend_sample_capacity.cpp b/src/skippy/tests/backend_sample_capacity.cpp +new file mode 100644 +index 000000000..b234872a7 +--- /dev/null ++++ b/src/skippy/tests/backend_sample_capacity.cpp +@@ -0,0 +1,251 @@ ++#include "skippy.h" ++#include "../runtime_types.h" ++#include "llama-context.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++namespace { ++ ++void ok(skippy_status status, skippy_error * error) { ++ if (status != SKIPPY_STATUS_OK) { ++ std::fprintf(stderr, "native failure: %s\n", error ? error->message : "no detail"); ++ std::exit(1); ++ } ++ skippy_error_free(error); ++} ++ ++skippy_session * create(skippy_model * model) { ++ skippy_session * session = nullptr; ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_create(model, &session, &error); ++ ok(status, error); ++ return session; ++} ++ ++skippy_sampling_config greedy() { ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.temperature = 0.0f; ++ sampling.repeat_penalty = 1.0f; ++ sampling.reasoning_budget_tokens = -1; ++ return sampling; ++} ++ ++bool valid_token(skippy_session * session, llama_token token) { ++ const auto * vocab = llama_model_get_vocab(llama_get_model(session->ctx)); ++ return token >= 0 && token < llama_vocab_n_tokens(vocab); ++} ++ ++void prefill(skippy_session * session) { ++ const llama_token tokens[] = {1, 2}; ++ size_t bytes = 0; ++ skippy_error * error = nullptr; ++ const auto status = skippy_prefill_chunk(session, tokens, 2, ++ nullptr, 0, nullptr, 0, &bytes, &error); ++ ok(status, error); ++} ++ ++void reset(skippy_session * session) { ++ skippy_error * error = nullptr; ++ const auto status = skippy_session_reset(session, &error); ++ ok(status, error); ++ prefill(session); ++} ++ ++void sampled_multirow(skippy_session * a, skippy_session * b) { ++ const std::array tokens_a = {3, 4, 5}; ++ const std::array tokens_b = {6, 7}; ++ const auto sampling_a = greedy(); ++ const auto sampling_b = greedy(); ++ skippy_error * configure_error = nullptr; ++ auto configure_status = skippy_session_configure_chat_sampling( ++ a, &sampling_a, "{}", a->token_history.size(), &configure_error); ++ ok(configure_status, configure_error); ++ configure_error = nullptr; ++ configure_status = skippy_session_configure_chat_sampling( ++ b, &sampling_b, "{}", b->token_history.size(), &configure_error); ++ ok(configure_status, configure_error); ++ CHECK(a->sampling_backend_enabled && b->sampling_backend_enabled); ++ std::array requests{}; ++ requests[0].session = a; ++ requests[0].token_ids = tokens_a.data(); ++ requests[0].token_count = tokens_a.size(); ++ requests[0].sampling = &sampling_a; ++ requests[0].sample_last = true; ++ requests[1].session = b; ++ requests[1].token_ids = tokens_b.data(); ++ requests[1].token_count = tokens_b.size(); ++ requests[1].sampling = &sampling_b; ++ requests[1].sample_last = true; ++ std::array indexes{}; ++ std::array predicted{}; ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ const auto status = skippy_iteration_batch_sampled(requests.data(), requests.size(), ++ nullptr, nullptr, nullptr, nullptr, indexes.data(), predicted.data(), ++ predicted.size(), &count, &error); ++ ok(status, error); ++ CHECK(count == 2 && indexes[0] == 0 && indexes[1] == 1); ++ // This fixture proves output capacity and request-index ownership; model ++ // numerical parity is covered by the existing serving/correctness gates. ++ CHECK(valid_token(a, predicted[0]) && valid_token(b, predicted[1])); ++ CHECK(a->sampling_backend_enabled && b->sampling_backend_enabled); ++ CHECK(a->ctx->get_cparams().n_outputs_max_per_seq == 1); ++} ++ ++void raw_verify(skippy_session * a, skippy_session * b) { ++ const llama_token tokens[] = {8, 9, 10}; ++ std::array predicted{}; ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ const auto status = skippy_verify_tokens(b, tokens, 3, predicted.data(), ++ predicted.size(), &count, &error); ++ ok(status, error); ++ CHECK(count == 3 && !b->sampling_backend_enabled && b->sampling_backend_retired); ++ CHECK(a->sampling_backend_enabled); ++ for (int row = 0; row < 3; ++row) { ++ CHECK(valid_token(b, predicted[row])); ++ const float * logits = llama_get_logits_ith(b->ctx, row); ++ CHECK(logits && std::isfinite(logits[0])); ++ } ++} ++ ++// This compatibility test intentionally calls the deprecated public API. ++#pragma GCC diagnostic push ++#pragma GCC diagnostic ignored "-Wdeprecated-declarations" ++void legacy_batch_contract(skippy_session * a, skippy_session * b, bool duplicate) { ++ std::array sessions = {a, duplicate ? a : b}; ++ const llama_token tokens[] = {17, 18}; ++ std::array predicted = {-1, -1}; ++ const auto before_past = a->n_past; ++ const auto before_history = a->token_history; ++ const auto before_window = a->inplace_verify_window.valid; ++ const auto before_checkpoints = a->verify_checkpoints.size(); ++ const auto before_in_place = a->verify_windows_in_place; ++ const auto before_checkpointed = a->verify_windows_checkpointed; ++ skippy_error * error = nullptr; ++ const auto status = skippy_decode_batch_sampled(sessions.data(), tokens, nullptr, ++ sessions.size(), predicted.data(), predicted.size(), &error); ++ if (duplicate) { ++ CHECK(status == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(a->n_past == before_past && a->token_history == before_history); ++ CHECK(a->inplace_verify_window.valid == before_window); ++ CHECK(a->verify_checkpoints.size() == before_checkpoints); ++ CHECK(a->verify_windows_in_place == before_in_place); ++ CHECK(a->verify_windows_checkpointed == before_checkpointed); ++ CHECK(predicted[0] == -1 && predicted[1] == -1); ++ } else { ++ ok(status, error); ++ CHECK(valid_token(a, predicted[0]) && valid_token(b, predicted[1])); ++ } ++} ++#pragma GCC diagnostic pop ++ ++// The sampler on A must not cap B's raw all-output rows in the SAME decode. ++void mixed_sampled_and_raw(skippy_session * a, skippy_session * b) { ++ llama_batch batch = llama_batch_init(4, 0, 1); ++ batch.n_tokens = 4; ++ for (int row = 0; row < 4; ++row) { ++ const bool sampled = row == 0; ++ batch.token[row] = 11 + row; ++ batch.pos[row] = sampled ? a->n_past : b->n_past + row - 1; ++ batch.n_seq_id[row] = 1; ++ batch.seq_id[row][0] = sampled ? a->seq_id : b->seq_id; ++ batch.logits[row] = 1; ++ } ++ CHECK(a->ctx->decode(batch) == 0); ++ CHECK(valid_token(a, llama_get_sampled_token_ith(a->ctx, 0))); ++ for (int row = 1; row < 4; ++row) { ++ const float * logits = llama_get_logits_ith(a->ctx, row); ++ CHECK(logits && std::isfinite(logits[0])); ++ } ++ llama_batch_free(batch); ++ // This direct native contract probe deliberately bypasses session history. ++ // Reset both sessions before using public session APIs again. ++ reset(a); ++ reset(b); ++ sampled_multirow(a, b); ++} ++ ++void readout_detaches_only_its_lane(skippy_session * a, skippy_session * b) { ++ const llama_token tokens[] = {15, 16}; ++ const auto sampling = greedy(); ++ const llama_token selected[] = {0, 1}; ++ float scores[2]{}; ++ skippy_token_score_request readout{selected, 2, scores}; ++ std::array requests{}; ++ requests[0].session = a; ++ requests[0].token_ids = tokens; ++ requests[0].token_count = 1; ++ requests[0].sampling = &sampling; ++ requests[0].sample_last = true; ++ requests[1].session = b; ++ requests[1].token_ids = tokens; ++ requests[1].token_count = 2; ++ requests[1].readout = &readout; ++ size_t index = 99; ++ llama_token predicted = -1; ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ const auto status = skippy_iteration_batch_sampled(requests.data(), requests.size(), ++ nullptr, nullptr, nullptr, nullptr, &index, &predicted, 1, &count, &error); ++ ok(status, error); ++ CHECK(count == 1 && index == 0 && valid_token(a, predicted)); ++ CHECK(std::isfinite(scores[0]) && std::isfinite(scores[1])); ++ CHECK(a->sampling_backend_enabled && !b->sampling_backend_enabled); ++ CHECK(b->sampling_backend_retired); ++ reset(b); ++ reset(a); ++ sampled_multirow(a, b); ++} ++ ++} // namespace ++ ++int main(int argc, char ** argv) { ++ CHECK(argc == 2); ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = "CPU"; ++ config.n_gpu_layers = 0; ++ config.ctx_size = 128; ++ config.n_batch = 32; ++ config.n_ubatch = 32; ++ config.lane_count = 2; ++ config.kv_unified = SKIPPY_TRISTATE_TRUE; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ auto status = skippy_model_open(argv[1], &config, &model, &error); ++ ok(status, error); ++ CHECK(model->ctx->get_cparams().n_outputs_max >= 32); ++ CHECK(model->ctx->get_cparams().n_outputs_max_per_seq == 1); ++ auto * a = create(model); ++ auto * b = create(model); ++ prefill(a); ++ prefill(b); ++ sampled_multirow(a, b); ++ legacy_batch_contract(a, b, false); ++ raw_verify(a, b); ++ legacy_batch_contract(b, a, true); ++ mixed_sampled_and_raw(a, b); ++ readout_detaches_only_its_lane(a, b); ++ error = nullptr; ++ status = skippy_session_free(a, &error); ++ ok(status, error); ++ error = nullptr; ++ status = skippy_session_free(b, &error); ++ ok(status, error); ++ error = nullptr; ++ status = skippy_model_free(model, &error); ++ ok(status, error); ++ std::fprintf(stderr, "BACKEND_SAMPLE_CAPACITY total>=32 sampled_per_sequence=1 mixed_raw_rows=3 reset=PASS\n"); ++ return 0; ++} +diff --git a/src/skippy/tests/recurrent_retention.cpp b/src/skippy/tests/recurrent_retention.cpp +new file mode 100644 +index 000000000..8eacda334 +--- /dev/null ++++ b/src/skippy/tests/recurrent_retention.cpp +@@ -0,0 +1,326 @@ ++// Explicit snapshot retention must preserve outputs and cache continuation. ++#include "skippy.h" ++#include "../runtime_types.h" ++#include "../state_memory.h" ++#include "llama-context.h" ++#include "llama-memory-recurrent.h" ++#include "llama-model.h" ++#include "ggml-cpu.h" ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++namespace { ++constexpr size_t teacher_steps = 32; ++constexpr float logit_limit = 1e-6f; ++const std::vector prefix = {1, 7, 3, 9, 4, 12, 5, 2}; ++using Trace = std::vector>; ++const char * test_backend = "CPU"; ++bool test_gpu = false; ++ ++template void ok(Call call) { ++ skippy_error * error = nullptr; ++ const auto status = call(&error); ++ if (status != SKIPPY_STATUS_OK) { ++ std::fprintf(stderr, "native status=%d: %s\n", status, error ? error->message : "no detail"); ++ std::exit(1); ++ } ++ skippy_error_free(error); ++} ++ ++struct Model { ++ skippy_model * value; ++ explicit Model(skippy_model * model) : value(model) {} ++ Model(const Model &) = delete; ++ ~Model() { ok([&](auto error) { return skippy_model_free(value, error); }); } ++}; ++ ++struct Session { ++ skippy_session * value = nullptr; ++ explicit Session(skippy_model * model) { ++ ok([&](auto error) { return skippy_session_create(model, &value, error); }); ++ } ++ Session(const Session &) = delete; ++ void release() { ++ if (value) { ++ ok([&](auto error) { return skippy_session_free(value, error); }); ++ value = nullptr; ++ } ++ } ++ ~Session() { release(); } ++}; ++ ++skippy_runtime_config config_for(uint32_t retention) { ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = test_backend; ++ config.n_gpu_layers = test_gpu ? 99 : 0; ++ config.ctx_size = 256; ++ config.n_batch = 32; ++ config.n_ubatch = 32; ++ config.lane_count = 2; ++ config.kv_unified = SKIPPY_TRISTATE_TRUE; ++ config.recurrent_rollback_tokens = retention; ++ return config; ++} ++ ++Model open(const char * path, const skippy_runtime_config * config) { ++ skippy_model * model = nullptr; ++ ok([&](auto error) { return skippy_model_open(path, config, &model, error); }); ++ if (test_gpu) { ++ auto * memory = skippy_memory_recurrent_adapter(model->ctx->get_memory()); ++ CHECK(memory != nullptr); ++ size_t device_tensors = 0; ++ for (auto * tensor : memory->r_l) { ++ if (!tensor) { continue; } ++ CHECK(tensor->buffer != nullptr); ++ const auto type = ggml_backend_dev_type(ggml_backend_buft_get_device( ++ ggml_backend_buffer_get_type(tensor->buffer))); ++ CHECK(type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU); ++ ++device_tensors; ++ } ++ CHECK(device_tensors > 0); ++ std::fprintf(stderr, "GPU_STATE tensors=%zu device=%s\n", device_tensors, test_backend); ++ } ++ return Model(model); ++} ++ ++bool recurrent(skippy_model * model) { ++ return skippy_memory_recurrent_adapter(model->ctx->get_memory()) != nullptr; ++} ++ ++void check_retention(skippy_model * model, uint32_t requested) { ++ auto * memory = skippy_memory_recurrent_adapter(model->ctx->get_memory()); ++ if (!memory) { ++ CHECK(model->ctx->get_cparams().n_rs_seq == 0); ++ return; ++ } ++ CHECK(model->ctx->get_cparams().n_rs_seq == requested); ++ CHECK(memory->n_rs_seq == requested); ++ size_t tensors = 0; ++ for (auto * tensor : memory->r_l) { ++ if (!tensor) { continue; } ++ CHECK(tensor->ne[1] == static_cast(memory->size) * (1 + requested)); ++ ++tensors; ++ } ++ CHECK(tensors > 0); ++ std::fprintf(stderr, "RETENTION depth=%u snapshot_groups=%u tensors=%zu\n", ++ memory->n_rs_seq, 1 + memory->n_rs_seq, tensors); ++} ++ ++void prefill(skippy_session * session, const std::vector & tokens) { ++ size_t bytes = 0; ++ ok([&](auto error) { ++ return skippy_prefill_chunk(session, tokens.data(), tokens.size(), ++ nullptr, 0, nullptr, 0, &bytes, error); ++ }); ++} ++ ++std::vector decode_logits(skippy_session * session, llama_token token) { ++ // Correctness-only full-row readback; timing arms never use this path. ++ CHECK(!session->sampling_backend_enabled); ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.temperature = 0; ++ sampling.repeat_penalty = 1; ++ sampling.reasoning_budget_tokens = -1; ++ llama_token predicted = -1; ++ size_t bytes = 0; ++ ok([&](auto error) { ++ return skippy_decode_step_sampled(session, token, &sampling, ++ nullptr, 0, nullptr, 0, &bytes, &predicted, error); ++ }); ++ const int32_t vocabulary = llama_vocab_n_tokens(llama_model_get_vocab(session->stage_model->model)); ++ CHECK(predicted >= 0 && predicted < vocabulary); ++ const float * logits = llama_get_logits_ith(session->ctx, -1); ++ CHECK(logits != nullptr); ++ return std::vector(logits, logits + vocabulary); ++} ++ ++Trace teacher_trace(skippy_session * session) { ++ Trace result; ++ for (size_t step = 0; step < teacher_steps; ++step) { ++ result.push_back(decode_logits(session, static_cast(1 + (step * 7) % 23))); ++ } ++ return result; ++} ++ ++void compare(const Trace & reference, const Trace & candidate, const char * label) { ++ CHECK(reference.size() == teacher_steps && candidate.size() == reference.size()); ++ float maximum = 0; ++ for (size_t step = 0; step < reference.size(); ++step) { ++ CHECK(reference[step].size() == candidate[step].size()); ++ for (size_t token = 0; token < reference[step].size(); ++token) { ++ CHECK(std::isfinite(reference[step][token]) && std::isfinite(candidate[step][token])); ++ maximum = std::max(maximum, std::fabs(reference[step][token] - candidate[step][token])); ++ } ++ } ++ std::fprintf(stderr, "FULL_VOCAB label=%s steps=%zu max_abs=%.9g limit=%.9g\n", ++ label, reference.size(), maximum, logit_limit); ++ CHECK(maximum <= logit_limit); ++} ++ ++struct Snapshot { ++ skippy_kv_page_desc page{}; ++ std::vector kv; ++ std::vector state; ++ ++ explicit Snapshot(skippy_session * session) { ++ const int32_t layers = session->stage_model->model->hparams.n_layer(); ++ size_t bytes = 0; ++ skippy_error * error = nullptr; ++ auto status = skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &page, nullptr, 0, &bytes, &error); ++ CHECK(status == SKIPPY_STATUS_BUFFER_TOO_SMALL); ++ skippy_error_free(error); ++ CHECK(bytes > 0); ++ kv.resize(bytes); ++ ok([&](auto out_error) { ++ return skippy_export_kv_page(session, 0, layers, 0, session->n_past, ++ &page, kv.data(), kv.size(), &bytes, out_error); ++ }); ++ bytes = 0; ++ error = nullptr; ++ status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); ++ CHECK(status == SKIPPY_STATUS_BUFFER_TOO_SMALL || status == SKIPPY_STATUS_OK); ++ skippy_error_free(error); ++ state.resize(bytes); ++ if (bytes) { ++ ok([&](auto out_error) { ++ return skippy_export_recurrent_state(session, state.data(), state.size(), &bytes, out_error); ++ }); ++ } ++ } ++ ++ void restore(skippy_session * session) const { ++ ok([&](auto error) { return skippy_import_kv_page(session, &page, kv.data(), kv.size(), error); }); ++ if (!state.empty()) { ++ ok([&](auto error) { ++ return skippy_import_recurrent_state(session, state.data(), state.size(), error); ++ }); ++ } ++ ok([&](auto error) { return skippy_session_set_position(session, prefix.size(), error); }); ++ ok([&](auto error) { ++ return skippy_session_restore_token_history(session, prefix.data(), prefix.size(), error); ++ }); ++ } ++}; ++ ++void same_snapshot(const Snapshot & before, const Snapshot & after) { ++ CHECK(before.kv == after.kv); ++ CHECK(before.state == after.state); ++} ++ ++void fresh_context_restore(const char * path, const skippy_runtime_config & config, ++ const Snapshot & saved, const Trace & reference) { ++ auto fresh = open(path, &config); ++ Session restored(fresh.value); ++ saved.restore(restored.value); ++ same_snapshot(saved, Snapshot(restored.value)); ++ compare(reference, teacher_trace(restored.value), "fresh-context-import"); ++} ++ ++Trace cache_continuation(skippy_model * model, const char * path, ++ const skippy_runtime_config & config) { ++ Session source(model); ++ Session parked(model); ++ prefill(source.value, prefix); ++ prefill(parked.value, {3, 4, 6}); ++ const Snapshot parked_before(parked.value); ++ const Snapshot saved(source.value); ++ CHECK(!recurrent(model) || !saved.state.empty()); ++ const int32_t cache_id = static_cast(model->lane_count * 2); ++ ok([&](auto error) { ++ return skippy_session_save_prefix(source.value, cache_id, prefix.size(), error); ++ }); ++ const Trace reference = teacher_trace(source.value); ++ source.release(); ++ Session restored(model); ++ ok([&](auto error) { ++ return skippy_session_restore_prefix(restored.value, cache_id, prefix.data(), prefix.size(), error); ++ }); ++ same_snapshot(saved, Snapshot(restored.value)); ++ compare(reference, teacher_trace(restored.value), "resident-restore"); ++ same_snapshot(parked_before, Snapshot(parked.value)); ++ restored.release(); ++ Session imported(model); ++ saved.restore(imported.value); ++ same_snapshot(saved, Snapshot(imported.value)); ++ compare(reference, teacher_trace(imported.value), "component-import"); ++ same_snapshot(parked_before, Snapshot(parked.value)); ++ ok([&](auto error) { return skippy_session_reset(imported.value, error); }); ++ CHECK(imported.value->verify_checkpoints.empty() && !imported.value->inplace_verify_window.valid); ++ prefill(imported.value, prefix); ++ compare(reference, teacher_trace(imported.value), "reset"); ++ fresh_context_restore(path, config, saved, reference); ++ return reference; ++} ++ ++void cross_mode_restore(skippy_model * source_model, skippy_model * target_model) { ++ Session source(source_model); ++ prefill(source.value, prefix); ++ const Snapshot saved(source.value); ++ const Trace reference = teacher_trace(source.value); ++ Session restored(target_model); ++ saved.restore(restored.value); ++ same_snapshot(saved, Snapshot(restored.value)); ++ compare(reference, teacher_trace(restored.value), "cross-mode-current-state-import"); ++} ++ ++void defaults(const char * path) { ++ CHECK(skippy_runtime_config_default().recurrent_rollback_tokens == 2); ++ { ++ auto config = config_for(2); ++ auto model = open(path, &config); ++ check_retention(model.value, 2); ++ } ++ { ++ auto model = open(path, nullptr); ++ check_retention(model.value, 2); ++ } ++ { ++ auto config = config_for(1); ++ auto model = open(path, &config); ++ check_retention(model.value, 1); ++ } ++} ++} // namespace ++ ++int main(int argc, char ** argv) { ++ CHECK(argc == 2 || (argc == 3 && std::string(argv[2]) == "gpu")); ++ test_gpu = argc == 3; ++ if (!test_gpu) { ++ // Keep portable correctness strictly CPU-only, including NULL config. ++ ggml_backend_register(ggml_backend_cpu_reg()); ++ } ++ llama_backend_init(); ++ if (test_gpu) { ++ auto * device = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); ++ if (!device) { device = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU); } ++ CHECK(device != nullptr); ++ test_backend = ggml_backend_dev_name(device); ++ } ++ std::fprintf(stderr, "TEST_BACKEND name=%s gpu=%d\n", test_backend, test_gpu); ++ const char * override_depth = std::getenv("SKIPPY_RS_SEQ"); ++ CHECK(override_depth == nullptr || override_depth[0] == '\0'); ++ defaults(argv[1]); ++ auto off_config = config_for(0); ++ auto retained_config = config_for(2); ++ auto off = open(argv[1], &off_config); ++ auto retained = open(argv[1], &retained_config); ++ check_retention(off.value, 0); ++ check_retention(retained.value, 2); ++ compare(cache_continuation(off.value, argv[1], off_config), ++ cache_continuation(retained.value, argv[1], retained_config), "zero-versus-two"); ++ cross_mode_restore(off.value, retained.value); ++ cross_mode_restore(retained.value, off.value); ++ std::fprintf(stderr, "RECURRENT_RETENTION defaults=2 explicit_off=0 positive=1 teacher_steps=32 PASS\n"); ++ return 0; ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch new file mode 100644 index 0000000000..fed63180f3 --- /dev/null +++ b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch @@ -0,0 +1,3038 @@ +From cf937afd998fce2d584ed5ed092205deded25a01 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Mon, 2 Nov 2026 09:00:00 +1100 +Subject: [PATCH 19/32] skippy: report native trace spans and GPU command + timing + +skippy/tracing.h reports where time goes inside a native call, for a +caller that already times the call itself. skippy_set_native_span_callback +delivers one span per finished phase of host work, on the thread that did +it: Skippy batch preparation, output handling and sampling; llama decode, +batch init, memory slot search, output reserve, per-ubatch graph build, +allocation, input upload and submission, output extraction, the recurrent +state sync and synchronize (the host waiting for the device); sampler +chains, each sampler and grammar; tokenization; KV and recurrent memory +operations, KV page export and import, and sequence state save and +restore; graph reserve, backend and memory creation, and model load +(GGUF open, hyperparameters, vocabulary, tensors and their data) at +startup. Spans nest under the open +span on their thread, else under the tag the caller set with +skippy_set_trace_tag, and work a thread does on another's behalf can adopt +that thread's open span as its parent; span ids carry +SKIPPY_NATIVE_SPAN_ID_BIT so they never collide with caller tags. +skippy_set_gpu_command_timing_callback reports, for each unit of device +work, when it was encoded and when the GPU ran it, carrying the submitting +thread's tag. SKIPPY_FEATURE_NATIVE_TRACING advertises the symbols; with no +callback installed a span costs one atomic load. + +Backends expose the capability through three registry procs, +ggml_backend_set_command_timing_callback, ggml_backend_set_command_timing_tag +and ggml_backend_set_trace_span_callback, so Skippy never links a backend +directly. Metal times each command buffer with a completed handler +(GPUStartTime/GPUEndTime) and its encode window, numbering graph computes +like GGML_METAL_CAPTURE_COMPUTE so a slow graph seen in a trace can be +captured for Xcode by number. It reports compiling each kernel library, +opening the pipeline archive, initialising the device library and compiling +each pipeline on first use, allocating and mapping buffers and their +residency sets, blocking uploads and downloads, output copies, graph +optimisation and waiting on the last command buffer. Device initialisation runs before anyone can +listen, so spans that end before the first span callback are kept, a +bounded number, and delivered when it arrives. A dispatch worker encoding a +command buffer carries that buffer's tag, so a pipeline compiled there +lands under the call that submitted the graph. + +Each command timing record also says what its graph nodes did. Backends +classify nodes as attention (flash attention, or the masked soft max and +K/Q, K/Q/V products of unfused attention), mat-muls with weights, +recurrent and linear-attention state (SSM, RWKV, gated linear attention, +delta-net updates and their cache copies), KV cache writes, and other +work; views and reshapes have no class. The record counts nodes and the +bytes they read per class (a gather or row write counts only its rows, not +the cache it indexes), the model layer of its first named node, the most +recurrent states one gather reads and how many of them are copied back +unchanged because no sequence of the batch owns them, and for attention +the most KV cells one query addresses (its row list for per-sequence row +lists, else the K/V span, or the K/Q product's K span for unfused +attention), the query rows, and how many attention nodes read row lists or +are flash attention. +With GGML_METAL_OP_PROFILE=1 and command timing installed, Metal splits +each graph into one command buffer per run of same-class nodes, encoded in +order on the calling thread, so the GPU times every class by itself; +splitting serialises the graph and stops fusion across class boundaries, +so totals grow while shares stay meaningful. +The first compute of a graph with a new node count reports an +mtl.graph_ops span whose detail counts the graph's nodes by op, so the +graphs two runtimes build for the same model can be compared op by op. + +The ABI version does not change: SKIPPY_FEATURE_NATIVE_TRACING advertises +the symbols and the Rust mirror looks them up at run time, so a runtime +built without this patch simply reports no native spans. + +Co-Authored-By: Claude Opus 5.5 +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/include/ggml-backend.h | 105 +++++ + ggml/src/ggml-metal/CMakeLists.txt | 1 + + ggml/src/ggml-metal/ggml-metal-context.m | 129 ++++++ + ggml/src/ggml-metal/ggml-metal-device.m | 24 + + ggml/src/ggml-metal/ggml-metal-timing.cpp | 529 ++++++++++++++++++++++ + ggml/src/ggml-metal/ggml-metal-timing.h | 102 +++++ + ggml/src/ggml-metal/ggml-metal.cpp | 10 + + include/skippy.h | 1 + + include/skippy/common.h | 2 + + include/skippy/tracing.h | 197 ++++++++ + src/CMakeLists.txt | 1 + + src/llama-context.cpp | 52 ++- + src/llama-kv-cache.cpp | 10 + + src/llama-memory-recurrent.cpp | 8 + + src/llama-model.cpp | 3 + + src/llama-sampler.cpp | 7 + + src/llama-vocab.cpp | 2 + + src/llama.cpp | 8 + + src/skippy/abi.cpp | 1 + + src/skippy/activation.cpp | 3 + + src/skippy/execution-batch.cpp | 6 + + src/skippy/model_loading.cpp | 17 + + src/skippy/sampling.cpp | 2 + + src/skippy/speculative_decoding.cpp | 2 + + src/skippy/trace_scope.h | 61 +++ + src/skippy/tracing.cpp | 272 +++++++++++ + tests/CMakeLists.txt | 4 + + tests/test-skippy-tracing-metal.cpp | 155 +++++++ + tests/test-skippy-tracing.cpp | 306 +++++++++++++ + 29 files changed, 2018 insertions(+), 2 deletions(-) + create mode 100644 ggml/src/ggml-metal/ggml-metal-timing.cpp + create mode 100644 ggml/src/ggml-metal/ggml-metal-timing.h + create mode 100644 include/skippy/tracing.h + create mode 100644 src/skippy/trace_scope.h + create mode 100644 src/skippy/tracing.cpp + create mode 100644 tests/test-skippy-tracing-metal.cpp + create mode 100644 tests/test-skippy-tracing.cpp + +diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h +index 0427fda49..f326769a3 100644 +--- a/ggml/include/ggml-backend.h ++++ b/ggml/include/ggml-backend.h +@@ -268,6 +268,111 @@ extern "C" { + char * error, + size_t error_capacity); + ++ // Command timing, exposed by a backend registry as the procs ++ // "ggml_backend_set_command_timing_callback" and ++ // "ggml_backend_set_command_timing_tag". A backend reports one record per ++ // unit of submitted device work (a Metal command buffer) once the device ++ // has finished it. Times are Unix nanoseconds; 0 when unknown. ++ // What a command's graph nodes do. Views and reshapes do no work and ++ // belong to no class. ++ enum ggml_backend_op_class { ++ GGML_BACKEND_OP_CLASS_OTHER, ++ // attention over the KV cache: flash attention, or the masked soft ++ // max and the K/Q and K/Q/V products the graph names "kq" and "kqv" ++ GGML_BACKEND_OP_CLASS_ATTENTION, ++ // matrix products with weights ++ GGML_BACKEND_OP_CLASS_MATMUL, ++ // recurrent and linear-attention state: SSM, RWKV, gated linear ++ // attention and delta-net updates, and copies to or from their cache ++ GGML_BACKEND_OP_CLASS_RECURRENT, ++ // writes into the attention KV cache ++ GGML_BACKEND_OP_CLASS_KV_WRITE, ++ GGML_BACKEND_OP_CLASS_COUNT, ++ }; ++ ++ struct ggml_backend_command_timing { ++ // the submitting thread's tag when the graph was submitted ++ uint64_t tag; ++ // backend instance, and its 1-based graph compute count ++ uint32_t context_id; ++ uint32_t compute_index; ++ // execution order of this command within the graph compute ++ uint32_t command_index; ++ uint32_t command_count; ++ uint32_t node_count; ++ // 0 when the device completed the command ++ int32_t status; ++ int64_t encode_start_unix_ns; ++ int64_t encode_end_unix_ns; ++ int64_t execute_start_unix_ns; ++ int64_t execute_end_unix_ns; ++ // The class every classified node of the command belongs to, or ++ // GGML_BACKEND_OP_CLASS_COUNT when it mixes classes. A backend that ++ // splits a graph at class boundaries (op profiling) sets one class ++ // per command and `split_by_class`. ++ int32_t op_class; ++ // the model layer of the command's first layer-named node, -1 if none ++ int32_t layer; ++ uint32_t split_by_class; ++ // attention nodes: the most KV cells one query addresses (the row ++ // list length when attention reads per-sequence row lists, else the ++ // K/V span; for unfused attention the K/Q product's K span), the ++ // most query rows one node processes, how many nodes read row lists, ++ // and how many are flash attention (the rest are unfused) ++ uint32_t attention_kv_cells; ++ uint32_t attention_queries; ++ uint32_t attention_row_list_nodes; ++ uint32_t attention_flash_nodes; ++ // per class: nodes, and the bytes they read; a gather counts the rows ++ // it reads and a row write the rows it writes, not the tensor they ++ // index, and attention counts only the K/V rows a node addresses ++ uint32_t class_nodes[GGML_BACKEND_OP_CLASS_COUNT]; ++ uint64_t class_bytes[GGML_BACKEND_OP_CLASS_COUNT]; ++ // recurrent state caches: the most states one gather reads (the ++ // states of the batch's sequences and every state between them), and ++ // the most of those a copy writes back unchanged ++ uint32_t recurrent_states; ++ uint32_t recurrent_states_carried; ++ }; ++ ++ // Called on a backend-owned thread; keep it short. ++ typedef void (*ggml_backend_command_timing_callback_t)( ++ const struct ggml_backend_command_timing * timing, ++ void * user_data); ++ // A null callback stops reporting. ++ typedef void (*ggml_backend_set_command_timing_callback_t)( ++ ggml_backend_command_timing_callback_t callback, ++ void * user_data); ++ // Thread-local: graphs this thread submits afterwards carry `tag`, and so ++ // do the backend's trace spans on this thread. ++ typedef void (*ggml_backend_set_command_timing_tag_t)(uint64_t tag); ++ ++ // Trace spans, exposed by a backend registry as the proc ++ // "ggml_backend_set_trace_span_callback": host-side backend work worth a ++ // timeline entry, such as compiling a kernel library or pipeline. A ++ // backend reports each span when it ends, on the thread that did the ++ // work. Spans that end before any callback was ever installed (device ++ // initialisation can run first) are kept, a bounded number of them, and ++ // delivered on the installing thread when the first callback arrives. ++ struct ggml_backend_trace_span { ++ // the reporting thread's tag (see the command timing tag); 0 when none ++ uint64_t tag; ++ // static storage, such as "mtl.pipeline_compile" ++ const char * name; ++ // NULL, or what the span worked on; valid only during the callback ++ const char * detail; ++ int64_t start_unix_ns; ++ int64_t end_unix_ns; ++ }; ++ ++ typedef void (*ggml_backend_trace_span_callback_t)( ++ const struct ggml_backend_trace_span * span, ++ void * user_data); ++ // A null callback stops reporting. ++ typedef void (*ggml_backend_set_trace_span_callback_t)( ++ ggml_backend_trace_span_callback_t callback, ++ void * user_data); ++ + // + // Backend registry + // +diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt +index a6d145e69..b36e3b56b 100644 +--- a/ggml/src/ggml-metal/CMakeLists.txt ++++ b/ggml/src/ggml-metal/CMakeLists.txt +@@ -12,6 +12,7 @@ ggml_add_backend_library(ggml-metal + ggml-metal-context.m + ggml-metal-fusion.cpp + ggml-metal-ops.cpp ++ ggml-metal-timing.cpp + ggml-metal-tuning.cpp + ) + +diff --git a/ggml/src/ggml-metal/ggml-metal-context.m b/ggml/src/ggml-metal/ggml-metal-context.m +index e12c55a39..f89c8ebe6 100644 +--- a/ggml/src/ggml-metal/ggml-metal-context.m ++++ b/ggml/src/ggml-metal/ggml-metal-context.m +@@ -7,6 +7,7 @@ + #import "ggml-metal-common.h" + #import "ggml-metal-ops.h" + #import "ggml-metal-fusion.h" ++#import "ggml-metal-timing.h" + + #import + +@@ -79,6 +80,11 @@ struct ggml_metal { + ggml_abort_callback abort_callback; + void * abort_callback_data; + ++ // command timing (ggml_backend_set_command_timing_callback) ++ uint32_t timing_context_id; ++ uint32_t timing_compute_index; // counts like GGML_METAL_CAPTURE_COMPUTE ++ ggml_metal_timing_record_t timing[GGML_METAL_MAX_COMMAND_BUFFERS + 1]; ++ + // error state - set when a command buffer fails during synchronize + // once set, graph_compute will return GGML_STATUS_FAILED until the backend is recreated + bool has_error; +@@ -181,6 +187,12 @@ ggml_metal_t ggml_metal_init(ggml_metal_device_t dev) { + res->cmd_bufs[i].obj = nil; + } + ++ res->timing_context_id = ggml_metal_timing_next_context_id(); ++ res->timing_compute_index = 0; ++ for (int i = 0; i <= GGML_METAL_MAX_COMMAND_BUFFERS; ++i) { ++ res->timing[i] = NULL; ++ } ++ + res->cmd_bufs_ext = [[NSMutableArray alloc] init]; + res->buf_refs = [[NSMutableArray alloc] init]; + +@@ -254,6 +266,7 @@ const char * ggml_metal_get_name(ggml_metal_t ctx) { + void ggml_metal_synchronize(ggml_metal_t ctx) { + // wait for any backend operations to finish + if (ctx->cmd_buf_last) { ++ GGML_METAL_TIMING_SPAN(span, "mtl.wait", NULL); + [ctx->cmd_buf_last waitUntilCompleted]; + ctx->cmd_buf_last = nil; + } +@@ -370,6 +383,8 @@ void ggml_metal_set_tensor_async(ggml_metal_t ctx, struct ggml_tensor * tensor, + } + + void ggml_metal_get_tensor_async(ggml_metal_t ctx, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { ++ // wraps the host destination and queues a blit; does not wait ++ GGML_METAL_TIMING_SPAN(span, "mtl.copy_out", tensor->name); + @autoreleasepool { + id device = ggml_metal_device_get_obj(ctx->dev); + id buf_dst = [device newBufferWithBytesNoCopy:data +@@ -471,6 +486,99 @@ bool ggml_metal_cpy_tensor_async(ggml_metal_t ctx_src, ggml_metal_t ctx_dst, con + } + } + ++// time a command buffer that encodes the graph nodes [idx_start, idx_end) ++// when command timing is on; call before it is committed ++static ggml_metal_timing_record_t ggml_metal_time_nodes( ++ ggml_metal_t ctx, id cmd_buf, int command_index, int command_count, ++ int idx_start, int idx_end, bool split_by_class) { ++ ggml_metal_timing_record_t record = ggml_metal_timing_begin( ++ ctx->timing_context_id, ctx->timing_compute_index, command_index, command_count, MAX(idx_end - idx_start, 0)); ++ if (record == NULL) { ++ return NULL; ++ } ++ ++ ggml_metal_timing_account(record, ctx->gf, idx_start, idx_end, split_by_class); ++ ++ [cmd_buf addCompletedHandler:^(id cb) { ++ const MTLCommandBufferStatus status = [cb status]; ++ ggml_metal_timing_finish(record, [cb GPUStartTime], [cb GPUEndTime], ++ status == MTLCommandBufferStatusCompleted ? 0 : (int32_t) status); ++ }]; ++ ++ return record; ++} ++ ++static void ggml_metal_time_command_buffer( ++ ggml_metal_t ctx, id cmd_buf, int cb_idx, int command_index, int idx_start, int idx_end) { ++ ctx->timing[cb_idx] = ggml_metal_time_nodes(ctx, cmd_buf, command_index, ctx->n_cb + 1, idx_start, idx_end, false); ++} ++ ++// op profiling: one command buffer per run of nodes of one class, encoded ++// and committed in order on the calling thread, so the GPU times each class ++// by itself. Splitting serialises the graph and stops fusion across class ++// boundaries, so totals grow; the shares are what this measures. ++static enum ggml_status ggml_metal_graph_compute_by_class(ggml_metal_t ctx, struct ggml_cgraph * gf, id queue) { ++ const int n_nodes = gf->n_nodes; ++ ++ int * run_ends = malloc(sizeof(int) * (size_t) n_nodes); ++ if (run_ends == NULL) { ++ return GGML_STATUS_ALLOC_FAILED; ++ } ++ ++ int n_runs = 0; ++ for (int idx_start = 0; idx_start < n_nodes; idx_start = run_ends[n_runs - 1]) { ++ run_ends[n_runs++] = ggml_metal_timing_class_run_end(gf, idx_start); ++ } ++ ++ int idx_start = 0; ++ for (int run = 0; run < n_runs; ++run) { ++ const int idx_end = run_ends[run]; ++ ++ id cmd_buf = [queue commandBufferWithUnretainedReferences]; ++ ggml_metal_timing_record_t record = ggml_metal_time_nodes(ctx, cmd_buf, run, n_runs, idx_start, idx_end, true); ++ ++ ggml_metal_timing_encode_start(record); ++ ++ ggml_metal_op_t ctx_op = ggml_metal_op_init( ++ ctx->dev, ++ cmd_buf, ++ gf, ++ ctx->finfo, ++ idx_start, ++ idx_end, ++ ctx->use_concurrency, ++ false, ++ ctx->debug_graph); ++ ++ for (int idx = 0; idx < ggml_metal_op_n_nodes(ctx_op); ++idx) { ++ const int res = ggml_metal_op_encode(ctx_op, idx); ++ if (res == 0) { ++ break; ++ } ++ ++ idx += res - 1; ++ } ++ ++ ggml_metal_op_free(ctx_op); ++ ++ ggml_metal_timing_encode_end(record); ++ ++ [cmd_buf commit]; ++ ++ // synchronize() waits for, checks and releases these ++ [ctx->cmd_bufs_ext addObject:cmd_buf]; ++ ctx->cmd_buf_last = cmd_buf; ++ ++ [cmd_buf retain]; ++ ++ idx_start = idx_end; ++ } ++ ++ free(run_ends); ++ ++ return GGML_STATUS_SUCCESS; ++} ++ + enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * gf) { + if (ctx->has_error) { + GGML_LOG_ERROR("%s: backend is in error state from a previous command buffer failure - recreate the backend to recover\n", __func__); +@@ -522,6 +630,9 @@ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * + ctx->capture_compute--; + } + ++ ctx->timing_compute_index++; ++ ggml_metal_timing_graph_ops(gf); ++ + const bool use_capture = ctx->capture_compute == 0; + if (use_capture) { + // make sure all previous computations have finished before starting the capture +@@ -563,6 +674,10 @@ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * + // short-hand + id queue = ggml_metal_device_get_queue(ctx->dev); + ++ if (!use_capture && ggml_metal_timing_op_profile()) { ++ return ggml_metal_graph_compute_by_class(ctx, gf, queue); ++ } ++ + // the main thread commits the first few commands immediately + // cmd_buf[n_cb] + { +@@ -574,6 +689,9 @@ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * + } + ctx->cmd_bufs[n_cb].obj = cmd_buf; + ++ // runs first on the GPU ++ ggml_metal_time_command_buffer(ctx, cmd_buf, n_cb, 0, 0, ctx->cb_start[0]); ++ + [cmd_buf enqueue]; + + ctx->encode_async(n_cb); +@@ -593,6 +711,12 @@ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * + } + ctx->cmd_bufs[cb_idx].obj = cmd_buf; + ++ // time only the buffers that encode_async commits; the rest may never complete ++ ctx->timing[cb_idx] = NULL; ++ if (cb_idx < 2 || ctx->abort_callback == NULL) { ++ ggml_metal_time_command_buffer(ctx, cmd_buf, cb_idx, cb_idx + 1, ctx->cb_start[cb_idx], ctx->cb_start[cb_idx + 1]); ++ } ++ + // always enqueue the first two command buffers + // enqueue all of the command buffers if we don't need to abort + if (cb_idx < 2 || ctx->abort_callback == NULL) { +@@ -685,6 +809,7 @@ void ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf) { + //const int64_t t_start = ggml_time_us(); + + if (ctx->use_graph_optimize) { ++ GGML_METAL_TIMING_SPAN(span, "mtl.graph_optimize", NULL); + ggml_graph_optimize(gf); + } + +@@ -760,6 +885,8 @@ void ggml_metal_set_n_cb(ggml_metal_t ctx, int n_cb) { + + id cmd_buf = ctx->cmd_bufs[cb_idx].obj; + ++ ggml_metal_timing_encode_start(ctx->timing[cb_idx]); ++ + ggml_metal_op_t ctx_op = ggml_metal_op_init( + ctx->dev, + cmd_buf, +@@ -782,6 +909,8 @@ void ggml_metal_set_n_cb(ggml_metal_t ctx, int n_cb) { + + ggml_metal_op_free(ctx_op); + ++ ggml_metal_timing_encode_end(ctx->timing[cb_idx]); ++ + if (cb_idx < 2 || ctx->abort_callback == NULL) { + [cmd_buf commit]; + } +diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m +index 8c21125d5..7c42724af 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.m ++++ b/ggml/src/ggml-metal/ggml-metal-device.m +@@ -5,6 +5,7 @@ + #import "ggml-backend-impl.h" + #import "ggml-metal-impl.h" + #import "ggml-metal-common.h" ++#import "ggml-metal-timing.h" + + #include + +@@ -276,6 +277,8 @@ static void ggml_metal_pso_cache_setup(ggml_metal_library_t lib, id d + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/pipelines-%016llx.metallibar", dir, (unsigned long long) h); + ++ GGML_METAL_TIMING_SPAN(span, "mtl.pipeline_cache_open", path); ++ + NSString * path_ns = [NSString stringWithUTF8String:path]; + NSURL * url = [NSURL fileURLWithPath:path_ns]; + +@@ -452,6 +455,7 @@ static bool ggml_metal_library_compile_all( + + for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { + dispatch_group_async(group, queue, ^{ ++ GGML_METAL_TIMING_SPAN(span, "mtl.library_compile", k_lib_names[kind]); + + const int64_t t0 = ggml_time_us(); + +@@ -905,6 +909,9 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_ + return res; + } + ++ // first use of this pipeline: compiled now, or loaded from the archive ++ GGML_METAL_TIMING_SPAN(span, "mtl.pipeline_compile", name); ++ + @autoreleasepool { + NSError * error = nil; + +@@ -1498,7 +1505,9 @@ ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { + snprintf(dev->props.desc, sizeof(dev->props.desc), "%s", gpu_name); + } + ++ const int64_t t_library = ggml_metal_timing_span_start(); + dev->library = ggml_metal_library_init(dev); ++ ggml_metal_timing_span_end("mtl.library_init", dev->props.desc, t_library); + if (!dev->library) { + GGML_LOG_ERROR("%s: error: failed to create library\n", __func__); + } +@@ -2305,6 +2314,8 @@ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { + return true; + } + ++ GGML_METAL_TIMING_SPAN(span, "mtl.residency_set", NULL); ++ + #if defined(GGML_METAL_HAS_RESIDENCY_SETS) + if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { + MTLResidencySetDescriptor * desc = [[MTLResidencySetDescriptor alloc] init]; +@@ -2364,6 +2375,10 @@ static void * ggml_metal_host_malloc(size_t n) { + } + + ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared) { ++ char span_detail[32]; ++ snprintf(span_detail, sizeof(span_detail), "%zu bytes", size); ++ GGML_METAL_TIMING_SPAN(span, "mtl.buffer_alloc", span_detail); ++ + ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); + + res->dev = dev; +@@ -2434,6 +2449,10 @@ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, + } + + ggml_metal_buffer_t ggml_metal_buffer_map(ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size) { ++ char span_detail[32]; ++ snprintf(span_detail, sizeof(span_detail), "%zu bytes", size); ++ GGML_METAL_TIMING_SPAN(span, "mtl.buffer_map", span_detail); ++ + ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); + + res->dev = dev; +@@ -2588,6 +2607,9 @@ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * + return; + } + ++ // a private buffer: a blit the host waits for ++ GGML_METAL_TIMING_SPAN(span, "mtl.upload", tensor->name); ++ + @autoreleasepool { + // src + void * data_ptr = (void *)(uintptr_t) data; // "const cast" the src data +@@ -2644,6 +2666,8 @@ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_ten + return; + } + ++ GGML_METAL_TIMING_SPAN(span, "mtl.download", tensor->name); ++ + @autoreleasepool { + // src + struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(buf, tensor); +diff --git a/ggml/src/ggml-metal/ggml-metal-timing.cpp b/ggml/src/ggml-metal/ggml-metal-timing.cpp +new file mode 100644 +index 000000000..8bf274932 +--- /dev/null ++++ b/ggml/src/ggml-metal/ggml-metal-timing.cpp +@@ -0,0 +1,529 @@ ++#include "ggml-metal-timing.h" ++ ++#include "ggml-impl.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#if defined(__APPLE__) ++#include ++#endif ++ ++namespace { ++ ++// install once: a replacement racing a completion may pair the new callback with the old data ++std::atomic g_callback { nullptr }; ++std::atomic g_user_data { nullptr }; ++ ++std::atomic g_span_callback { nullptr }; ++std::atomic g_span_user_data { nullptr }; ++ ++std::atomic g_next_context_id { 0 }; ++ ++std::mutex g_graph_ops_mutex; ++std::set g_graph_ops_reported; // node counts, guarded by g_graph_ops_mutex ++ ++thread_local uint64_t g_tag = 0; ++ ++// spans that ended before the first span callback arrived: device ++// initialisation compiles the kernel libraries before anyone can listen ++struct pending_span { ++ uint64_t tag; ++ const char * name; ++ bool has_detail; ++ std::string detail; ++ int64_t start_unix_ns; ++ int64_t end_unix_ns; ++}; ++ ++constexpr size_t MAX_PENDING_SPANS = 256; ++ ++std::mutex g_pending_mutex; ++std::vector g_pending; // guarded by g_pending_mutex ++std::atomic g_span_installed { false }; ++ ++// seconds on the host clock that Metal stamps command buffers with ++double host_now_s() { ++#if defined(__APPLE__) ++ static const double ns_per_tick = [] { ++ mach_timebase_info_data_t info {}; ++ mach_timebase_info(&info); ++ return (double) info.numer / (double) info.denom; ++ }(); ++ return (double) mach_absolute_time() * ns_per_tick * 1e-9; ++#else ++ timespec ts {}; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ return (double) ts.tv_sec + (double) ts.tv_nsec * 1e-9; ++#endif ++} ++ ++int64_t unix_now_ns() { ++ timespec ts {}; ++ clock_gettime(CLOCK_REALTIME, &ts); ++ return (int64_t) ts.tv_sec * 1000000000 + (int64_t) ts.tv_nsec; ++} ++ ++void deliver_span(ggml_backend_trace_span_callback_t callback, void * user_data, const ggml_backend_trace_span & span) { ++ if (callback != nullptr) { ++ callback(&span, user_data); ++ } ++} ++ ++// views and reshapes: no work, so they join the run around them ++constexpr int OP_CLASS_NONE = -1; ++ ++bool has_prefix(const char * name, std::string_view prefix) { ++ return std::string_view(name).compare(0, prefix.size(), prefix) == 0; ++} ++ ++// the cache a node writes, or reads with a view: its root tensor's name ++const char * cache_name(const ggml_tensor * t) { ++ const ggml_tensor * root = t->view_src != nullptr ? t->view_src : t; ++ return has_prefix(root->name, "cache_") ? root->name : nullptr; ++} ++ ++// llama-memory-recurrent names its state cache_r_l and cache_s_l ++bool is_recurrent_cache(const char * name) { ++ return has_prefix(name, "cache_r_l") || has_prefix(name, "cache_s_l"); ++} ++ ++// the cache class of a node that copies into or gathers from a cache ++int cache_class(const ggml_tensor * node) { ++ const char * name = cache_name(node); ++ if (name == nullptr && node->op == GGML_OP_GET_ROWS && node->src[0] != nullptr) { ++ name = cache_name(node->src[0]); ++ return name != nullptr && is_recurrent_cache(name) ? GGML_BACKEND_OP_CLASS_RECURRENT : GGML_BACKEND_OP_CLASS_OTHER; ++ } ++ if (name == nullptr) { ++ return GGML_BACKEND_OP_CLASS_OTHER; ++ } ++ return is_recurrent_cache(name) ? GGML_BACKEND_OP_CLASS_RECURRENT : GGML_BACKEND_OP_CLASS_KV_WRITE; ++} ++ ++// the K/Q and K/Q/V products of llama-graph's unfused attention ("kq-", ++// "kqv-") and its output ("kqv_out-") ++bool is_named_attention(const ggml_tensor * node) { ++ return has_prefix(node->name, "kq-") || has_prefix(node->name, "kqv-") || ++ has_prefix(node->name, "kq_") || has_prefix(node->name, "kqv_"); ++} ++ ++int op_class(const ggml_tensor * node) { ++ switch (node->op) { ++ case GGML_OP_NONE: ++ case GGML_OP_RESHAPE: ++ case GGML_OP_VIEW: ++ case GGML_OP_PERMUTE: ++ case GGML_OP_TRANSPOSE: ++ return OP_CLASS_NONE; ++ case GGML_OP_FLASH_ATTN_EXT: ++ return GGML_BACKEND_OP_CLASS_ATTENTION; ++ case GGML_OP_SSM_CONV: ++ case GGML_OP_SSM_SCAN: ++ case GGML_OP_RWKV_WKV6: ++ case GGML_OP_RWKV_WKV7: ++ case GGML_OP_GATED_LINEAR_ATTN: ++ case GGML_OP_GATED_DELTA_NET: ++ return GGML_BACKEND_OP_CLASS_RECURRENT; ++ case GGML_OP_SOFT_MAX: ++ // a masked soft max is unfused attention; MoE routing has no mask ++ return node->src[1] != nullptr || is_named_attention(node) ? ++ GGML_BACKEND_OP_CLASS_ATTENTION : GGML_BACKEND_OP_CLASS_OTHER; ++ case GGML_OP_MUL_MAT: ++ case GGML_OP_MUL_MAT_ID: ++ return is_named_attention(node) ? GGML_BACKEND_OP_CLASS_ATTENTION : GGML_BACKEND_OP_CLASS_MATMUL; ++ case GGML_OP_SET_ROWS: ++ case GGML_OP_CPY: ++ case GGML_OP_GET_ROWS: ++ return cache_class(node); ++ default: ++ return is_named_attention(node) ? GGML_BACKEND_OP_CLASS_ATTENTION : GGML_BACKEND_OP_CLASS_OTHER; ++ } ++} ++ ++uint64_t input_bytes(const ggml_tensor * node) { ++ return std::accumulate(std::begin(node->src), std::end(node->src), uint64_t { 0 }, ++ [](uint64_t sum, const ggml_tensor * src) { return src != nullptr ? sum + ggml_nbytes(src) : sum; }); ++} ++ ++uint64_t bytes_of(const ggml_tensor * t) { ++ return t != nullptr ? ggml_nbytes(t) : 0; ++} ++ ++// a gather reads only its rows, and a row write writes only its rows, of the ++// tensor they index: get_rows(a, ids) has a as src[0], set_rows(a, b, ids) as src[2] ++uint64_t bytes_read(const ggml_tensor * node) { ++ switch (node->op) { ++ case GGML_OP_GET_ROWS: ++ return ggml_nbytes(node) + bytes_of(node->src[1]); ++ case GGML_OP_SET_ROWS: ++ return input_bytes(node) - bytes_of(node->src[2]); ++ default: ++ return input_bytes(node); ++ } ++} ++ ++bool in_recurrent_cache(const ggml_tensor * t) { ++ const char * name = t != nullptr ? cache_name(t) : nullptr; ++ return name != nullptr && is_recurrent_cache(name); ++} ++ ++struct state_rows { ++ uint32_t gathered; ++ uint32_t carried; ++}; ++ ++// llama-graph's build_rs gathers the states from the batch's first state cell ++// to its last, then copies the gathered states no sequence of the batch owns ++// back unchanged ++state_rows state_rows_of(const ggml_tensor * node) { ++ if (node->op == GGML_OP_GET_ROWS && in_recurrent_cache(node->src[0]) && node->src[1] != nullptr) { ++ return { (uint32_t) ggml_nelements(node->src[1]), 0 }; ++ } ++ if (node->op != GGML_OP_CPY || node->src[0] == nullptr || !in_recurrent_cache(node->src[1])) { ++ return { 0, 0 }; ++ } ++ const ggml_tensor * gathered = node->src[0]->view_src; ++ const bool unchanged = gathered != nullptr && gathered->op == GGML_OP_GET_ROWS && in_recurrent_cache(gathered->src[0]); ++ return { 0, unchanged ? (uint32_t) ggml_nrows(node->src[0]) : 0 }; ++} ++ ++// ggml_flash_attn_ext_rows passes its I32 row lists [padded_rows, slices] as src[5] ++const ggml_tensor * attention_rows(const ggml_tensor * node) { ++ return node->op == GGML_OP_FLASH_ATTN_EXT ? node->src[5] : nullptr; ++} ++ ++struct attention_shape { ++ uint32_t kv_cells; ++ uint32_t queries; ++ bool row_lists; ++ bool flash; ++ uint64_t bytes; ++}; ++ ++// unfused attention's K/Q product, kq = mul_mat(k, q): k is ++// [head_dim, n_kv, n_head_kv, ...], q is [head_dim, n_tokens, n_head, ...] ++attention_shape unfused_shape_of(const ggml_tensor * node) { ++ const ggml_tensor * k = node->src[0]; ++ const ggml_tensor * q = node->src[1]; ++ if (k == nullptr || q == nullptr) { ++ return { 0, 0, false, false, input_bytes(node) }; ++ } ++ return { (uint32_t) k->ne[1], (uint32_t) (q->ne[1] * q->ne[3]), false, false, input_bytes(node) }; ++} ++ ++// what one attention node addresses: with row lists only the listed K/V ++// rows of the shared pool, otherwise the whole K/V span it was given ++attention_shape attention_shape_of(const ggml_tensor * node) { ++ if (node->op == GGML_OP_MUL_MAT && has_prefix(node->name, "kq-")) { ++ return unfused_shape_of(node); ++ } ++ const ggml_tensor * q = node->src[0]; ++ const ggml_tensor * k = node->src[1]; ++ const ggml_tensor * v = node->src[2]; ++ const ggml_tensor * rows = attention_rows(node); ++ if (node->op != GGML_OP_FLASH_ATTN_EXT || q == nullptr || k == nullptr || v == nullptr) { ++ return { 0, 0, false, false, input_bytes(node) }; ++ } ++ const uint32_t queries = (uint32_t) (q->ne[1] * q->ne[3]); ++ if (rows == nullptr) { ++ return { (uint32_t) k->ne[1], queries, false, true, input_bytes(node) }; ++ } ++ const uint64_t row_bytes = ++ ggml_row_size(k->type, k->ne[0]) * (uint64_t) k->ne[2] + ++ ggml_row_size(v->type, v->ne[0]) * (uint64_t) v->ne[2]; ++ const uint64_t listed = (uint64_t) rows->ne[0] * (uint64_t) rows->ne[1]; ++ const uint64_t other = input_bytes(node) - ggml_nbytes(k) - ggml_nbytes(v); ++ return { (uint32_t) rows->ne[0], queries, true, true, other + listed * row_bytes }; ++} ++ ++// llama-graph names a layer's tensors "-" ++int32_t layer_of(const ggml_tensor * node) { ++ const std::string_view name(node->name); ++ const size_t dash = name.rfind('-'); ++ if (dash == std::string_view::npos || dash + 1 == name.size()) { ++ return -1; ++ } ++ const std::string_view digits = name.substr(dash + 1); ++ if (!std::all_of(digits.begin(), digits.end(), [](char c) { return c >= '0' && c <= '9'; })) { ++ return -1; ++ } ++ return (int32_t) std::strtol(std::string(digits).c_str(), nullptr, 10); ++} ++ ++} // namespace ++ ++struct ggml_metal_timing_record { ++ ggml_backend_command_timing timing {}; ++ ++ // the encoding thread's own tag, restored once it has encoded this buffer ++ uint64_t saved_tag = 0; ++ ++ // written by the encoding thread, read on Metal's completion thread ++ std::atomic encode_start_host_s { 0.0 }; ++ std::atomic encode_end_host_s { 0.0 }; ++}; ++ ++uint32_t ggml_metal_timing_next_context_id(void) { ++ return g_next_context_id.fetch_add(1, std::memory_order_relaxed) + 1; ++} ++ ++ggml_metal_timing_record_t ggml_metal_timing_begin( ++ uint32_t context_id, ++ uint32_t compute_index, ++ uint32_t command_index, ++ uint32_t command_count, ++ uint32_t node_count) { ++ if (g_callback.load(std::memory_order_acquire) == nullptr && ++ g_span_callback.load(std::memory_order_acquire) == nullptr) { ++ return nullptr; ++ } ++ ++ auto * record = new (std::nothrow) ggml_metal_timing_record {}; ++ if (record == nullptr) { ++ return nullptr; ++ } ++ ++ record->timing.tag = g_tag; ++ record->timing.context_id = context_id; ++ record->timing.compute_index = compute_index; ++ record->timing.command_index = command_index; ++ record->timing.command_count = command_count; ++ record->timing.node_count = node_count; ++ record->timing.op_class = GGML_BACKEND_OP_CLASS_COUNT; ++ record->timing.layer = -1; ++ ++ return record; ++} ++ ++void ggml_metal_timing_account( ++ ggml_metal_timing_record_t record, ++ struct ggml_cgraph * gf, ++ int start, ++ int end, ++ bool split_by_class) { ++ if (record == nullptr || gf == nullptr || start >= end) { ++ return; ++ } ++ ggml_backend_command_timing & timing = record->timing; ++ timing.split_by_class = split_by_class ? 1 : 0; ++ ++ ggml_tensor ** first = gf->nodes + start; ++ ggml_tensor ** last = gf->nodes + std::min(end, gf->n_nodes); ++ ++ std::for_each(first, last, [&timing](const ggml_tensor * node) { ++ const int cls = op_class(node); ++ if (cls == OP_CLASS_NONE) { ++ return; ++ } ++ if (timing.layer < 0) { ++ timing.layer = layer_of(node); ++ } ++ timing.class_nodes[cls] += 1; ++ const state_rows states = state_rows_of(node); ++ timing.recurrent_states = std::max(timing.recurrent_states, states.gathered); ++ timing.recurrent_states_carried = std::max(timing.recurrent_states_carried, states.carried); ++ if (cls != GGML_BACKEND_OP_CLASS_ATTENTION) { ++ timing.class_bytes[cls] += bytes_read(node); ++ return; ++ } ++ const attention_shape shape = attention_shape_of(node); ++ timing.class_bytes[cls] += shape.bytes; ++ timing.attention_kv_cells = std::max(timing.attention_kv_cells, shape.kv_cells); ++ timing.attention_queries = std::max(timing.attention_queries, shape.queries); ++ timing.attention_row_list_nodes += shape.row_lists ? 1 : 0; ++ timing.attention_flash_nodes += shape.flash ? 1 : 0; ++ }); ++ ++ const uint32_t * counts_begin = std::cbegin(timing.class_nodes); ++ const uint32_t * counts_end = std::cend(timing.class_nodes); ++ const auto nonzero = [](uint32_t n) { return n > 0; }; ++ const auto classes_used = std::count_if(counts_begin, counts_end, nonzero); ++ if (classes_used == 0) { ++ timing.op_class = GGML_BACKEND_OP_CLASS_OTHER; ++ } else if (classes_used == 1) { ++ timing.op_class = (int32_t) std::distance(counts_begin, std::find_if(counts_begin, counts_end, nonzero)); ++ } ++} ++ ++int ggml_metal_timing_class_run_end(struct ggml_cgraph * gf, int start) { ++ ggml_tensor ** first = gf->nodes + start; ++ ggml_tensor ** last = gf->nodes + gf->n_nodes; ++ ++ const auto classified = [](const ggml_tensor * node) { return op_class(node) != OP_CLASS_NONE; }; ++ ggml_tensor ** lead = std::find_if(first, last, classified); ++ if (lead == last) { ++ return gf->n_nodes; ++ } ++ const int cls = op_class(*lead); ++ ggml_tensor ** next = std::find_if(lead + 1, last, [cls](const ggml_tensor * node) { ++ const int other = op_class(node); ++ return other != OP_CLASS_NONE && other != cls; ++ }); ++ return (int) std::distance(gf->nodes, next); ++} ++ ++bool ggml_metal_timing_op_profile(void) { ++ static const bool requested = [] { ++ const char * value = std::getenv("GGML_METAL_OP_PROFILE"); ++ return value != nullptr && value[0] != '\0' && std::string_view(value) != "0"; ++ }(); ++ return requested && g_callback.load(std::memory_order_acquire) != nullptr; ++} ++ ++void ggml_metal_timing_encode_start(ggml_metal_timing_record_t record) { ++ if (record != nullptr) { ++ record->saved_tag = g_tag; ++ g_tag = record->timing.tag; ++ record->encode_start_host_s.store(host_now_s(), std::memory_order_release); ++ } ++} ++ ++void ggml_metal_timing_encode_end(ggml_metal_timing_record_t record) { ++ if (record != nullptr) { ++ record->encode_end_host_s.store(host_now_s(), std::memory_order_release); ++ g_tag = record->saved_tag; ++ } ++} ++ ++void ggml_metal_timing_finish( ++ ggml_metal_timing_record_t record, ++ double execute_start_host_s, ++ double execute_end_host_s, ++ int32_t status) { ++ const std::unique_ptr owned(record); ++ if (!owned) { ++ return; ++ } ++ ++ const auto callback = g_callback.load(std::memory_order_acquire); ++ if (callback == nullptr) { ++ return; ++ } ++ void * user_data = g_user_data.load(std::memory_order_acquire); ++ ++ // one paired reading converts every host time on this record ++ const double host_now = host_now_s(); ++ const int64_t unix_now = unix_now_ns(); ++ const auto to_unix_ns = [&](double host_s) -> int64_t { ++ return host_s > 0.0 ? unix_now - (int64_t) ((host_now - host_s) * 1e9) : 0; ++ }; ++ ++ ggml_backend_command_timing timing = owned->timing; ++ timing.status = status; ++ timing.encode_start_unix_ns = to_unix_ns(owned->encode_start_host_s.load(std::memory_order_acquire)); ++ timing.encode_end_unix_ns = to_unix_ns(owned->encode_end_host_s.load(std::memory_order_acquire)); ++ timing.execute_start_unix_ns = to_unix_ns(execute_start_host_s); ++ timing.execute_end_unix_ns = to_unix_ns(execute_end_host_s); ++ ++ callback(&timing, user_data); ++} ++ ++int64_t ggml_metal_timing_span_start(void) { ++ if (g_span_callback.load(std::memory_order_acquire) == nullptr && ++ g_span_installed.load(std::memory_order_acquire)) { ++ return 0; ++ } ++ return unix_now_ns(); ++} ++ ++void ggml_metal_timing_span_end(const char * name, const char * detail, int64_t start_unix_ns) { ++ if (start_unix_ns == 0 || name == nullptr) { ++ return; ++ } ++ const ggml_backend_trace_span span = { g_tag, name, detail, start_unix_ns, unix_now_ns() }; ++ ++ if (g_span_installed.load(std::memory_order_acquire)) { ++ deliver_span(g_span_callback.load(std::memory_order_acquire), ++ g_span_user_data.load(std::memory_order_acquire), span); ++ return; ++ } ++ ++ { ++ std::lock_guard lock(g_pending_mutex); ++ if (!g_span_installed.load(std::memory_order_acquire)) { ++ if (g_pending.size() < MAX_PENDING_SPANS) { ++ g_pending.push_back({ span.tag, name, detail != nullptr, detail != nullptr ? detail : "", ++ span.start_unix_ns, span.end_unix_ns }); ++ } ++ return; ++ } ++ } ++ // the first callback arrived while this span was ending ++ deliver_span(g_span_callback.load(std::memory_order_acquire), ++ g_span_user_data.load(std::memory_order_acquire), span); ++} ++ ++void ggml_metal_timing_set_callback(ggml_backend_command_timing_callback_t callback, void * user_data) { ++ if (callback == nullptr) { ++ g_callback.store(nullptr, std::memory_order_release); ++ return; ++ } ++ g_user_data.store(user_data, std::memory_order_relaxed); ++ g_callback.store(callback, std::memory_order_release); ++} ++ ++void ggml_metal_timing_graph_ops(struct ggml_cgraph * gf) { ++ if (gf == nullptr || g_callback.load(std::memory_order_acquire) == nullptr) { ++ return; ++ } ++ { ++ std::lock_guard lock(g_graph_ops_mutex); ++ if (!g_graph_ops_reported.insert(gf->n_nodes).second) { ++ return; ++ } ++ } ++ const int64_t start = ggml_metal_timing_span_start(); ++ ++ std::map counts; ++ std::for_each(gf->nodes, gf->nodes + gf->n_nodes, [&counts](const ggml_tensor * node) { ++ ++counts[ggml_op_desc(node)]; ++ }); ++ const std::string detail = std::accumulate(counts.begin(), counts.end(), "nodes=" + std::to_string(gf->n_nodes), ++ [](std::string text, const auto & op) { ++ return std::move(text) + ' ' + std::string(op.first) + ':' + std::to_string(op.second); ++ }); ++ ++ ggml_metal_timing_span_end("mtl.graph_ops", detail.c_str(), start); ++} ++ ++void ggml_metal_timing_set_tag(uint64_t tag) { ++ g_tag = tag; ++} ++ ++void ggml_metal_timing_set_span_callback(ggml_backend_trace_span_callback_t callback, void * user_data) { ++ if (callback == nullptr) { ++ g_span_callback.store(nullptr, std::memory_order_release); ++ return; ++ } ++ ++ std::vector pending; ++ { ++ std::lock_guard lock(g_pending_mutex); ++ g_span_user_data.store(user_data, std::memory_order_relaxed); ++ g_span_callback.store(callback, std::memory_order_release); ++ g_span_installed.store(true, std::memory_order_release); ++ pending.swap(g_pending); ++ } ++ ++ // kept spans reach the first callback in the order they ended ++ for (const auto & kept : pending) { ++ const ggml_backend_trace_span span = { ++ kept.tag, kept.name, kept.has_detail ? kept.detail.c_str() : nullptr, ++ kept.start_unix_ns, kept.end_unix_ns, ++ }; ++ deliver_span(callback, user_data, span); ++ } ++} +diff --git a/ggml/src/ggml-metal/ggml-metal-timing.h b/ggml/src/ggml-metal/ggml-metal-timing.h +new file mode 100644 +index 000000000..3cbe29099 +--- /dev/null ++++ b/ggml/src/ggml-metal/ggml-metal-timing.h +@@ -0,0 +1,102 @@ ++// tracing for ggml-metal: ++// - command timing: one record per command buffer, reported through ++// ggml_backend_set_command_timing_callback once the GPU has finished it ++// - trace spans: host-side work such as library and pipeline compilation, ++// reported through ggml_backend_set_trace_span_callback ++ ++#pragma once ++ ++#include "ggml-backend.h" ++ ++#include ++#include ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++typedef struct ggml_metal_timing_record * ggml_metal_timing_record_t; ++ ++// a process-unique id for a new Metal context ++uint32_t ggml_metal_timing_next_context_id(void); ++ ++// NULL unless a command timing or trace span callback is installed; ++// captures the calling thread's tag ++ggml_metal_timing_record_t ggml_metal_timing_begin( ++ uint32_t context_id, ++ uint32_t compute_index, ++ uint32_t command_index, ++ uint32_t command_count, ++ uint32_t node_count); ++ ++// accept NULL records; between the two, the encoding thread carries the ++// record's tag, so spans it reports (a pipeline compiled on first use) land ++// under the call that submitted the graph even on a dispatch worker ++void ggml_metal_timing_encode_start(ggml_metal_timing_record_t record); ++void ggml_metal_timing_encode_end (ggml_metal_timing_record_t record); ++ ++// classifies the graph nodes [start, end) the record's command encodes (see ++// ggml_backend_op_class); `split_by_class` marks a command of a graph split ++// at class boundaries; accepts a NULL record ++void ggml_metal_timing_account( ++ ggml_metal_timing_record_t record, ++ struct ggml_cgraph * gf, ++ int start, ++ int end, ++ bool split_by_class); ++ ++// the end of the run of nodes from `start` that share one class; views and ++// reshapes join the run they sit in ++int ggml_metal_timing_class_run_end(struct ggml_cgraph * gf, int start); ++ ++// the first compute of a graph with this many nodes reports an "mtl.graph_ops" ++// span whose detail counts its nodes by op ("nodes=N ADD:12 CPY:4 ..."), while ++// a command timing callback is installed ++void ggml_metal_timing_graph_ops(struct ggml_cgraph * gf); ++ ++// whether to split each graph at class boundaries, one command buffer per ++// run, so the GPU times every class by itself: GGML_METAL_OP_PROFILE=1 with ++// a command timing callback installed ++bool ggml_metal_timing_op_profile(void); ++ ++// reports and frees the record; times are MTLCommandBuffer GPUStartTime/GPUEndTime ++void ggml_metal_timing_finish( ++ ggml_metal_timing_record_t record, ++ double execute_start_host_s, ++ double execute_end_host_s, ++ int32_t status); ++ ++// the start of a trace span, in Unix nanoseconds; 0 when nothing would ++// record it (a callback was installed once and has since been cleared) ++int64_t ggml_metal_timing_span_start(void); ++ ++// report a span begun by ggml_metal_timing_span_start; `name` must have ++// static storage, `detail` may be NULL and is copied when the span is kept ++// for later delivery; ignores a zero start ++void ggml_metal_timing_span_end(const char * name, const char * detail, int64_t start_unix_ns); ++ ++// a trace span from here to the end of the enclosing scope, for C and ++// Objective-C callers with several exits; `detail` must outlive the scope ++struct ggml_metal_timing_span_scope { ++ const char * name; ++ const char * detail; ++ int64_t start_unix_ns; ++}; ++ ++static inline void ggml_metal_timing_span_scope_end(struct ggml_metal_timing_span_scope * scope) { ++ ggml_metal_timing_span_end(scope->name, scope->detail, scope->start_unix_ns); ++} ++ ++#define GGML_METAL_TIMING_SPAN(var, name, detail) \ ++ __attribute__((cleanup(ggml_metal_timing_span_scope_end), unused)) \ ++ struct ggml_metal_timing_span_scope var = { (name), (detail), ggml_metal_timing_span_start() } ++ ++// the ggml_backend_set_command_timing_callback, _tag and ++// ggml_backend_set_trace_span_callback procs ++void ggml_metal_timing_set_callback(ggml_backend_command_timing_callback_t callback, void * user_data); ++void ggml_metal_timing_set_tag(uint64_t tag); ++void ggml_metal_timing_set_span_callback(ggml_backend_trace_span_callback_t callback, void * user_data); ++ ++#ifdef __cplusplus ++} ++#endif +diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp +index 528853974..833fe8549 100644 +--- a/ggml/src/ggml-metal/ggml-metal.cpp ++++ b/ggml/src/ggml-metal/ggml-metal.cpp +@@ -7,6 +7,7 @@ + #include "ggml-metal-fusion.h" + #include "ggml-metal-context.h" + #include "ggml-metal-ops.h" ++#include "ggml-metal-timing.h" + #include "ggml-metal-tuning.h" + + #include +@@ -1019,6 +1020,15 @@ static void * ggml_backend_metal_get_proc_address(ggml_backend_reg_t reg, const + if (strcmp(name, "ggml_backend_cachegen_decode") == 0) { + return (void *)ggml_metal_cachegen_decode; + } ++ if (strcmp(name, "ggml_backend_set_command_timing_callback") == 0) { ++ return (void *)(ggml_backend_set_command_timing_callback_t) ggml_metal_timing_set_callback; ++ } ++ if (strcmp(name, "ggml_backend_set_command_timing_tag") == 0) { ++ return (void *)(ggml_backend_set_command_timing_tag_t) ggml_metal_timing_set_tag; ++ } ++ if (strcmp(name, "ggml_backend_set_trace_span_callback") == 0) { ++ return (void *)(ggml_backend_set_trace_span_callback_t) ggml_metal_timing_set_span_callback; ++ } + if (strcmp(name, "ggml_backend_metal_tuning_set_fa_vec_override") == 0) { + return (void *)ggml_backend_metal_tuning_set_fa_vec_override; + } +diff --git a/include/skippy.h b/include/skippy.h +index dc8cbb431..8d710ed64 100644 +--- a/include/skippy.h ++++ b/include/skippy.h +@@ -12,6 +12,7 @@ + // Public umbrella for the capability-oriented Skippy C API. + #include "skippy/common.h" + #include "skippy/events.h" ++#include "skippy/tracing.h" + #include "skippy/devices.h" + #include "skippy/runtime.h" + #include "skippy/model_source.h" +diff --git a/include/skippy/common.h b/include/skippy/common.h +index cbba91849..0e7b4f8a2 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -102,6 +102,8 @@ enum skippy_feature { + #define SKIPPY_FEATURE_KV_EVENTS ((uint64_t)1 << 33) + #define SKIPPY_FEATURE_DEVICE_EVENTS ((uint64_t)1 << 34) + #define SKIPPY_FEATURE_DIAGNOSTIC_EVENTS ((uint64_t)1 << 35) ++/** @brief Native span and GPU command timing callbacks (`skippy/tracing.h`). */ ++#define SKIPPY_FEATURE_NATIVE_TRACING (UINT64_C(1) << 43) + #define SKIPPY_FEATURE_UNLOAD_EVENTS ((uint64_t)1 << 36) + /** @brief Full-model embedding, reranking, and encoder-decoder execution. */ + #define SKIPPY_FEATURE_NON_CHAT_WORKLOADS ((uint64_t)1 << 37) +diff --git a/include/skippy/tracing.h b/include/skippy/tracing.h +new file mode 100644 +index 000000000..e9e57357c +--- /dev/null ++++ b/include/skippy/tracing.h +@@ -0,0 +1,197 @@ ++#ifndef SKIPPY_TRACING_H ++#define SKIPPY_TRACING_H ++ ++/** ++ * @file skippy/tracing.h ++ * @brief Where time goes inside native calls: native spans and GPU command timing. ++ * ++ * Requires SKIPPY_FEATURE_NATIVE_TRACING. Two callbacks report what a native ++ * call did, for a caller that already times the call itself. Native spans ++ * name the phases of host work (preparing a batch, building and allocating ++ * the llama graph, encoding it, waiting for the device, extracting outputs, ++ * sampling, and in a backend that reports them, compiling kernel libraries ++ * and pipelines); each arrives when it ends, on the thread that did the work. ++ * GPU command timing reports each unit of device work (Metal: a command ++ * buffer) once the device has finished it, on a backend completion thread. ++ * Both carry the tag the calling thread set with skippy_set_trace_tag, so a ++ * caller that sets a fresh tag before each native call can place everything ++ * the call caused under it, though spans and device records arrive later. ++ */ ++ ++#include "common.h" ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++#define SKIPPY_NATIVE_SPAN_V1_ABI_VERSION 1 ++ ++/** ++ * @brief Set in every native span id, so ids never collide with caller tags ++ * that leave the top bit clear. ++ */ ++#define SKIPPY_NATIVE_SPAN_ID_BIT (UINT64_C(1) << 63) ++ ++/** @brief One finished phase of native work. */ ++struct skippy_native_span_v1 { ++ uint32_t abi_version; ++ uint32_t struct_size; ++ /** Process-unique and nonzero; SKIPPY_NATIVE_SPAN_ID_BIT is set. */ ++ uint64_t id; ++ /** ++ * The enclosing native span's id when there is one, else the reporting ++ * thread's trace tag, else 0. Children end, and so arrive, before their ++ * parent. ++ */ ++ uint64_t parent; ++ /** Dotted span name such as "llama.graph_compute"; static storage. */ ++ const char * name; ++ /** Null, or what the span worked on; valid only during the callback. */ ++ const char * detail; ++ /** Unix nanoseconds. */ ++ int64_t start_unix_ns; ++ int64_t end_unix_ns; ++ /** Null, or the name of one measured quantity; static storage. */ ++ const char * value_name; ++ int64_t value; ++}; ++ ++/** ++ * @brief Receives one native span, on the thread that did the work. ++ * ++ * That is usually the thread inside the native call, so a slow callback ++ * slows the call it measures. The span is valid only for the call. ++ */ ++typedef void (*skippy_native_span_callback)( ++ const struct skippy_native_span_v1 * span, ++ void * user_data); ++ ++/** ++ * @brief Installs the process-global native span callback. ++ * ++ * Install once, before the calls to observe; a null callback stops ++ * reporting. A callback already running may finish after it is cleared. ++ * Installing reaches every loaded backend, which may initialise the backend ++ * registry on the calling thread. Backend spans that ended before a backend ++ * received its first callback (device initialisation compiles kernel ++ * libraries) are delivered from within this call: those that began during ++ * it under the calling thread's tag, earlier ones with no parent. ++ */ ++LLAMA_API enum skippy_status skippy_set_native_span_callback( ++ skippy_native_span_callback callback, ++ void * user_data); ++ ++#define SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION 1 ++ ++/** @brief Timing of one unit of device work, such as a Metal command buffer. */ ++struct skippy_gpu_command_timing_v1 { ++ uint32_t abi_version; ++ uint32_t struct_size; ++ /** The submitting thread's trace tag; 0 when none was set. */ ++ uint64_t tag; ++ /** The ggml backend registry name, such as "MTL"; static storage. */ ++ const char * backend_name; ++ /** Backend instance, and its 1-based graph compute count. */ ++ uint32_t context_id; ++ uint32_t compute_index; ++ /** Execution order of this command within its graph compute. */ ++ uint32_t command_index; ++ uint32_t command_count; ++ /** Graph nodes encoded into this command. */ ++ uint32_t node_count; ++ /** 0 when the device completed the command, else a backend status. */ ++ int32_t status; ++ /** Unix nanoseconds; 0 when the backend did not observe the instant. */ ++ int64_t encode_start_unix_ns; ++ int64_t encode_end_unix_ns; ++ int64_t execute_start_unix_ns; ++ int64_t execute_end_unix_ns; ++ /** ++ * What the command's graph nodes do: "attention", "matmul", "recurrent", ++ * "kv_write" or "other" when every classified node shares that class, ++ * else "mixed"; static storage. Views and reshapes have no class. ++ * Attention is flash attention, or the masked soft max and K/Q, K/Q/V ++ * products of unfused attention; recurrent is SSM, RWKV, gated linear ++ * attention and delta-net state, and copies to or from its cache. ++ */ ++ const char * op_class; ++ /** The model layer of the command's first layer-named node; -1 when unknown. */ ++ int32_t layer; ++ /** ++ * 1 when the backend split this graph at op class boundaries so each ++ * command holds one class (Metal: GGML_METAL_OP_PROFILE=1), else 0. ++ */ ++ uint32_t split_by_class; ++ /** ++ * Attention nodes: the most KV cells one query addresses (the row list ++ * length for attention that reads per-sequence row lists, else the K/V ++ * span; for unfused attention, the K/Q product's K span), the most query ++ * rows one node processes, how many nodes read row lists, and how many ++ * are flash attention (unfused attention has none). ++ */ ++ uint32_t attention_kv_cells; ++ uint32_t attention_queries; ++ uint32_t attention_row_list_nodes; ++ uint32_t attention_flash_nodes; ++ /** Graph nodes by class. */ ++ uint32_t attention_nodes; ++ uint32_t matmul_nodes; ++ uint32_t recurrent_nodes; ++ uint32_t kv_write_nodes; ++ uint32_t other_nodes; ++ /** ++ * Bytes the nodes read, by class: weights and activations for mat-muls; ++ * for gathers from and row writes into a cache, only the rows read or ++ * written; for attention only the K/V rows its nodes address. ++ */ ++ uint64_t attention_bytes; ++ uint64_t matmul_bytes; ++ uint64_t recurrent_bytes; ++ uint64_t kv_write_bytes; ++ uint64_t other_bytes; ++ /** ++ * Recurrent state caches: the most states one gather reads (the states ++ * of the batch's sequences and every state between them), and the most ++ * of those a copy writes back unchanged because no sequence in the batch ++ * owns them. ++ */ ++ uint32_t recurrent_states; ++ uint32_t recurrent_states_carried; ++}; ++ ++/** ++ * @brief Receives one timing record, on a backend-owned completion thread. ++ * ++ * The record is valid only for the duration of the call. Return quickly: ++ * the thread may be serving completion for every command on the device. ++ */ ++typedef void (*skippy_gpu_command_timing_callback)( ++ const struct skippy_gpu_command_timing_v1 * timing, ++ void * user_data); ++ ++/** ++ * @brief Installs the process-global GPU command timing callback. ++ * ++ * Install once, before submitting work; a null callback stops reporting. A ++ * callback already running may finish after it is cleared. Returns ++ * SKIPPY_STATUS_UNSUPPORTED when no loaded backend reports command timing. ++ */ ++LLAMA_API enum skippy_status skippy_set_gpu_command_timing_callback( ++ skippy_gpu_command_timing_callback callback, ++ void * user_data); ++ ++/** ++ * @brief Sets the calling thread's trace tag for the work it does afterwards. ++ * ++ * Native spans without an enclosing native span, and GPU work the thread ++ * submits, carry the tag. Thread-local and cheap; pass 0 to stop tagging. ++ * Tags should leave SKIPPY_NATIVE_SPAN_ID_BIT clear. Backends see the tag ++ * once either callback has been installed. ++ */ ++LLAMA_API void skippy_set_trace_tag(uint64_t tag); ++ ++#ifdef __cplusplus ++} ++#endif ++ ++#endif // SKIPPY_TRACING_H +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 75cb30503..6e4e9023b 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -64,6 +64,7 @@ add_library(llama + skippy/abi.cpp + skippy/block_boundaries.cpp + skippy/devices.cpp ++ skippy/tracing.cpp + skippy/glm_dsa.cpp + skippy/graph_dependencies.cpp + skippy/graph_identity.cpp +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index e460d2250..b3ec732f9 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -17,6 +17,7 @@ + #include "skippy/activation.h" + #include "skippy/environment.h" + #include "skippy/state_memory.h" ++#include "skippy/trace_scope.h" + + #include + #include +@@ -499,6 +500,7 @@ llama_context::llama_context( + } + + if (!hparams.vocab_only) { ++ skippy_trace::scope backend_trace("llama.backend_init"); + // GPU backends + for (const auto & dev : model.devices) { + ggml_backend_t backend = ggml_backend_dev_init(dev.dev, nullptr); +@@ -580,6 +582,8 @@ llama_context::llama_context( + /*.no_alloc =*/ model.no_alloc(), + }; + ++ // allocates the KV cache and recurrent state ++ skippy_trace::scope memory_trace("llama.memory_create"); + memory.reset(model.create_memory(params_mem, cparams, graph_build_inputs.selection)); + } + +@@ -852,6 +856,8 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ + return; + } + ++ skippy_trace::scope trace("llama.sched_reserve"); ++ + sched_need_reserve = false; + ++sched_reserve_count; + +@@ -1010,7 +1016,11 @@ void llama_context::synchronize() { + return; + } + +- ggml_backend_sched_synchronize(sched.get()); ++ { ++ // the host waits here for the device to finish queued work ++ skippy_trace::scope trace("llama.synchronize", "queued_tokens", n_queued_tokens); ++ ggml_backend_sched_synchronize(sched.get()); ++ } + + // FIXME: if multiple single tokens are evaluated without a synchronization, + // the stats will be added to the prompt evaluation stats +@@ -1138,6 +1148,8 @@ bool llama_context::memory_update( + } + } + ++ skippy_trace::scope trace("llama.memory_update"); ++ + // reset the previous graph results to make sure that they won't be reused + // TODO: make mctx->apply() report if a graph reserve is needed, then reset graph results only if the memory module reset the scheduler + for (auto & res : gf_res_prev) { +@@ -1790,7 +1802,13 @@ llm_graph_result * llama_context::process_ubatch( + llama_memory_context_i * mctx, + ggml_status & ret, + const skippy_graph_build_inputs & graph_build_inputs) { +- if (mctx && !mctx->apply()) { ++ skippy_trace::scope trace("llama.process_ubatch", "tokens", ubatch.n_tokens); ++ trace.set_detail("build"); ++ ++ skippy_trace::scope apply_trace("llama.memory_apply"); ++ const bool applied = mctx == nullptr || mctx->apply(); ++ apply_trace.end(); ++ if (!applied) { + LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); + ret = GGML_STATUS_FAILED; + return nullptr; +@@ -1805,6 +1823,7 @@ llm_graph_result * llama_context::process_ubatch( + + if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { + //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); ++ trace.set_detail("reuse"); + + // with pipeline parallelism, the previous graph_compute_async may still be running + // on the GPU. we must synchronize before set_inputs to avoid overwriting input tensors +@@ -1823,7 +1842,10 @@ llm_graph_result * llama_context::process_ubatch( + + //const auto t_start_us = ggml_time_us(); + ++ skippy_trace::scope build_trace("llama.graph_build"); + gf = model.build_graph(gparams); ++ build_trace.set_value("nodes", gf != nullptr ? ggml_graph_n_nodes(gf) : 0); ++ build_trace.end(); + + //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); + +@@ -1843,11 +1865,13 @@ llm_graph_result * llama_context::process_ubatch( + return nullptr; + } + ++ skippy_trace::scope alloc_trace("llama.graph_alloc"); + if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) { + LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__); + ret = GGML_STATUS_ALLOC_FAILED; + return nullptr; + } ++ alloc_trace.end(); + + gf_res_prev_active = res; + } +@@ -1857,12 +1881,16 @@ llm_graph_result * llama_context::process_ubatch( + //const auto t_start_us = ggml_time_us(); + + // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated ++ skippy_trace::scope inputs_trace("llama.set_inputs"); + res->set_inputs(&ubatch, graph_build_inputs); + + //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); + } + ++ // submits the graph; the device may still be running it on return ++ skippy_trace::scope compute_trace("llama.graph_compute", "nodes", ggml_graph_n_nodes(res->get_gf())); + const auto status = graph_compute(res->get_gf(), ubatch.n_tokens > 1); ++ compute_trace.end(); + if (status != GGML_STATUS_SUCCESS) { + LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status); + ret = status; +@@ -2159,6 +2187,8 @@ int llama_context::decode( + return encode(batch_inp, graph_build_inputs); + } + ++ skippy_trace::scope trace("llama.decode", "tokens", (int64_t) batch_inp.tokens.size()); ++ + if (batch_inp.tokens.empty()) { + LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); + return -1; +@@ -2219,12 +2249,14 @@ int llama_context::decode( + } + } + ++ skippy_trace::scope batch_trace("llama.batch_init"); + // Activation imports retain token IDs for sampling, but their position + // sideband has embedding semantics (including overlapping M-RoPE image positions). + if (!balloc->init(batch_inp, vocab, output_all, !graph_build_inputs.activation_frontier.empty())) { + LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__); + return -1; + } ++ batch_trace.end(); + + const uint32_t n_tokens_all = balloc->get_n_tokens(); + const uint32_t n_outputs_all = balloc->get_n_outputs(); +@@ -2265,6 +2297,8 @@ int llama_context::decode( + + llama_memory_context_ptr mctx; + ++ // finds cells for the batch and splits it into ubatches ++ skippy_trace::scope slot_trace("llama.memory_init_batch"); + while (true) { + mctx = memory->init_batch(*balloc, cparams.n_ubatch, embd_all); + if (!mctx) { +@@ -2308,11 +2342,15 @@ int llama_context::decode( + break; + } + ++ slot_trace.end(); ++ + // reserve output buffer ++ skippy_trace::scope output_trace("llama.output_reserve", "outputs", n_outputs_all); + if (output_reserve(n_outputs_all) < n_outputs_all) { + LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all); + return -2; + }; ++ output_trace.end(); + + int64_t n_outputs_prev = 0; + int64_t n_tokens_prev = 0; +@@ -2399,6 +2437,9 @@ int llama_context::decode( + // ggml_graph_dump_dot(gf, NULL, "llama.dot"); + //} + ++ // queues copies of this ubatch's outputs to the host ++ skippy_trace::scope extract_trace("llama.output_extract", "outputs", n_outputs); ++ + auto * t_logits = res->get_logits(); + auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr; + auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr; +@@ -2537,10 +2578,13 @@ int llama_context::decode( + copy_tensor_async_rows(res->t_candidates, sampling.candidates, stride, n_outputs_prev, sched.get(), &sampling.candidates_count); + } + ++ extract_trace.end(); ++ + n_outputs_prev += n_outputs; + n_tokens_prev += ubatch.n_tokens; + if (llm_arch_is_recurrent(model.arch) || llm_arch_is_hybrid(model.arch)) { + // Recurrent state written by this graph must be ready before the next ubatch or output read. ++ skippy_trace::scope sync_trace("llama.recurrent_sync"); + ggml_backend_sched_synchronize(sched.get()); + } + } while (mctx->next()); +@@ -3106,6 +3150,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t + LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); + GGML_ASSERT(n_outputs >= 1); + ++ skippy_trace::scope trace("llama.graph_reserve", "tokens", n_tokens); ++ + if (n_tokens % n_seqs != 0) { + n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs + LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs); +@@ -4121,6 +4167,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl + } + + size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) { ++ skippy_trace::scope trace("llama.state_seq_save", "bytes", (int64_t) size); + std::unique_ptr io; + if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { + io = std::make_unique(dst, size, mem_storage[seq_id]); +@@ -4140,6 +4187,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz + } + + size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) { ++ skippy_trace::scope trace("llama.state_seq_restore", "bytes", (int64_t) size); + std::unique_ptr io; + if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { + // create a temporary io to read the magic and the src seq_id +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index fd12f9966..fe7101445 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -1,4 +1,5 @@ + #include "llama-kv-cache.h" ++#include "skippy/trace_scope.h" + + #include "llama-impl.h" + #include "llama-io.h" +@@ -452,6 +453,7 @@ void llama_kv_cache::init_rotation(const char * name_tag) { + } + + void llama_kv_cache::clear(bool data) { ++ skippy_trace::scope trace("llama.kv_clear"); + for (uint32_t s = 0; s < n_stream; ++s) { + v_cells[s].reset(); + v_heads[s] = 0; +@@ -465,6 +467,7 @@ void llama_kv_cache::clear(bool data) { + } + + bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { ++ skippy_trace::scope trace("llama.kv_seq_rm", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] + if (other) { + return true; +@@ -567,6 +570,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + } + + void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { ++ skippy_trace::scope trace("llama.kv_seq_cp", "seq", seq_id_dst); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] + if (other) { + return; +@@ -659,6 +663,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll + } + + void llama_kv_cache::seq_keep(llama_seq_id seq_id) { ++ skippy_trace::scope trace("llama.kv_seq_keep", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] + if (other) { + return; +@@ -686,6 +691,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { + } + + void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { ++ skippy_trace::scope trace("llama.kv_seq_add", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] + if (other) { + return; +@@ -1636,6 +1642,7 @@ bool llama_kv_cache::stage_export_kv_page( + size_t output_capacity, + size_t * out_bytes, + std::string & error) const { ++ skippy_trace::scope trace("llama.kv_page_export", "seq", seq_id); + if (out_desc == nullptr || out_bytes == nullptr) { + error = "out_desc and out_bytes are required"; + return false; +@@ -1878,6 +1885,7 @@ bool llama_kv_cache::stage_import_kv_page( + size_t input_bytes, + std::string & error, + bool validate_only) { ++ skippy_trace::scope trace("llama.kv_page_import", "bytes", (int64_t) input_bytes); + if (input == nullptr) { + error = "input payload is required"; + return false; +@@ -3527,6 +3535,7 @@ ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_co + } + + void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { ++ skippy_trace::scope trace("llama.kv_state_write", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] + if (other) { + return; +@@ -3599,6 +3608,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla + } + + void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { ++ skippy_trace::scope trace("llama.kv_state_read", "seq", seq_id); + state_read_sinfo(io, seq_id, flags, nullptr, nullptr); + } + +diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp +index b7570d445..c488e921c 100644 +--- a/src/llama-memory-recurrent.cpp ++++ b/src/llama-memory-recurrent.cpp +@@ -1,4 +1,5 @@ + #include "llama-memory-recurrent.h" ++#include "skippy/trace_scope.h" + + #include "ggml-backend.h" + #include "llama-impl.h" +@@ -174,6 +175,7 @@ llama_memory_recurrent::llama_memory_recurrent( + } + + void llama_memory_recurrent::clear(bool data) { ++ skippy_trace::scope trace("llama.recurrent_clear"); + for (int32_t i = 0; i < (int32_t) size; ++i) { + cells[i].pos = -1; + cells[i].seq_id.clear(); +@@ -195,6 +197,7 @@ void llama_memory_recurrent::clear(bool data) { + } + + bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { ++ skippy_trace::scope trace("llama.recurrent_seq_rm", "seq", seq_id); + uint32_t new_head = size; + + if (p0 < 0) { +@@ -292,6 +295,7 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos + } + + void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { ++ skippy_trace::scope trace("llama.recurrent_seq_cp", "seq", seq_id_dst); + if (seq_id_src == seq_id_dst) { + return; + } +@@ -329,6 +333,7 @@ void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id + } + + void llama_memory_recurrent::seq_keep(llama_seq_id seq_id) { ++ skippy_trace::scope trace("llama.recurrent_seq_keep", "seq", seq_id); + uint32_t new_head = size; + + for (uint32_t i = 0; i < size; ++i) { +@@ -361,6 +366,7 @@ void llama_memory_recurrent::seq_keep(llama_seq_id seq_id) { + } + + void llama_memory_recurrent::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { ++ skippy_trace::scope trace("llama.recurrent_seq_add", "seq", seq_id); + if (shift == 0) { + return; + } +@@ -812,6 +818,7 @@ size_t llama_memory_recurrent::size_p_bytes() const { + } + + void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { ++ skippy_trace::scope trace("llama.recurrent_state_write", "seq", seq_id); + GGML_UNUSED(flags); + + std::vector> cell_ranges; // ranges, from inclusive, to exclusive +@@ -893,6 +900,7 @@ void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq + } + + void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { ++ skippy_trace::scope trace("llama.recurrent_state_read", "seq", seq_id); + GGML_UNUSED(flags); + + uint32_t cell_count; +diff --git a/src/llama-model.cpp b/src/llama-model.cpp +index 8ded67e17..f93cbad04 100644 +--- a/src/llama-model.cpp ++++ b/src/llama-model.cpp +@@ -1,4 +1,5 @@ + #include "llama-model.h" ++#include "skippy/trace_scope.h" + + #include "llama-arch.h" + #include "llama-ext.h" +@@ -2193,11 +2194,13 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { + } + + // load tensor data ++ skippy_trace::scope data_trace("llama.load_tensor_data", "buffers", (int64_t) ctx_bufs.size()); + for (auto & [ctx, bufs] : ctx_bufs) { + if (!ml.load_all_data(ctx, bufs, use_mlock ? &pimpl->mlock_mmaps : NULL, params.progress_callback, params.progress_callback_user_data)) { + return false; + } + } ++ data_trace.end(); + + if (use_mmap_buffer) { + for (auto & mapping : ml.mappings) { +diff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp +index 9004efa20..2f0aa0432 100644 +--- a/src/llama-sampler.cpp ++++ b/src/llama-sampler.cpp +@@ -1,4 +1,5 @@ + #include "llama-sampler.h" ++#include "skippy/trace_scope.h" + + #include "llama-impl.h" + #include "llama-vocab.h" +@@ -386,6 +387,9 @@ void llama_sampler_apply(struct llama_sampler * smpl, struct llama_token_data_ar + } + + GGML_ASSERT(smpl->iface->apply); ++ skippy_trace::scope trace("llama.sampler_apply", "candidates", (int64_t) cur_p->size); ++ // a sampler owns its name for its lifetime ++ trace.set_detail(smpl->iface->name != nullptr ? smpl->iface->name(smpl) : nullptr); + smpl->iface->apply(smpl, cur_p); + } + +@@ -894,6 +898,7 @@ uint32_t llama_sampler_backend_n_nodes(const llama_sampler * sampler) { + } + + llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx) { ++ skippy_trace::scope trace("llama.sampler_sample"); + const llama_token sampled_token = llama_get_sampled_token_ith (ctx, idx); + const float * sampled_probs = llama_get_sampled_probs_ith (ctx, idx); + const float * sampled_logits = llama_get_sampled_logits_ith (ctx, idx); +@@ -2680,6 +2685,7 @@ static const char * llama_sampler_grammar_name(const struct llama_sampler * /*sm + static void llama_sampler_grammar_accept_impl(struct llama_sampler * smpl, llama_token token) { + auto * ctx = (llama_sampler_grammar *) smpl->ctx; + if (ctx->grammar) { ++ skippy_trace::scope trace("llama.grammar_accept"); + llama_grammar_accept_impl(*ctx->grammar, token); + } + } +@@ -2687,6 +2693,7 @@ static void llama_sampler_grammar_accept_impl(struct llama_sampler * smpl, llama + static void llama_sampler_grammar_apply(struct llama_sampler * smpl, llama_token_data_array * cur_p) { + auto * ctx = (llama_sampler_grammar *) smpl->ctx; + if (ctx->grammar) { ++ skippy_trace::scope trace("llama.grammar_apply", "candidates", (int64_t) cur_p->size); + llama_grammar_apply_impl(*ctx->grammar, cur_p); + } + } +diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp +index 229a051e0..4008012df 100644 +--- a/src/llama-vocab.cpp ++++ b/src/llama-vocab.cpp +@@ -1,4 +1,5 @@ + #include "llama-vocab.h" ++#include "skippy/trace_scope.h" + + #include "ggml.h" + #include "gguf.h" +@@ -4939,6 +4940,7 @@ int32_t llama_tokenize( + int32_t n_tokens_max, + bool add_special, + bool parse_special) { ++ skippy_trace::scope trace("llama.tokenize", "bytes", text_len); + return vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special); + } + +diff --git a/src/llama.cpp b/src/llama.cpp +index fb9a9bfbb..654b50dda 100644 +--- a/src/llama.cpp ++++ b/src/llama.cpp +@@ -1,4 +1,5 @@ + #include "llama.h" ++#include "skippy/trace_scope.h" + + #include "llama-impl.h" + #include "llama-version.h" +@@ -317,9 +318,12 @@ static std::pair llama_model_load(struct gguf_context * meta + const std::string & fname, std::vector & splits, bool ordered_parts, FILE * file, llama_model_params & params, + const llama_model_loader_stage_selection * stage_selection) { + try { ++ // reads the GGUF header and tensor index ++ skippy_trace::scope open_trace("llama.gguf_open"); + llama_model_loader ml(metadata, set_tensor_data, set_tensor_data_ud, fname, splits, ordered_parts, file, params.load_mode, + params.check_tensors, params.no_alloc, params.load_mtp, params.kv_overrides, params.tensor_buft_overrides, + stage_selection); ++ open_trace.end(); + + ml.lazy.mode = params.lazy_mode; + +@@ -346,6 +350,7 @@ static std::pair llama_model_load(struct gguf_context * meta + model->hparams.vocab_only = params.vocab_only; + + try { ++ skippy_trace::scope trace("llama.load_hparams"); + model->load_hparams(ml); + } catch(const std::exception & e) { + throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what())); +@@ -354,6 +359,7 @@ static std::pair llama_model_load(struct gguf_context * meta + throw std::runtime_error("CLIP cannot be used as main model, use it with --mmproj instead"); + } + try { ++ skippy_trace::scope trace("llama.load_vocab"); + model->load_vocab(ml); + } catch(const std::exception & e) { + throw std::runtime_error("error loading model vocabulary: " + std::string(e.what())); +@@ -367,9 +373,11 @@ static std::pair llama_model_load(struct gguf_context * meta + return {0, model_ptr.release()}; + } + ++ skippy_trace::scope tensors_trace("llama.load_tensors"); + if (!model->load_tensors(ml)) { + return {-2, nullptr}; + } ++ tensors_trace.end(); + + return {0, model_ptr.release()}; + } catch (const std::exception & err) { +diff --git a/src/skippy/abi.cpp b/src/skippy/abi.cpp +index ceed6e5d3..15c5c343b 100644 +--- a/src/skippy/abi.cpp ++++ b/src/skippy/abi.cpp +@@ -43,6 +43,7 @@ uint64_t skippy_abi_features(void) { + SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 | + SKIPPY_FEATURE_KV_EVENTS | + SKIPPY_FEATURE_DEVICE_EVENTS | ++ SKIPPY_FEATURE_NATIVE_TRACING | + SKIPPY_FEATURE_DIAGNOSTIC_EVENTS | + SKIPPY_FEATURE_UNLOAD_EVENTS | + SKIPPY_FEATURE_NON_CHAT_WORKLOADS | +diff --git a/src/skippy/activation.cpp b/src/skippy/activation.cpp +index 7167e5f7a..885b602e9 100644 +--- a/src/skippy/activation.cpp ++++ b/src/skippy/activation.cpp +@@ -7,6 +7,7 @@ + #include "skippy-verify-checkpoint.h" + #include "skippy/devices.h" + #include "skippy/verify_window.h" ++#include "skippy/trace_scope.h" + + #include + #include "gguf.h" +@@ -468,6 +469,7 @@ enum skippy_status skippy_decode_batch( + int32_t glm_dsa_phase_hint, + struct skippy_error ** out_error, + const skippy_graph_build_inputs * graph_build_inputs) { ++ skippy_trace::scope prepare_trace("skippy.decode_prepare", "tokens", static_cast(token_count)); + if (session == nullptr || session->ctx == nullptr || token_count == 0) { + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and at least one token are required"); + return SKIPPY_STATUS_INVALID_ARGUMENT; +@@ -498,6 +500,7 @@ enum skippy_status skippy_decode_batch( + inputs.selection.glm_dsa_phase_hint, + token_count); + } ++ prepare_trace.end(); + skippy_glm_dsa_op_timing_begin(session, token_count); + int32_t rc = 0; + const bool decoded = skippy_contain_native_failure( +diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp +index 40faff815..a31540652 100644 +--- a/src/skippy/execution-batch.cpp ++++ b/src/skippy/execution-batch.cpp +@@ -6,6 +6,7 @@ + #include "skippy/runtime_types.h" + #include "skippy/sampling_internal.h" + #include "skippy/selected_logits.h" ++#include "skippy/trace_scope.h" + + #include "llama-arch.h" + #include "llama-context.h" +@@ -254,6 +255,8 @@ enum skippy_status skippy_iteration_batch_sampled( + size_t sampled_output_capacity, + size_t * out_sampled_output_count, + struct skippy_error ** out_error) { ++ // validation, output frames, the batched frontier and the llama batch ++ skippy_trace::scope prepare_trace("skippy.batch_prepare", "requests", static_cast(request_count)); + if (requests == nullptr || request_count == 0 || out_sampled_output_count == nullptr) { + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, + "requests, request_count, and out_sampled_output_count are required"); +@@ -448,6 +451,7 @@ enum skippy_status skippy_iteration_batch_sampled( + seq_ids.data(), + logits.data(), + }; ++ prepare_trace.end(); + int32_t decode_rc = 0; + if (!skippy_contain_native_failure( + out_error, [&] { decode_rc = first->ctx->decode(batch, graph_inputs); })) { +@@ -461,6 +465,8 @@ enum skippy_status skippy_iteration_batch_sampled( + skippy_mark_context_work_pending(first->stage_model); + skippy_synchronize_context_if_pending(first->stage_model); + ++ // exports, readouts and sampling, request by request ++ skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); + size_t sampled_index = 0; + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; +diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp +index bbc1c2d42..a4bf2a475 100644 +--- a/src/skippy/model_loading.cpp ++++ b/src/skippy/model_loading.cpp +@@ -22,6 +22,7 @@ + #include "llama-model-loader.h" + #include "model_load_config_internal.h" + #include "skippy/graph_identity.h" ++#include "skippy/trace_scope.h" + #include "../vendor/nlohmann/json.hpp" + + #include +@@ -762,7 +763,10 @@ enum skippy_status skippy_finish_model_open( + } + + const skippy_graph_build_inputs graph_build_inputs = skippy_graph_build_inputs_from_config(config); ++ skippy_trace::scope context_trace("llama.context_init"); ++ context_trace.set_detail("target"); + stage_model->ctx = llama_init_from_model_with_graph_inputs(model, params, graph_build_inputs); ++ context_trace.end(); + if (stage_model->ctx == nullptr) { + const char * message = "failed to create llama context"; + if (event_scope != nullptr) { +@@ -871,7 +875,10 @@ enum skippy_status skippy_finish_model_open( + // MTP consumes raw multirow outputs, without session backend samplers. + mtp_params.n_outputs_max_per_seq = 0; + mtp_params.embeddings = false; ++ skippy_trace::scope mtp_trace("llama.context_init"); ++ mtp_trace.set_detail("mtp"); + stage_model->mtp_ctx = llama_init_from_model_with_graph_inputs(model, mtp_params, graph_build_inputs); ++ mtp_trace.end(); + if (stage_model->mtp_ctx != nullptr) { + llama_set_embeddings_nextn(stage_model->ctx, true, false); + llama_set_embeddings_nextn(stage_model->mtp_ctx, true, false); +@@ -988,10 +995,12 @@ enum skippy_status skippy_model_open_impl( + params.progress_callback_user_data = &event_scope; + } + ++ skippy_trace::scope backend_trace("skippy.backend_init"); + llama_backend_init(); + if (!ggml_backend_reg_count()) { + ggml_backend_load_all(); + } ++ backend_trace.end(); + std::vector selected_devices; + enum skippy_status device_status = skippy_apply_selected_backend_device(config, params, selected_devices, out_error); + if (device_status != SKIPPY_STATUS_OK) { +@@ -1003,8 +1012,10 @@ enum skippy_status skippy_model_open_impl( + return device_status; + } + const auto selection = skippy_loader_selection(config); ++ skippy_trace::scope load_trace("llama.model_load"); + llama_model * model = llama_model_load_from_file_with_selection( + path, params, skippy_loader_selection_ptr(config, selection)); ++ load_trace.end(); + if (model == nullptr) { + const char * message = "failed to load llama model"; + event_scope.emit_failure(SKIPPY_STATUS_MODEL_ERROR, message); +@@ -1080,10 +1091,12 @@ enum skippy_status skippy_model_open_from_parts_impl( + params.progress_callback_user_data = &event_scope; + } + ++ skippy_trace::scope backend_trace("skippy.backend_init"); + llama_backend_init(); + if (!ggml_backend_reg_count()) { + ggml_backend_load_all(); + } ++ backend_trace.end(); + std::vector selected_devices; + enum skippy_status device_status = skippy_apply_selected_backend_device(config, params, selected_devices, out_error); + if (device_status != SKIPPY_STATUS_OK) { +@@ -1095,8 +1108,10 @@ enum skippy_status skippy_model_open_from_parts_impl( + return device_status; + } + const auto selection = skippy_loader_selection(config); ++ skippy_trace::scope load_trace("llama.model_load", "parts", static_cast(path_count)); + llama_model * model = llama_model_load_from_parts_with_selection( + paths, path_count, params, skippy_loader_selection_ptr(config, selection)); ++ load_trace.end(); + if (model == nullptr) { + const char * message = "failed to load llama model from GGUF parts"; + event_scope.emit_failure(SKIPPY_STATUS_MODEL_ERROR, message); +@@ -1154,10 +1169,12 @@ enum skippy_status skippy_model_attach_mtp_draft_model( + skippy_apply_host_expert_placement(config, model_params, tensor_placement); + } + ++ skippy_trace::scope backend_trace("skippy.backend_init"); + llama_backend_init(); + if (!ggml_backend_reg_count()) { + ggml_backend_load_all(); + } ++ backend_trace.end(); + std::vector selected_devices; + enum skippy_status device_status = skippy_apply_selected_backend_device(config, model_params, selected_devices, out_error); + if (device_status != SKIPPY_STATUS_OK) { +diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp +index b688fce73..671ccbb3c 100644 +--- a/src/skippy/sampling.cpp ++++ b/src/skippy/sampling.cpp +@@ -7,6 +7,7 @@ + #include "../../common/sampling.h" + #include "skippy/sampling_internal.h" + #include "skippy/speculative_internal.h" ++#include "skippy/trace_scope.h" + + #include "llama-impl.h" + #include "../vendor/nlohmann/json.hpp" +@@ -575,6 +576,7 @@ llama_token skippy_sample_token_ith( + skippy_session * session, + const skippy_sampling_config * sampling, + int32_t logits_index) { ++ skippy_trace::scope trace("skippy.sample"); + if (session == nullptr || session->reset_required || session->ctx == nullptr || + session->stage_model == nullptr || session->stage_model->model == nullptr) { + return LLAMA_TOKEN_NULL; +diff --git a/src/skippy/speculative_decoding.cpp b/src/skippy/speculative_decoding.cpp +index 7f55c0d88..3fb86667d 100644 +--- a/src/skippy/speculative_decoding.cpp ++++ b/src/skippy/speculative_decoding.cpp +@@ -6,6 +6,7 @@ + #include "skippy/runtime_types.h" + #include "skippy/sampling_internal.h" + #include "skippy/speculative_internal.h" ++#include "skippy/trace_scope.h" + + #include "llama-context.h" + #include "llama-graph.h" +@@ -191,6 +192,7 @@ enum skippy_status skippy_mtp_sync_target_inputs( + token_count == 0) { + return skippy_success(out_error); + } ++ skippy_trace::scope trace("skippy.mtp_sync", "tokens", static_cast(token_count)); + if (token_count > static_cast(std::numeric_limits::max())) { + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "MTP token_count exceeds int32_t range"); + return SKIPPY_STATUS_INVALID_ARGUMENT; +diff --git a/src/skippy/trace_scope.h b/src/skippy/trace_scope.h +new file mode 100644 +index 000000000..b64d9da37 +--- /dev/null ++++ b/src/skippy/trace_scope.h +@@ -0,0 +1,61 @@ ++#pragma once ++ ++// Native trace spans (skippy/tracing.h) for Skippy and llama internals. With ++// no span callback installed a scope costs one atomic load. ++ ++#include ++ ++namespace skippy_trace { ++ ++// A span from construction until end() or destruction, nested under the ++// scope already open on this thread, else under the thread's trace tag. ++// Scopes on one thread must end in reverse order of construction. ++class scope { ++ public: ++ explicit scope(const char * name) noexcept; ++ scope(const char * name, const char * value_name, int64_t value) noexcept; ++ ~scope() { end(); } ++ ++ scope(const scope &) = delete; ++ scope & operator=(const scope &) = delete; ++ ++ // `detail` must outlive the scope ++ void set_detail(const char * detail) noexcept { detail_ = detail; } ++ void set_value(const char * value_name, int64_t value) noexcept { ++ value_name_ = value_name; ++ value_ = value; ++ } ++ ++ // ends the span now; later calls and the destructor do nothing ++ void end() noexcept; ++ ++ private: ++ const char * name_; ++ const char * detail_ = nullptr; ++ const char * value_name_ = nullptr; ++ int64_t value_ = 0; ++ uint64_t id_ = 0; ++ uint64_t parent_ = 0; ++ uint64_t previous_ = 0; ++ int64_t start_unix_ns_ = 0; ++}; ++ ++// What a span begun now on this thread nests under: its open scope, else its ++// trace tag; 0 when there is neither. ++uint64_t current_parent() noexcept; ++ ++// While it lives, spans this thread begins nest under `parent`, so work done ++// on another thread's behalf joins that thread's trace. ++class adopt { ++ public: ++ explicit adopt(uint64_t parent) noexcept; ++ ~adopt(); ++ ++ adopt(const adopt &) = delete; ++ adopt & operator=(const adopt &) = delete; ++ ++ private: ++ uint64_t previous_; ++}; ++ ++} // namespace skippy_trace +diff --git a/src/skippy/tracing.cpp b/src/skippy/tracing.cpp +new file mode 100644 +index 000000000..9aa48e08c +--- /dev/null ++++ b/src/skippy/tracing.cpp +@@ -0,0 +1,272 @@ ++#include "skippy/tracing.h" ++#include "skippy/trace_scope.h" ++ ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++ ++namespace { ++ ++// Each supporting backend registry gets its own forwarder, so a record can ++// name the backend it came from. ++constexpr size_t MAX_TRACING_BACKENDS = 4; ++ ++std::atomic g_span_callback { nullptr }; ++std::atomic g_span_user_data { nullptr }; ++ ++std::atomic g_gpu_callback { nullptr }; ++std::atomic g_gpu_user_data { nullptr }; ++ ++// Read on every tagged native call, so lock-free. ++std::array, MAX_TRACING_BACKENDS> g_tag_setters {}; ++ ++std::atomic g_next_span_id { 0 }; ++ ++// when the span callback was last installed; backend spans kept from before ++// then have no known parent ++std::atomic g_span_install_unix_ns { 0 }; ++ ++// the innermost open scope on this thread, and the tag its caller set ++thread_local uint64_t t_current = 0; ++thread_local uint64_t t_tag = 0; ++ ++int64_t unix_now_ns() { ++ return std::chrono::duration_cast( ++ std::chrono::system_clock::now().time_since_epoch()).count(); ++} ++ ++uint64_t next_span_id() { ++ return (g_next_span_id.fetch_add(1, std::memory_order_relaxed) + 1) | SKIPPY_NATIVE_SPAN_ID_BIT; ++} ++ ++void deliver_span( ++ uint64_t id, uint64_t parent, const char * name, const char * detail, ++ int64_t start_unix_ns, int64_t end_unix_ns, const char * value_name, int64_t value) { ++ const auto callback = g_span_callback.load(std::memory_order_acquire); ++ if (callback == nullptr) { ++ return; ++ } ++ skippy_native_span_v1 span = {}; ++ span.abi_version = SKIPPY_NATIVE_SPAN_V1_ABI_VERSION; ++ span.struct_size = sizeof(span); ++ span.id = id; ++ span.parent = parent; ++ span.name = name; ++ span.detail = detail; ++ span.start_unix_ns = start_unix_ns; ++ span.end_unix_ns = end_unix_ns; ++ span.value_name = value_name; ++ span.value = value; ++ callback(&span, g_span_user_data.load(std::memory_order_acquire)); ++} ++ ++// A backend span joins the open scope on its thread when there is one (a ++// pipeline compiled inside llama.graph_compute), else the tag the backend ++// carried (a dispatch worker encoding for a tagged call), else the thread's ++// own tag: device initialisation that the install itself triggered. Spans ++// kept from before the install began have no parent. ++uint64_t backend_span_parent(const ggml_backend_trace_span & span) { ++ if (t_current != 0) { ++ return t_current; ++ } ++ if (span.tag != 0) { ++ return span.tag; ++ } ++ return span.start_unix_ns < g_span_install_unix_ns.load(std::memory_order_acquire) ? 0 : t_tag; ++} ++ ++void forward_backend_span(const ggml_backend_trace_span * span, void *) { ++ if (span == nullptr || span->name == nullptr) { ++ return; ++ } ++ const uint64_t parent = backend_span_parent(*span); ++ deliver_span(next_span_id(), parent, span->name, span->detail, ++ span->start_unix_ns, span->end_unix_ns, nullptr, 0); ++} ++ ++// the names skippy/tracing.h documents for ggml_backend_op_class ++const char * op_class_name(int32_t op_class) { ++ switch (op_class) { ++ case GGML_BACKEND_OP_CLASS_OTHER: return "other"; ++ case GGML_BACKEND_OP_CLASS_ATTENTION: return "attention"; ++ case GGML_BACKEND_OP_CLASS_MATMUL: return "matmul"; ++ case GGML_BACKEND_OP_CLASS_RECURRENT: return "recurrent"; ++ case GGML_BACKEND_OP_CLASS_KV_WRITE: return "kv_write"; ++ default: return "mixed"; ++ } ++} ++ ++void fill_op_classes(skippy_gpu_command_timing_v1 & record, const ggml_backend_command_timing & timing) { ++ record.op_class = op_class_name(timing.op_class); ++ record.layer = timing.layer; ++ record.split_by_class = timing.split_by_class; ++ record.attention_kv_cells = timing.attention_kv_cells; ++ record.attention_queries = timing.attention_queries; ++ record.attention_row_list_nodes = timing.attention_row_list_nodes; ++ record.attention_flash_nodes = timing.attention_flash_nodes; ++ record.attention_nodes = timing.class_nodes[GGML_BACKEND_OP_CLASS_ATTENTION]; ++ record.matmul_nodes = timing.class_nodes[GGML_BACKEND_OP_CLASS_MATMUL]; ++ record.recurrent_nodes = timing.class_nodes[GGML_BACKEND_OP_CLASS_RECURRENT]; ++ record.kv_write_nodes = timing.class_nodes[GGML_BACKEND_OP_CLASS_KV_WRITE]; ++ record.other_nodes = timing.class_nodes[GGML_BACKEND_OP_CLASS_OTHER]; ++ record.attention_bytes = timing.class_bytes[GGML_BACKEND_OP_CLASS_ATTENTION]; ++ record.matmul_bytes = timing.class_bytes[GGML_BACKEND_OP_CLASS_MATMUL]; ++ record.recurrent_bytes = timing.class_bytes[GGML_BACKEND_OP_CLASS_RECURRENT]; ++ record.kv_write_bytes = timing.class_bytes[GGML_BACKEND_OP_CLASS_KV_WRITE]; ++ record.other_bytes = timing.class_bytes[GGML_BACKEND_OP_CLASS_OTHER]; ++ record.recurrent_states = timing.recurrent_states; ++ record.recurrent_states_carried = timing.recurrent_states_carried; ++} ++ ++void forward_command_timing(const ggml_backend_command_timing * timing, void * user_data) { ++ const auto callback = g_gpu_callback.load(std::memory_order_acquire); ++ if (callback == nullptr || timing == nullptr) { ++ return; ++ } ++ auto * reg = static_cast(user_data); ++ ++ skippy_gpu_command_timing_v1 record = {}; ++ record.abi_version = SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION; ++ record.struct_size = sizeof(record); ++ record.tag = timing->tag; ++ record.backend_name = reg != nullptr ? ggml_backend_reg_name(reg) : ""; ++ record.context_id = timing->context_id; ++ record.compute_index = timing->compute_index; ++ record.command_index = timing->command_index; ++ record.command_count = timing->command_count; ++ record.node_count = timing->node_count; ++ record.status = timing->status; ++ record.encode_start_unix_ns = timing->encode_start_unix_ns; ++ record.encode_end_unix_ns = timing->encode_end_unix_ns; ++ record.execute_start_unix_ns = timing->execute_start_unix_ns; ++ record.execute_end_unix_ns = timing->execute_end_unix_ns; ++ fill_op_classes(record, *timing); ++ ++ callback(&record, g_gpu_user_data.load(std::memory_order_acquire)); ++} ++ ++template ++T backend_proc(ggml_backend_reg_t reg, const char * name) { ++ return reinterpret_cast(ggml_backend_reg_get_proc_address(reg, name)); ++} ++ ++// Remember every backend that takes a tag, so skippy_set_trace_tag reaches ++// it whichever callback was installed. Returns how many there are. ++size_t register_tag_setters() { ++ size_t count = 0; ++ for (size_t i = 0; i < ggml_backend_reg_count() && count < MAX_TRACING_BACKENDS; ++i) { ++ const auto set_tag = backend_proc( ++ ggml_backend_reg_get(i), "ggml_backend_set_command_timing_tag"); ++ if (set_tag != nullptr) { ++ g_tag_setters[count++].store(set_tag, std::memory_order_release); ++ } ++ } ++ return count; ++} ++ ++} // namespace ++ ++namespace skippy_trace { ++ ++scope::scope(const char * name) noexcept : name_(name) { ++ if (g_span_callback.load(std::memory_order_relaxed) == nullptr) { ++ return; ++ } ++ id_ = next_span_id(); ++ previous_ = t_current; ++ parent_ = t_current != 0 ? t_current : t_tag; ++ t_current = id_; ++ start_unix_ns_ = unix_now_ns(); ++} ++ ++scope::scope(const char * name, const char * value_name, int64_t value) noexcept : scope(name) { ++ set_value(value_name, value); ++} ++ ++void scope::end() noexcept { ++ if (id_ == 0) { ++ return; ++ } ++ const int64_t end_unix_ns = unix_now_ns(); ++ t_current = previous_; ++ deliver_span(id_, parent_, name_, detail_, start_unix_ns_, end_unix_ns, value_name_, value_); ++ id_ = 0; ++} ++ ++uint64_t current_parent() noexcept { ++ return t_current != 0 ? t_current : t_tag; ++} ++ ++adopt::adopt(uint64_t parent) noexcept : previous_(t_current) { ++ if (parent != 0) { ++ t_current = parent; ++ } ++} ++ ++adopt::~adopt() { ++ t_current = previous_; ++} ++ ++} // namespace skippy_trace ++ ++enum skippy_status skippy_set_native_span_callback( ++ skippy_native_span_callback callback, ++ void * user_data) { ++ if (callback == nullptr) { ++ g_span_callback.store(nullptr, std::memory_order_release); ++ } else { ++ g_span_install_unix_ns.store(unix_now_ns(), std::memory_order_release); ++ g_span_user_data.store(user_data, std::memory_order_relaxed); ++ g_span_callback.store(callback, std::memory_order_release); ++ } ++ ++ register_tag_setters(); ++ for (size_t i = 0; i < ggml_backend_reg_count(); ++i) { ++ const auto set_callback = backend_proc( ++ ggml_backend_reg_get(i), "ggml_backend_set_trace_span_callback"); ++ if (set_callback != nullptr) { ++ set_callback(callback != nullptr ? forward_backend_span : nullptr, nullptr); ++ } ++ } ++ ++ // Skippy and llama report their own spans with or without a backend. ++ return SKIPPY_STATUS_OK; ++} ++ ++enum skippy_status skippy_set_gpu_command_timing_callback( ++ skippy_gpu_command_timing_callback callback, ++ void * user_data) { ++ if (callback == nullptr) { ++ g_gpu_callback.store(nullptr, std::memory_order_release); ++ } else { ++ g_gpu_user_data.store(user_data, std::memory_order_relaxed); ++ g_gpu_callback.store(callback, std::memory_order_release); ++ } ++ ++ register_tag_setters(); ++ size_t supported = 0; ++ for (size_t i = 0; i < ggml_backend_reg_count(); ++i) { ++ ggml_backend_reg_t reg = ggml_backend_reg_get(i); ++ const auto set_callback = backend_proc( ++ reg, "ggml_backend_set_command_timing_callback"); ++ if (set_callback != nullptr) { ++ set_callback(callback != nullptr ? forward_command_timing : nullptr, reg); ++ ++supported; ++ } ++ } ++ ++ return supported > 0 ? SKIPPY_STATUS_OK : SKIPPY_STATUS_UNSUPPORTED; ++} ++ ++void skippy_set_trace_tag(uint64_t tag) { ++ t_tag = tag; ++ for (const auto & setter : g_tag_setters) { ++ const auto set_tag = setter.load(std::memory_order_acquire); ++ if (set_tag == nullptr) { ++ return; ++ } ++ set_tag(tag); ++ } ++} +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index b8b159025..638e84e37 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -185,6 +185,9 @@ llama_build_and_test(test-skippy-rerank-template.cpp) + llama_build_and_test(test-skippy-activation-validation.cpp) + + if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) ++ # scopes are internal to libllama ++ llama_build_and_test(test-skippy-tracing.cpp) ++ target_include_directories(test-skippy-tracing PRIVATE ${PROJECT_SOURCE_DIR}/ggml/src ${PROJECT_SOURCE_DIR}/src) + llama_build_and_test(test-skippy-cachegen-import.cpp) + llama_build_and_test(test-skippy-sampling-suppress.cpp) + llama_build_and_test(test-skippy-kv-page-export.cpp) +@@ -330,6 +333,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) + + if (GGML_METAL) + llama_build_and_test(test-skippy-cachegen-metal.cpp) ++ llama_build_and_test(test-skippy-tracing-metal.cpp) + endif() + # debug tool for chat template differential analysis (not registered as a test, run it manually) + llama_build(test-chat-analysis.cpp) +diff --git a/tests/test-skippy-tracing-metal.cpp b/tests/test-skippy-tracing-metal.cpp +new file mode 100644 +index 000000000..365052e0e +--- /dev/null ++++ b/tests/test-skippy-tracing-metal.cpp +@@ -0,0 +1,155 @@ ++// skippy native tracing on the real Metal backend: library initialisation ++// that ran before the install is still reported, and a tagged graph compute ++// reports the pipelines it compiled and the command buffers that ran, in ++// order, on the GPU ++ ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++#include "ggml-metal.h" ++#include "ggml.h" ++#include "skippy/common.h" ++#include "skippy/tracing.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(cond) \ ++ do { \ ++ if (!(cond)) { \ ++ std::fprintf(stderr, "%s:%d: CHECK(%s)\n", __FILE__, __LINE__, #cond); \ ++ return 1; \ ++ } \ ++ } while (0) ++ ++namespace { ++ ++constexpr uint64_t TAG = 0x5eed; ++ ++struct received_span { ++ std::string name; ++ std::string detail; ++ uint64_t parent; ++ int64_t start_unix_ns; ++ int64_t end_unix_ns; ++}; ++ ++// timings arrive on Metal's completion thread, spans on encoding threads ++std::mutex g_mutex; ++std::vector g_received; ++std::vector g_spans; ++ ++void receive(const skippy_gpu_command_timing_v1 * timing, void *) { ++ std::lock_guard lock(g_mutex); ++ g_received.push_back(*timing); ++} ++ ++void receive_span(const skippy_native_span_v1 * span, void *) { ++ std::lock_guard lock(g_mutex); ++ g_spans.push_back({ span->name, span->detail != nullptr ? span->detail : "", span->parent, ++ span->start_unix_ns, span->end_unix_ns }); ++} ++ ++size_t received_count() { ++ std::lock_guard lock(g_mutex); ++ return g_received.size(); ++} ++ ++bool has_span(const char * name, uint64_t parent) { ++ std::lock_guard lock(g_mutex); ++ for (const auto & span : g_spans) { ++ if (span.name == name && span.parent == parent && span.start_unix_ns <= span.end_unix_ns) { ++ return true; ++ } ++ } ++ return false; ++} ++ ++} // namespace ++ ++int main() { ++ ggml_backend_t backend = ggml_backend_metal_init(); ++ if (backend == nullptr) { ++ std::fprintf(stderr, "no Metal device; skipping\n"); ++ return 0; ++ } ++ ++ // the device compiled its libraries before anyone listened ++ CHECK(skippy_set_native_span_callback(receive_span, nullptr) == SKIPPY_STATUS_OK); ++ CHECK(has_span("mtl.library_init", 0)); ++ CHECK(skippy_set_gpu_command_timing_callback(receive, nullptr) == SKIPPY_STATUS_OK); ++ ++ ggml_init_params params = { ggml_tensor_overhead() * 8 + ggml_graph_overhead(), nullptr, true }; ++ ggml_context * ctx = ggml_init(params); ++ CHECK(ctx != nullptr); ++ ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4096); ++ ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4096); ++ ggml_tensor * c = ggml_add(ctx, ggml_mul(ctx, a, b), b); ++ ggml_cgraph * gf = ggml_new_graph(ctx); ++ ggml_build_forward_expand(gf, c); ++ ++ ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); ++ CHECK(buffer != nullptr); ++ const std::vector ones(4096, 1.0f); ++ ggml_backend_tensor_set(a, ones.data(), 0, ggml_nbytes(a)); ++ ggml_backend_tensor_set(b, ones.data(), 0, ggml_nbytes(b)); ++ ++ const auto submitted = std::chrono::system_clock::now(); ++ skippy_set_trace_tag(TAG); ++ CHECK(ggml_backend_graph_compute(backend, gf) == GGML_STATUS_SUCCESS); ++ skippy_set_trace_tag(0); ++ ++ // the graph's kernels were first used here, by this call ++ CHECK(has_span("mtl.pipeline_compile", TAG)); ++ ++ // completion handlers run after the GPU finishes, possibly after synchronize returns ++ for (int i = 0; i < 200 && received_count() == 0; ++i) { ++ std::this_thread::sleep_for(std::chrono::milliseconds(10)); ++ } ++ ++ std::vector received; ++ { ++ std::lock_guard lock(g_mutex); ++ received = g_received; ++ } ++ CHECK(!received.empty()); ++ ++ const char * backend_name = ggml_backend_reg_name(ggml_backend_metal_reg()); ++ const int64_t submitted_ns = std::chrono::duration_cast( ++ submitted.time_since_epoch()).count(); ++ // mul and add are neither attention, mat-muls, recurrent state nor KV writes ++ uint32_t other_nodes = 0; ++ for (const auto & t : received) { ++ other_nodes += t.other_nodes; ++ CHECK(std::strcmp(t.op_class, "other") == 0); ++ CHECK(t.attention_nodes == 0 && t.matmul_nodes == 0 && t.recurrent_nodes == 0 && t.kv_write_nodes == 0); ++ CHECK(t.layer == -1); ++ } ++ CHECK(other_nodes == 2); ++ for (const auto & t : received) { ++ CHECK(t.tag == TAG); ++ CHECK(std::strcmp(t.backend_name, backend_name) == 0); ++ CHECK(t.status == 0); ++ CHECK(t.compute_index >= 1); ++ CHECK(t.command_index < t.command_count); ++ CHECK(t.encode_start_unix_ns <= t.encode_end_unix_ns); ++ CHECK(t.execute_start_unix_ns > 0 && t.execute_start_unix_ns <= t.execute_end_unix_ns); ++ // a clock-conversion error would land far from the submission time ++ CHECK(t.execute_start_unix_ns > submitted_ns - 1000000000LL); ++ CHECK(t.execute_end_unix_ns < submitted_ns + 10000000000LL); ++ } ++ ++ CHECK(skippy_set_gpu_command_timing_callback(nullptr, nullptr) == SKIPPY_STATUS_OK); ++ CHECK(skippy_set_native_span_callback(nullptr, nullptr) == SKIPPY_STATUS_OK); ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++ ggml_backend_free(backend); ++ ++ std::printf("ok: %zu command buffer(s)\n", received.size()); ++ return 0; ++} +diff --git a/tests/test-skippy-tracing.cpp b/tests/test-skippy-tracing.cpp +new file mode 100644 +index 000000000..804c2f7e0 +--- /dev/null ++++ b/tests/test-skippy-tracing.cpp +@@ -0,0 +1,306 @@ ++// skippy native tracing on any platform: scope nesting and tags, and a fake ++// backend registry for span and GPU command timing forwarding ++ ++#include "ggml-backend-impl.h" ++#include "ggml-backend.h" ++#include "skippy/common.h" ++#include "skippy/trace_scope.h" ++#include "skippy/tracing.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(cond) \ ++ do { \ ++ if (!(cond)) { \ ++ std::fprintf(stderr, "%s:%d: CHECK(%s)\n", __FILE__, __LINE__, #cond); \ ++ return 1; \ ++ } \ ++ } while (0) ++ ++namespace { ++ ++// what the fake backend was handed ++ggml_backend_command_timing_callback_t g_backend_callback = nullptr; ++void * g_backend_user_data = nullptr; ++ggml_backend_trace_span_callback_t g_backend_span_callback = nullptr; ++void * g_backend_span_user_data = nullptr; ++uint64_t g_backend_tag = 0; ++ ++void fake_set_callback(ggml_backend_command_timing_callback_t callback, void * user_data) { ++ g_backend_callback = callback; ++ g_backend_user_data = user_data; ++} ++ ++void fake_set_span_callback(ggml_backend_trace_span_callback_t callback, void * user_data) { ++ g_backend_span_callback = callback; ++ g_backend_span_user_data = user_data; ++} ++ ++void fake_set_tag(uint64_t tag) { ++ g_backend_tag = tag; ++} ++ ++const char * fake_name(ggml_backend_reg_t) { ++ return "FakeGPU"; ++} ++ ++size_t fake_device_count(ggml_backend_reg_t) { ++ return 0; ++} ++ ++ggml_backend_dev_t fake_device(ggml_backend_reg_t, size_t) { ++ return nullptr; ++} ++ ++void * fake_proc(ggml_backend_reg_t, const char * name) { ++ if (std::strcmp(name, "ggml_backend_set_command_timing_callback") == 0) { ++ return (void *) (ggml_backend_set_command_timing_callback_t) fake_set_callback; ++ } ++ if (std::strcmp(name, "ggml_backend_set_command_timing_tag") == 0) { ++ return (void *) (ggml_backend_set_command_timing_tag_t) fake_set_tag; ++ } ++ if (std::strcmp(name, "ggml_backend_set_trace_span_callback") == 0) { ++ return (void *) (ggml_backend_set_trace_span_callback_t) fake_set_span_callback; ++ } ++ return nullptr; ++} ++ ++ggml_backend_reg g_fake_reg = { ++ /* .api_version = */ GGML_BACKEND_API_VERSION, ++ /* .iface = */ { fake_name, fake_device_count, fake_device, fake_proc }, ++ /* .context = */ nullptr, ++}; ++ ++struct received_span { ++ skippy_native_span_v1 span; ++ std::string name; ++ std::string detail; ++}; ++ ++int g_user_marker = 0; ++ ++std::vector g_spans; ++std::vector g_timings; ++ ++// built-in backends may report their own spans; keep the test's ++void receive_span(const skippy_native_span_v1 * span, void * user_data) { ++ if (span == nullptr || user_data != &g_user_marker || std::strncmp(span->name, "test.", 5) != 0) { ++ return; ++ } ++ g_spans.push_back({ *span, span->name, span->detail != nullptr ? span->detail : "" }); ++} ++ ++void receive_timing(const skippy_gpu_command_timing_v1 * timing, void * user_data) { ++ if (timing != nullptr && user_data == &g_user_marker) { ++ g_timings.push_back(*timing); ++ } ++} ++ ++const received_span * find_span(const char * name) { ++ for (const auto & span : g_spans) { ++ if (span.name == name) { ++ return &span; ++ } ++ } ++ return nullptr; ++} ++ ++int64_t unix_now_ns() { ++ return std::chrono::duration_cast( ++ std::chrono::system_clock::now().time_since_epoch()).count(); ++} ++ ++int check_scopes() { ++ // nothing is reported before a callback is installed ++ { ++ skippy_trace::scope early("test.early"); ++ } ++ CHECK(skippy_set_native_span_callback(receive_span, &g_user_marker) == SKIPPY_STATUS_OK); ++ CHECK(find_span("test.early") == nullptr); ++ ++ skippy_set_trace_tag(42); ++ { ++ skippy_trace::scope outer("test.outer", "tokens", 7); ++ { ++ skippy_trace::scope inner("test.inner"); ++ inner.set_detail("reuse"); ++ } ++ skippy_trace::scope sibling("test.sibling"); ++ sibling.end(); ++ sibling.end(); ++ } ++ skippy_set_trace_tag(0); ++ { ++ skippy_trace::scope untagged("test.untagged"); ++ } ++ ++ CHECK(g_spans.size() == 4); ++ const auto * outer = find_span("test.outer"); ++ const auto * inner = find_span("test.inner"); ++ const auto * sibling = find_span("test.sibling"); ++ const auto * untagged = find_span("test.untagged"); ++ CHECK(outer && inner && sibling && untagged); ++ // children end, and arrive, first ++ CHECK(g_spans[0].name == "test.inner" && g_spans[2].name == "test.outer"); ++ ++ for (const auto & got : g_spans) { ++ CHECK(got.span.abi_version == SKIPPY_NATIVE_SPAN_V1_ABI_VERSION); ++ CHECK(got.span.struct_size == sizeof(skippy_native_span_v1)); ++ CHECK((got.span.id & SKIPPY_NATIVE_SPAN_ID_BIT) != 0); ++ CHECK(got.span.start_unix_ns > 0 && got.span.start_unix_ns <= got.span.end_unix_ns); ++ } ++ CHECK(outer->span.parent == 42); ++ CHECK(inner->span.parent == outer->span.id); ++ CHECK(sibling->span.parent == outer->span.id); ++ CHECK(untagged->span.parent == 0); ++ CHECK(inner->span.id != outer->span.id && sibling->span.id != inner->span.id); ++ CHECK(inner->span.start_unix_ns >= outer->span.start_unix_ns); ++ CHECK(inner->span.end_unix_ns <= outer->span.end_unix_ns); ++ CHECK(std::strcmp(outer->span.value_name, "tokens") == 0 && outer->span.value == 7); ++ CHECK(inner->span.value_name == nullptr && inner->detail == "reuse"); ++ ++ // work another thread does on this one's behalf joins the scope that handed it over ++ g_spans.clear(); ++ { ++ skippy_trace::scope handing("test.handing"); ++ const uint64_t parent = skippy_trace::current_parent(); ++ CHECK(parent != 0); ++ std::thread([parent] { ++ skippy_trace::adopt joined(parent); ++ skippy_trace::scope adopted("test.adopted"); ++ }).join(); ++ } ++ std::thread([] { ++ skippy_trace::adopt none(skippy_trace::current_parent()); ++ skippy_trace::scope lone("test.lone"); ++ }).join(); ++ const auto * handing = find_span("test.handing"); ++ const auto * adopted = find_span("test.adopted"); ++ const auto * lone = find_span("test.lone"); ++ CHECK(handing && adopted && lone); ++ CHECK(adopted->span.parent == handing->span.id); ++ CHECK(lone->span.parent == 0); ++ return 0; ++} ++ ++int check_backend() { ++ ggml_backend_register(&g_fake_reg); ++ ++ CHECK(skippy_set_native_span_callback(receive_span, &g_user_marker) == SKIPPY_STATUS_OK); ++ CHECK(g_backend_span_callback != nullptr); ++ CHECK(skippy_set_gpu_command_timing_callback(receive_timing, &g_user_marker) == SKIPPY_STATUS_OK); ++ CHECK(g_backend_callback != nullptr); ++ CHECK(g_backend_user_data == &g_fake_reg); ++ ++ skippy_set_trace_tag(77); ++ CHECK(g_backend_tag == 77); ++ ++ // a span the backend kept from before the install has no parent ++ g_spans.clear(); ++ ggml_backend_trace_span span = { 0, "test.kept", "kept detail", 1000, 2000 }; ++ g_backend_span_callback(&span, g_backend_span_user_data); ++ // one from this thread joins its tag, or its open scope ++ const int64_t now = unix_now_ns(); ++ span = { 0, "test.backend", "pipeline", now, now + 10 }; ++ g_backend_span_callback(&span, g_backend_span_user_data); ++ { ++ skippy_trace::scope open("test.open"); ++ span = { 5, "test.nested", nullptr, now, now + 10 }; ++ g_backend_span_callback(&span, g_backend_span_user_data); ++ } ++ // a backend tag wins outside a scope (a dispatch worker encoding) ++ span = { 9, "test.worker", nullptr, now, now + 10 }; ++ g_backend_span_callback(&span, g_backend_span_user_data); ++ ++ const auto * kept = find_span("test.kept"); ++ const auto * owned = find_span("test.backend"); ++ const auto * open = find_span("test.open"); ++ const auto * nested = find_span("test.nested"); ++ const auto * worker = find_span("test.worker"); ++ CHECK(kept && owned && open && nested && worker); ++ CHECK(kept->span.parent == 0 && kept->detail == "kept detail"); ++ CHECK(owned->span.parent == 77 && owned->detail == "pipeline"); ++ CHECK(nested->span.parent == open->span.id); ++ CHECK(worker->span.parent == 9); ++ CHECK((owned->span.id & SKIPPY_NATIVE_SPAN_ID_BIT) != 0); ++ CHECK(owned->span.start_unix_ns == now && owned->span.end_unix_ns == now + 10); ++ ++ ggml_backend_command_timing timing = {}; ++ timing.tag = 77; ++ timing.context_id = 3; ++ timing.compute_index = 7; ++ timing.command_index = 1; ++ timing.command_count = 2; ++ timing.node_count = 64; ++ timing.encode_start_unix_ns = 1000; ++ timing.encode_end_unix_ns = 2000; ++ timing.execute_start_unix_ns = 2500; ++ timing.execute_end_unix_ns = 9000; ++ timing.op_class = GGML_BACKEND_OP_CLASS_ATTENTION; ++ timing.layer = 11; ++ timing.split_by_class = 1; ++ timing.attention_kv_cells = 4096; ++ timing.attention_queries = 4; ++ timing.attention_row_list_nodes = 2; ++ timing.attention_flash_nodes = 2; ++ timing.class_nodes[GGML_BACKEND_OP_CLASS_ATTENTION] = 2; ++ timing.class_nodes[GGML_BACKEND_OP_CLASS_OTHER] = 3; ++ timing.class_bytes[GGML_BACKEND_OP_CLASS_ATTENTION] = 1 << 20; ++ timing.class_bytes[GGML_BACKEND_OP_CLASS_MATMUL] = 1 << 10; ++ timing.recurrent_states = 9; ++ timing.recurrent_states_carried = 5; ++ g_backend_callback(&timing, g_backend_user_data); ++ ++ CHECK(g_timings.size() == 1); ++ const skippy_gpu_command_timing_v1 & got = g_timings[0]; ++ CHECK(got.abi_version == SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION); ++ CHECK(got.struct_size == sizeof(skippy_gpu_command_timing_v1)); ++ CHECK(got.tag == 77); ++ CHECK(std::strcmp(got.backend_name, "FakeGPU") == 0); ++ CHECK(got.context_id == 3 && got.compute_index == 7); ++ CHECK(got.command_index == 1 && got.command_count == 2 && got.node_count == 64); ++ CHECK(got.status == 0); ++ CHECK(got.encode_start_unix_ns == 1000 && got.encode_end_unix_ns == 2000); ++ CHECK(got.execute_start_unix_ns == 2500 && got.execute_end_unix_ns == 9000); ++ CHECK(std::strcmp(got.op_class, "attention") == 0); ++ CHECK(got.layer == 11 && got.split_by_class == 1); ++ CHECK(got.attention_kv_cells == 4096 && got.attention_queries == 4 && got.attention_row_list_nodes == 2); ++ CHECK(got.attention_flash_nodes == 2); ++ CHECK(got.attention_nodes == 2 && got.other_nodes == 3 && got.matmul_nodes == 0); ++ CHECK(got.attention_bytes == (1 << 20) && got.matmul_bytes == (1 << 10) && got.other_bytes == 0); ++ CHECK(got.recurrent_states == 9 && got.recurrent_states_carried == 5); ++ ++ // a command that mixes classes says so ++ timing.op_class = GGML_BACKEND_OP_CLASS_COUNT; ++ g_backend_callback(&timing, g_backend_user_data); ++ CHECK(g_timings.size() == 2 && std::strcmp(g_timings[1].op_class, "mixed") == 0); ++ ++ // clearing stops both reports ++ CHECK(skippy_set_gpu_command_timing_callback(nullptr, nullptr) == SKIPPY_STATUS_OK); ++ CHECK(g_backend_callback == nullptr); ++ CHECK(skippy_set_native_span_callback(nullptr, nullptr) == SKIPPY_STATUS_OK); ++ CHECK(g_backend_span_callback == nullptr); ++ g_spans.clear(); ++ { ++ skippy_trace::scope cleared("test.cleared"); ++ } ++ CHECK(g_spans.empty()); ++ skippy_set_trace_tag(0); ++ return 0; ++} ++ ++} // namespace ++ ++int main() { ++ if (check_scopes() != 0 || check_backend() != 0) { ++ return 1; ++ } ++ std::printf("ok\n"); ++ return 0; ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch new file mode 100644 index 0000000000..11f828c08b --- /dev/null +++ b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch @@ -0,0 +1,621 @@ +From 53c13a8bef39b480fb887be77cbed4602cadb63f Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Thu, 5 Nov 2026 01:00:00 +1100 +Subject: [PATCH 20/32] skippy: sample a batch's requests concurrently + +An iteration's sampled requests waited for one another: after the batch's +outputs were recorded, each request ran its sampler chain in turn on the +scheduler thread while the GPU sat idle. With four requests decoding +together on Qwen3.5-4B, sampling took about 0.5 ms of every ~21 ms step, +most of it the top-k pass over the full 248,320-token vocabulary. + +skippy_iteration_batch_sampled now records every request's outputs first and +then samples the requests together. Its sessions are already distinct and +share one context. A sampler that would attach or retire a backend sampler +on that context, or that samples through one, is readied and sampled first +on the calling thread. The rest sample at the same time, one thread each, +under a skippy.sample_concurrent span that their skippy.sample spans join. + +Sampling reads the context's outputs, and every read synchronizes the +context and applies pending output reorders, which write to it. A +llama_synchronized_outputs, made only by llama_context::synchronize_outputs +after doing both, lets a thread hold a llama_output_reader; while it does, +that thread's reads of the context skip both steps, so concurrent readers +write nothing shared. + +skippy-concurrent-sampling decodes four lanes together for twelve steps on +dense and hybrid recurrent fixtures, and checks every sampled token against +four more sessions with the same seeded samplers sampling the same rows one +after another, and that all four sampled under the concurrent span. + +Co-Authored-By: Claude Opus 5.5 +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + src/CMakeLists.txt | 12 ++ + src/llama-context.cpp | 23 ++- + src/llama-context.h | 33 +++++ + src/llama-graph.h | 2 +- + src/skippy/batch_sampling.cpp | 91 ++++++++++++ + src/skippy/batch_sampling.h | 20 +++ + src/skippy/execution-batch.cpp | 25 ++-- + src/skippy/sampling.cpp | 42 +++++- + src/skippy/sampling_internal.h | 6 + + src/skippy/tests/concurrent_sampling.cpp | 175 +++++++++++++++++++++++ + 10 files changed, 412 insertions(+), 17 deletions(-) + create mode 100644 src/skippy/batch_sampling.cpp + create mode 100644 src/skippy/batch_sampling.h + create mode 100644 src/skippy/tests/concurrent_sampling.cpp + +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 6e4e9023b..7eee0656e 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -82,6 +82,7 @@ add_library(llama + ../common/json.cpp + ../common/llguidance.cpp + skippy/sampling.cpp ++ skippy/batch_sampling.cpp + skippy/sampling_config.cpp + skippy/chat_sampling.cpp + skippy/sampling_vocab.cpp +@@ -493,6 +494,17 @@ if (LLAMA_STAGE_BUILD_TESTS) + endfunction() + add_skippy_sampling_history_state_tests(granitehybrid skippy-noalloc-granite-hybrid-fixture recurrent) + ++ add_executable(skippy-concurrent-sampling skippy/tests/concurrent_sampling.cpp) ++ target_include_directories(skippy-concurrent-sampling PRIVATE .) ++ target_compile_features(skippy-concurrent-sampling PRIVATE cxx_std_17) ++ target_link_libraries(skippy-concurrent-sampling PRIVATE llama) ++ add_test(NAME skippy_concurrent_sampling_gemma ++ COMMAND skippy-concurrent-sampling "${SKIPPY_MODEL_FIXTURE_DIR}/gemma-dense.gguf") ++ set_tests_properties(skippy_concurrent_sampling_gemma PROPERTIES FIXTURES_REQUIRED skippy-model-loader-fixtures) ++ add_test(NAME skippy_concurrent_sampling_qwen35 ++ COMMAND skippy-concurrent-sampling "${SKIPPY_MODEL_FIXTURE_DIR}/qwen35-dense.gguf") ++ set_tests_properties(skippy_concurrent_sampling_qwen35 PROPERTIES FIXTURES_REQUIRED skippy-noalloc-qwen35-fixture) ++ + add_test( + NAME skippy_generate_qwen3_fixture + COMMAND skippy-model-fixture-generator +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index b3ec732f9..d9068d348 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -1011,8 +1011,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ + __func__, (t_end_us - t_start_us)/1000.0, ggml_backend_sched_get_n_copies(sched.get())); + } + ++// the context whose synchronized outputs this thread reads, if any ++static thread_local const llama_context * t_output_reader_ctx = nullptr; ++ ++llama_output_reader::llama_output_reader(const llama_synchronized_outputs & outputs) ++ : previous(t_output_reader_ctx) { ++ t_output_reader_ctx = &outputs.context(); ++} ++ ++llama_output_reader::~llama_output_reader() { ++ t_output_reader_ctx = previous; ++} ++ ++llama_synchronized_outputs llama_context::synchronize_outputs() { ++ synchronize(); ++ output_reorder(); ++ return llama_synchronized_outputs(*this); ++} ++ + void llama_context::synchronize() { +- if (!sched) { ++ if (!sched || t_output_reader_ctx == this) { + return; + } + +@@ -2860,6 +2878,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to + } + + void llama_context::output_reorder() { ++ if (t_output_reader_ctx == this) { ++ return; ++ } + const uint64_t n_vocab = model.vocab.n_tokens(); + const uint64_t n_embd = model.hparams.n_embd; + const uint64_t n_embd_out = model.hparams.n_embd_out(); +diff --git a/src/llama-context.h b/src/llama-context.h +index f8884668f..919813ac8 100644 +--- a/src/llama-context.h ++++ b/src/llama-context.h +@@ -66,6 +66,36 @@ struct llama_memory_buffer { + + using llama_memory_buffers = std::map; + ++struct llama_context; ++ ++// Proof that a context's outputs were synchronized and reordered; made only ++// by llama_context::synchronize_outputs. ++class llama_synchronized_outputs { ++ public: ++ const llama_context & context() const { return ctx; } ++ ++ private: ++ friend struct llama_context; ++ explicit llama_synchronized_outputs(const llama_context & ctx) : ctx(ctx) {} ++ ++ const llama_context & ctx; ++}; ++ ++// While one lives, its thread reads the context's outputs without ++// synchronizing or reordering them, so several threads may read at once. The ++// thread that synchronized queues no work on the context meanwhile. ++class llama_output_reader { ++ public: ++ explicit llama_output_reader(const llama_synchronized_outputs & outputs); ++ ~llama_output_reader(); ++ ++ llama_output_reader(const llama_output_reader &) = delete; ++ llama_output_reader & operator=(const llama_output_reader &) = delete; ++ ++ private: ++ const llama_context * previous; ++}; ++ + struct llama_context { + // init scheduler and compute buffers, reserve worst-case graphs + llama_context( +@@ -86,6 +116,9 @@ struct llama_context { + + void synchronize(); + ++ // synchronizes and reorders the outputs, for llama_output_reader ++ llama_synchronized_outputs synchronize_outputs(); ++ + const llama_model & get_model() const; + const llama_cparams & get_cparams() const; + const skippy_graph_build_inputs & get_graph_build_inputs() const; +diff --git a/src/llama-graph.h b/src/llama-graph.h +index 2622c5878..54fd815ef 100644 +--- a/src/llama-graph.h ++++ b/src/llama-graph.h +@@ -1674,7 +1674,7 @@ struct llm_graph_context { + int32_t state_size, + int32_t n_seqs, + skippy_state_kind kind, int il, +- const llm_graph_get_rows_fn & get_state_rows = ggml_get_rows) const; ++ const llm_graph_get_rows_fn & get_state_rows = nullptr) const; + + ggml_tensor * build_rwkv_token_shift_load( + llm_graph_input_rs * inp, +diff --git a/src/skippy/batch_sampling.cpp b/src/skippy/batch_sampling.cpp +new file mode 100644 +index 000000000..e59c89857 +--- /dev/null ++++ b/src/skippy/batch_sampling.cpp +@@ -0,0 +1,91 @@ ++#include "skippy/batch_sampling.h" ++ ++#include "llama-context.h" ++#include "skippy/runtime_types.h" ++#include "skippy/sampling_internal.h" ++#include "skippy/trace_scope.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++ ++bool distinct_sessions(const std::vector & requests) { ++ std::vector sessions(requests.size()); ++ std::transform(requests.begin(), requests.end(), sessions.begin(), ++ [](const skippy_sample_request & request) { return request.session; }); ++ std::sort(sessions.begin(), sessions.end()); ++ return std::adjacent_find(sessions.begin(), sessions.end()) == sessions.end(); ++} ++ ++llama_token sample(const skippy_sample_request & request) { ++ return skippy_sample_token_ith(request.session, request.sampling, request.logits_index); ++} ++ ++// One helper thread per index after the first, which this thread samples. ++// Each thread writes only its own slot of `tokens`. ++void sample_concurrently( ++ const std::vector & requests, ++ std::vector::const_iterator first, ++ std::vector::const_iterator last, ++ const llama_synchronized_outputs & outputs, ++ std::vector & tokens) { ++ skippy_trace::scope trace("skippy.sample_concurrent", "requests", std::distance(first, last)); ++ const uint64_t parent = skippy_trace::current_parent(); ++ const auto sample_reading = [&requests, &tokens, &outputs](size_t index) { ++ const llama_output_reader reader(outputs); ++ tokens[index] = sample(requests[index]); ++ }; ++ std::vector helpers; ++ helpers.reserve(static_cast(std::distance(first, last))); ++ std::for_each(std::next(first), last, [&](size_t index) { ++ try { ++ helpers.emplace_back([&sample_reading, index, parent] { ++ const skippy_trace::adopt joined(parent); ++ sample_reading(index); ++ }); ++ } catch (const std::system_error &) { ++ sample_reading(index); ++ } ++ }); ++ sample_reading(*first); ++ std::for_each(helpers.begin(), helpers.end(), [](std::thread & helper) { helper.join(); }); ++} ++ ++bool share_context( ++ const std::vector & requests, ++ std::vector::const_iterator first, ++ std::vector::const_iterator last) { ++ const llama_context * ctx = requests[*first].session->ctx; ++ return std::all_of(first, last, [&](size_t index) { return requests[index].session->ctx == ctx; }); ++} ++ ++} // namespace ++ ++std::vector skippy_sample_requests(const std::vector & requests) { ++ std::vector tokens(requests.size(), LLAMA_TOKEN_NULL); ++ if (requests.size() < 2 || !distinct_sessions(requests)) { ++ std::transform(requests.begin(), requests.end(), tokens.begin(), sample); ++ return tokens; ++ } ++ ++ // Readying a sampler may attach or retire a backend sampler on the shared ++ // context, and those that remain on it sample through it: both stay here. ++ std::vector order(requests.size()); ++ std::iota(order.begin(), order.end(), size_t { 0 }); ++ const auto concurrent = std::stable_partition(order.begin(), order.end(), [&](size_t index) { ++ return !skippy_prepare_concurrent_sample(requests[index].session, requests[index].sampling); ++ }); ++ std::for_each(order.begin(), concurrent, [&](size_t index) { tokens[index] = sample(requests[index]); }); ++ ++ if (std::distance(concurrent, order.end()) < 2 || !share_context(requests, concurrent, order.end())) { ++ std::for_each(concurrent, order.end(), [&](size_t index) { tokens[index] = sample(requests[index]); }); ++ return tokens; ++ } ++ const llama_synchronized_outputs outputs = requests[*concurrent].session->ctx->synchronize_outputs(); ++ sample_concurrently(requests, concurrent, order.end(), outputs, tokens); ++ return tokens; ++} +diff --git a/src/skippy/batch_sampling.h b/src/skippy/batch_sampling.h +new file mode 100644 +index 000000000..0c253ca71 +--- /dev/null ++++ b/src/skippy/batch_sampling.h +@@ -0,0 +1,20 @@ ++#pragma once ++ ++#include "llama.h" ++ ++#include ++#include ++ ++struct skippy_sampling_config; ++struct skippy_session; ++ ++struct skippy_sample_request { ++ skippy_session * session; ++ const skippy_sampling_config * sampling; ++ int32_t logits_index; ++}; ++ ++// Every request's next token, in request order. When the sessions are ++// distinct, those whose samplers only read the shared context sample at the ++// same time, one thread each; the rest sample first, on this thread. ++std::vector skippy_sample_requests(const std::vector & requests); +diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp +index a31540652..83c290ee2 100644 +--- a/src/skippy/execution-batch.cpp ++++ b/src/skippy/execution-batch.cpp +@@ -1,5 +1,6 @@ + #include "skippy.h" + #include "skippy/activation_internal.h" ++#include "skippy/batch_sampling.h" + #include "skippy/errors.h" + #include "skippy/graph_build_inputs.h" + #include "skippy/runtime_support.h" +@@ -467,7 +468,10 @@ enum skippy_status skippy_iteration_batch_sampled( + + // exports, readouts and sampling, request by request + skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); +- size_t sampled_index = 0; ++ // the sessions are distinct and share one context: they sample together ++ // once every request's outputs are recorded ++ std::vector samples; ++ std::vector sample_request_indexes; + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; + status = skippy_copy_batched_exports( +@@ -495,16 +499,19 @@ enum skippy_status skippy_iteration_batch_sampled( + if (request.sample_last && request_logits) { + // Logits are indexed by the original batch row; llama.cpp handles + // sparse output-row translation internally. +- const skippy_status sample_status = skippy_store_sampled_token( +- skippy_sample_token_ith( +- request.session, request.sampling, +- static_cast(offsets[request_index + 1] - 1)), +- &out_predicted_tokens[sampled_index], out_error); +- if (sample_status != SKIPPY_STATUS_OK) return sample_status; +- out_sampled_request_indexes[sampled_index++] = request_index; ++ samples.push_back({ request.session, request.sampling, ++ static_cast(offsets[request_index + 1] - 1) }); ++ sample_request_indexes.push_back(request_index); + } + } +- *out_sampled_output_count = sampled_index; ++ const std::vector sampled = skippy_sample_requests(samples); ++ const auto exhausted = std::find_if(sampled.begin(), sampled.end(), [](llama_token token) { return token < 0; }); ++ if (exhausted != sampled.end()) { ++ return skippy_store_sampled_token(*exhausted, out_predicted_tokens, out_error); ++ } ++ std::copy(sampled.begin(), sampled.end(), out_predicted_tokens); ++ std::copy(sample_request_indexes.begin(), sample_request_indexes.end(), out_sampled_request_indexes); ++ *out_sampled_output_count = sampled.size(); + return skippy_success(out_error); + } + +diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp +index 671ccbb3c..d9f980c39 100644 +--- a/src/skippy/sampling.cpp ++++ b/src/skippy/sampling.cpp +@@ -545,6 +545,40 @@ static bool skippy_ensure_plain_sampling_chain( + return true; + } + ++static bool skippy_sampling_session_ready(const skippy_session * session) { ++ return session != nullptr && !session->reset_required && session->ctx != nullptr && ++ session->stage_model != nullptr && session->stage_model->model != nullptr; ++} ++ ++// the session's configured sampler already serves this request ++static bool skippy_uses_session_sampler( ++ const skippy_session * session, ++ const skippy_sampling_config * sampling) { ++ return session->sampler != nullptr && ++ (!session->chat_sampling_metadata.empty() || ++ (skippy_sampling_enabled(sampling) && session->sampling_config_valid && ++ skippy_sampling_configs_equal(session->sampling_config, *sampling))); ++} ++ ++bool skippy_prepare_concurrent_sample( ++ skippy_session * session, ++ const skippy_sampling_config * sampling) { ++ if (!skippy_sampling_session_ready(session)) { ++ return false; ++ } ++ try { ++ if (!skippy_uses_session_sampler(session, sampling) && ++ !skippy_ensure_plain_sampling_chain(session, sampling)) { ++ return false; ++ } ++ } catch (...) { ++ // sampling on the calling thread reports the failure ++ return false; ++ } ++ // a backend sampler reads and retires through the shared context ++ return session->sampler != nullptr && !session->sampling_backend_enabled; ++} ++ + void skippy_refresh_backend_sampling( + skippy_session * session, + const skippy_sampling_config * sampling) { +@@ -577,15 +611,11 @@ llama_token skippy_sample_token_ith( + const skippy_sampling_config * sampling, + int32_t logits_index) { + skippy_trace::scope trace("skippy.sample"); +- if (session == nullptr || session->reset_required || session->ctx == nullptr || +- session->stage_model == nullptr || session->stage_model->model == nullptr) { ++ if (!skippy_sampling_session_ready(session)) { + return LLAMA_TOKEN_NULL; + } + try { +- if (session->sampler != nullptr && +- (!session->chat_sampling_metadata.empty() || +- (skippy_sampling_enabled(sampling) && session->sampling_config_valid && +- skippy_sampling_configs_equal(session->sampling_config, *sampling)))) { ++ if (skippy_uses_session_sampler(session, sampling)) { + return skippy_chat_sample_token(session, logits_index); + } + if (skippy_ensure_plain_sampling_chain(session, sampling)) { +diff --git a/src/skippy/sampling_internal.h b/src/skippy/sampling_internal.h +index 7bbf16016..38621b6e9 100644 +--- a/src/skippy/sampling_internal.h ++++ b/src/skippy/sampling_internal.h +@@ -64,4 +64,10 @@ llama_token skippy_sample_token_ith( + skippy_session * session, + const skippy_sampling_config * sampling, + int32_t logits_index); ++// Readies the session's sampler on the calling thread; true when sampling it ++// afterwards only reads the shared context, so other threads may sample other ++// sessions at the same time. ++bool skippy_prepare_concurrent_sample( ++ skippy_session * session, ++ const skippy_sampling_config * sampling); + llama_token skippy_sample_token(skippy_session * session, const skippy_sampling_config * sampling); +diff --git a/src/skippy/tests/concurrent_sampling.cpp b/src/skippy/tests/concurrent_sampling.cpp +new file mode 100644 +index 000000000..0e19dbce5 +--- /dev/null ++++ b/src/skippy/tests/concurrent_sampling.cpp +@@ -0,0 +1,175 @@ ++#include "skippy.h" ++#include "../runtime_types.h" ++#include "../sampling_internal.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(condition) do { if (!(condition)) { \ ++ std::fprintf(stderr, "CHECK failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); } } while (0) ++ ++namespace { ++ ++constexpr size_t LANES = 4; ++constexpr int STEPS = 12; ++ ++void ok(skippy_status status, skippy_error * error) { ++ if (status != SKIPPY_STATUS_OK) { ++ std::fprintf(stderr, "native failure: %s\n", error ? error->message : "no detail"); ++ std::exit(1); ++ } ++ skippy_error_free(error); ++} ++ ++struct span { ++ uint64_t id; ++ uint64_t parent; ++ std::string name; ++}; ++ ++// spans arrive from every sampling thread ++std::vector g_spans; ++std::atomic g_receiving { false }; ++ ++void receive(const skippy_native_span_v1 * received, void *) { ++ while (g_receiving.exchange(true, std::memory_order_acquire)) {} ++ g_spans.push_back({ received->id, received->parent, received->name }); ++ g_receiving.store(false, std::memory_order_release); ++} ++ ++skippy_session * create(skippy_model * model) { ++ skippy_session * session = nullptr; ++ skippy_error * error = nullptr; ++ ok(skippy_session_create(model, &session, &error), error); ++ return session; ++} ++ ++// a seeded random sampler: not greedy, so it samples on the CPU ++skippy_sampling_config random_sampling(uint32_t seed) { ++ skippy_sampling_config config{}; ++ config.version = 1; ++ config.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ config.seed = seed; ++ config.top_k = 40; ++ config.temperature = 1.3f; ++ config.top_p = 0.95f; ++ config.repeat_penalty = 1.0f; ++ config.reasoning_budget_tokens = -1; ++ return config; ++} ++ ++std::array decode_together( ++ const std::array & sessions, ++ const std::array & tokens, ++ const std::array & sampling) { ++ std::array requests{}; ++ std::array order{}; ++ std::iota(order.begin(), order.end(), size_t { 0 }); ++ std::transform(order.begin(), order.end(), requests.begin(), [&](size_t lane) { ++ skippy_iteration_request request{}; ++ request.session = sessions[lane]; ++ request.token_ids = &tokens[lane]; ++ request.token_count = 1; ++ request.sampling = &sampling[lane]; ++ request.sample_last = true; ++ return request; ++ }); ++ std::array indexes{}; ++ std::array predicted{}; ++ size_t count = 0; ++ skippy_error * error = nullptr; ++ ok(skippy_iteration_batch_sampled(requests.data(), LANES, nullptr, nullptr, nullptr, nullptr, ++ indexes.data(), predicted.data(), LANES, &count, &error), error); ++ CHECK(count == LANES); ++ CHECK(indexes == order); ++ return predicted; ++} ++ ++} // namespace ++ ++int main(int argc, char ** argv) { ++ CHECK(argc == 2); ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = "CPU"; ++ config.n_gpu_layers = 0; ++ config.ctx_size = 512; ++ config.lane_count = 2 * LANES; ++ config.kv_unified = 1; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ ok(skippy_model_open(argv[1], &config, &model, &error), error); ++ const auto n_vocab = static_cast(model->model->vocab.n_tokens()); ++ CHECK(n_vocab > 64); ++ ++ std::array together{}; ++ std::array alone{}; ++ std::array sampling{}; ++ std::array next{}; ++ std::array lanes{}; ++ std::iota(lanes.begin(), lanes.end(), size_t { 0 }); ++ std::for_each(lanes.begin(), lanes.end(), [&](size_t lane) { ++ together[lane] = create(model); ++ alone[lane] = create(model); ++ sampling[lane] = random_sampling(17 + static_cast(lane)); ++ const std::vector prompt = { static_cast(3 + lane), 7, 5 }; ++ size_t bytes = 0; ++ skippy_error * prefill_error = nullptr; ++ ok(skippy_prefill_chunk(together[lane], prompt.data(), prompt.size(), ++ nullptr, 0, nullptr, 0, &bytes, &prefill_error), prefill_error); ++ next[lane] = static_cast(9 + lane); ++ }); ++ ++ CHECK(skippy_set_native_span_callback(receive, nullptr) == SKIPPY_STATUS_OK); ++ std::vector generated; ++ for (int step = 0; step < STEPS; ++step) { ++ g_spans.clear(); ++ const auto predicted = decode_together(together, next, sampling); ++ // Samplers with the same seeds read the same rows, one after another. ++ std::array expected{}; ++ std::transform(lanes.begin(), lanes.end(), expected.begin(), [&](size_t lane) { ++ return skippy_sample_token_ith(alone[lane], &sampling[lane], static_cast(lane)); ++ }); ++ CHECK(predicted == expected); ++ CHECK(std::all_of(predicted.begin(), predicted.end(), ++ [&](llama_token token) { return token >= 0 && token < n_vocab; })); ++ ++ // all four sampled under one concurrent span, which nests in the batch outputs ++ const auto named = [](const char * name) { ++ return [name](const span & candidate) { return candidate.name == name; }; ++ }; ++ const auto concurrent = std::find_if(g_spans.begin(), g_spans.end(), named("skippy.sample_concurrent")); ++ const auto outputs = std::find_if(g_spans.begin(), g_spans.end(), named("skippy.batch_outputs")); ++ CHECK(concurrent != g_spans.end() && outputs != g_spans.end()); ++ CHECK(concurrent->parent == outputs->id); ++ const auto under_concurrent = std::count_if(g_spans.begin(), g_spans.end(), [&](const span & candidate) { ++ return candidate.name == "skippy.sample" && candidate.parent == concurrent->id; ++ }); ++ CHECK(under_concurrent == static_cast(LANES)); ++ ++ generated.insert(generated.end(), predicted.begin(), predicted.end()); ++ next = predicted; ++ } ++ CHECK(skippy_set_native_span_callback(nullptr, nullptr) == SKIPPY_STATUS_OK); ++ // seeded random sampling over a random model varies its choices ++ std::sort(generated.begin(), generated.end()); ++ CHECK(std::distance(generated.begin(), std::unique(generated.begin(), generated.end())) > 4); ++ ++ std::for_each(lanes.begin(), lanes.end(), [&](size_t lane) { ++ skippy_error * free_error = nullptr; ++ ok(skippy_session_free(together[lane], &free_error), free_error); ++ ok(skippy_session_free(alone[lane], &free_error), free_error); ++ }); ++ ok(skippy_model_free(model, &error), error); ++ std::printf("ok\n"); ++ return 0; ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0021-skippy-trace-K-V-row-list-runs.patch b/skippy/llama_cpp/patches/0021-skippy-trace-K-V-row-list-runs.patch new file mode 100644 index 0000000000..5ae7502cdb --- /dev/null +++ b/skippy/llama_cpp/patches/0021-skippy-trace-K-V-row-list-runs.patch @@ -0,0 +1,149 @@ +From d5bd4b0df8fd7fea4e7f57d2ae39595cce53eb6e Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sat, 7 Nov 2026 19:12:33 +1100 +Subject: [PATCH 21/32] skippy: trace K/V row-list runs + +Each ubatch that fills row lists reports a llama.kv_rows span: the most +contiguous cell runs one list holds, with cells:runs per slice in its +detail, so a trace shows how fragmented the unified pool is for each query +slice. skippy_trace::active() lets that work run only while a span callback +is installed. + +The row-list path is measured against ordinary attention over the unified +pool with llama.cpp's own LLAMA_KV_ROWS_DISABLE. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + src/CMakeLists.txt | 1 + + src/llama-kv-cache.cpp | 2 ++ + src/skippy/kv_rows_trace.cpp | 41 ++++++++++++++++++++++++++++++++++++ + src/skippy/kv_rows_trace.h | 7 ++++++ + src/skippy/trace_scope.h | 3 +++ + src/skippy/tracing.cpp | 4 ++++ + 6 files changed, 58 insertions(+) + create mode 100644 src/skippy/kv_rows_trace.cpp + create mode 100644 src/skippy/kv_rows_trace.h + +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 7eee0656e..7dad15759 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -65,6 +65,7 @@ add_library(llama + skippy/block_boundaries.cpp + skippy/devices.cpp + skippy/tracing.cpp ++ skippy/kv_rows_trace.cpp + skippy/glm_dsa.cpp + skippy/graph_dependencies.cpp + skippy/graph_identity.cpp +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index fe7101445..d00c1fe4a 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -1,4 +1,5 @@ + #include "llama-kv-cache.h" ++#include "skippy/kv_rows_trace.h" + #include "skippy/trace_scope.h" + + #include "llama-impl.h" +@@ -3191,6 +3192,7 @@ void llama_kv_cache::set_input_attn_mask(const llm_attn_mask & attn_mask, const + int32_t * data = (int32_t *) attn_mask.rows->data; + + cells.get_seq_cells(get_kv_rows_slices(*ubatch, n_slices, n_swa, swa_type), data, n_rows); ++ skippy_trace_kv_rows(data, n_rows, n_slices); + } + + // the mask is left unallocated when the graph only stores K/V without attending +diff --git a/src/skippy/kv_rows_trace.cpp b/src/skippy/kv_rows_trace.cpp +new file mode 100644 +index 000000000..e5f06b614 +--- /dev/null ++++ b/src/skippy/kv_rows_trace.cpp +@@ -0,0 +1,41 @@ ++#include "skippy/kv_rows_trace.h" ++ ++#include "skippy/trace_scope.h" ++ ++#include ++#include ++#include ++ ++// The span's value is the most contiguous cell runs one list holds, and its ++// detail gives cells:runs per slice, so a trace shows how fragmented the ++// unified pool is for each query slice. -1 entries are padding, between runs ++// and after the last. ++void skippy_trace_kv_rows(const int32_t * data, int64_t n_per_slice, int64_t n_slices) { ++ if (!skippy_trace::active()) { ++ return; ++ } ++ thread_local std::string detail; ++ detail.clear(); ++ int64_t max_runs = 0; ++ for (int64_t s = 0; s < n_slices; ++s) { ++ const int32_t * begin = data + s * n_per_slice; ++ const int32_t * end = begin + n_per_slice; ++ int64_t cells = 0; ++ int64_t runs = 0; ++ int32_t previous = -2; ++ std::for_each(begin, end, [&](int32_t cell) { ++ if (cell < 0) { ++ return; ++ } ++ runs += cell != previous + 1; ++ ++cells; ++ previous = cell; ++ }); ++ max_runs = std::max(max_runs, runs); ++ char item[48]; ++ std::snprintf(item, sizeof(item), "%s%lld:%lld", s ? " " : "", (long long) cells, (long long) runs); ++ detail += item; ++ } ++ skippy_trace::scope trace("llama.kv_rows", "runs", max_runs); ++ trace.set_detail(detail.c_str()); ++} +diff --git a/src/skippy/kv_rows_trace.h b/src/skippy/kv_rows_trace.h +new file mode 100644 +index 000000000..537a4f4cd +--- /dev/null ++++ b/src/skippy/kv_rows_trace.h +@@ -0,0 +1,7 @@ ++#pragma once ++ ++#include ++ ++// Reports one llama.kv_rows span for the row lists a ubatch attends through: ++// `n_slices` lists of `n_per_slice` cell indices each, -1 where padded. ++void skippy_trace_kv_rows(const int32_t * data, int64_t n_per_slice, int64_t n_slices); +diff --git a/src/skippy/trace_scope.h b/src/skippy/trace_scope.h +index b64d9da37..6e6641571 100644 +--- a/src/skippy/trace_scope.h ++++ b/src/skippy/trace_scope.h +@@ -44,6 +44,9 @@ class scope { + // trace tag; 0 when there is neither. + uint64_t current_parent() noexcept; + ++// Whether a span callback is installed, for work done only to describe a span. ++bool active() noexcept; ++ + // While it lives, spans this thread begins nest under `parent`, so work done + // on another thread's behalf joins that thread's trace. + class adopt { +diff --git a/src/skippy/tracing.cpp b/src/skippy/tracing.cpp +index 9aa48e08c..29e9047b1 100644 +--- a/src/skippy/tracing.cpp ++++ b/src/skippy/tracing.cpp +@@ -199,6 +199,10 @@ uint64_t current_parent() noexcept { + return t_current != 0 ? t_current : t_tag; + } + ++bool active() noexcept { ++ return g_span_callback.load(std::memory_order_relaxed) != nullptr; ++} ++ + adopt::adopt(uint64_t parent) noexcept : previous_(t_current) { + if (parent != 0) { + t_current = parent; +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0022-ggml-metal-read-consecutive-row-list-blocks-like-den.patch b/skippy/llama_cpp/patches/0022-ggml-metal-read-consecutive-row-list-blocks-like-den.patch new file mode 100644 index 0000000000..749aacdd21 --- /dev/null +++ b/skippy/llama_cpp/patches/0022-ggml-metal-read-consecutive-row-list-blocks-like-den.patch @@ -0,0 +1,112 @@ +From ab4663bec3a9a8b26539ae83fd67201d8389a7b9 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sat, 7 Nov 2026 21:19:15 +1100 +Subject: [PATCH 22/32] ggml-metal: read consecutive row-list blocks like dense + attention + +The flash-attention vec kernel serves K/V row lists through the sparse +path: one dependent load per row behind an index. A block whose 32 indices +are consecutive now takes the dense path from its first row, so a shared +prefix and any contiguous run stream at dense speed; only a block with +gaps or padding gathers row by row. + +The row lists are strictly ascending, so a 32-row block is consecutive +exactly when its first and last entries are 31 apart. Two uniform loads +decide it, with no index staging, simdgroup barrier or vote; only a +gathered block stages its indices. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + .../ggml-metal/kernels/fa_vec_common.metal | 33 ++++++++++++++----- + 1 file changed, 24 insertions(+), 9 deletions(-) + +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index c81e4d09b..965216ae7 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -230,8 +230,23 @@ kernel void kernel_flash_attn_ext_vec( + ic = 0; + } + +- // load the KV row indices for the current block into shared memory +- if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { ++ // a block whose row list is consecutive reads K/V like the dense path, from its first row; ++ // only a block with gaps or padding gathers row by row. the lists are strictly ascending ++ // (llama_kv_cells::get_seq_cells), so a block is consecutive iff its ends are C-1 apart: ++ // two uniform loads decide it, without staging the indices ++ int rows_base = -1; ++ if (FC_flash_attn_ext_vec_has_rows) { ++ const int first = rows_list[ic]; ++ const int last = rows_list[ic + C - 1]; ++ ++ rows_base = (first >= 0 && last == first + C - 1) ? first : -1; ++ } ++ ++ const bool gather = FC_flash_attn_ext_vec_has_sparse || (FC_flash_attn_ext_vec_has_rows && rows_base < 0); ++ const int icr = rows_base >= 0 ? rows_base : ic; ++ ++ // load the KV row indices of a gathered block into shared memory ++ if (gather) { + FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { + const short i = ii*NW + tiisg; + +@@ -293,8 +308,8 @@ kernel void kernel_flash_attn_ext_vec( + { + device const k4_t * pk4 = nullptr; + +- if (!FC_flash_attn_ext_vec_has_sparse && !FC_flash_attn_ext_vec_has_rows) { +- pk4 = (device const k4_t *) (k + ic*args.nb11); ++ if (!gather) { ++ pk4 = (device const k4_t *) (k + icr*args.nb11); + + pk4 += ty*NS10/4 + tx; + } +@@ -308,7 +323,7 @@ kernel void kernel_flash_attn_ext_vec( + + // each simdgroup processes Q queries and NE (NW/NL) cache elements + FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { +- if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { ++ if (gather) { + // the KV rows are gathered from the index list; -1 entries are padding + const int i11 = spidx[NE*cc + ty]; + if (i11 >= 0) { +@@ -344,7 +359,7 @@ kernel void kernel_flash_attn_ext_vec( + } + } + } else { +- device const kd4_t * pk = (device const kd4_t *) (k + ((ic + NE*cc + ty)*args.nb11)); ++ device const kd4_t * pk = (device const kd4_t *) (k + ((icr + NE*cc + ty)*args.nb11)); + + k4_t mk; + +@@ -451,7 +466,7 @@ kernel void kernel_flash_attn_ext_vec( + } + } + +- if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { ++ if (gather) { + FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { + // the KV rows are gathered from the index list; -1 entries are padding + const int i11 = spidx[NE*cc + ty]; +@@ -485,7 +500,7 @@ kernel void kernel_flash_attn_ext_vec( + } + } + } else if (is_same::value) { +- device const v4_t * pv4 = (device const v4_t *) (v + ic*args.nb21); ++ device const v4_t * pv4 = (device const v4_t *) (v + icr*args.nb21); + + pv4 += ty*NS20/4 + tx; + +@@ -499,7 +514,7 @@ kernel void kernel_flash_attn_ext_vec( + } + } else { + FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { +- device const vd4_t * pv4 = (device const vd4_t *) (v + ((ic + NE*cc + ty)*args.nb21)); ++ device const vd4_t * pv4 = (device const vd4_t *) (v + ((icr + NE*cc + ty)*args.nb21)); + + FOR_UNROLL (short ii = 0; ii < DV4/NL; ++ii) { + const short i = ii*NL + tx; +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0023-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch b/skippy/llama_cpp/patches/0023-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch new file mode 100644 index 0000000000..fe9dec31e1 --- /dev/null +++ b/skippy/llama_cpp/patches/0023-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch @@ -0,0 +1,193 @@ +From 3c84df55abd0cd603cb6591a13904ba5b2d0f2c3 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sat, 7 Nov 2026 21:27:50 +1100 +Subject: [PATCH 23/32] llama: keep a sequence's unified-pool cells in chunks + +The unified pool placed a ubatch's tokens in consecutive cells, so at four +concurrent requests each sequence's decode cells sat at stride four and its +row list held one run per token. A token now goes to the cell after its +sequence's highest one while that stays inside the same 64-cell chunk and +free, else to the first cell of a fresh all-empty chunk; a pool too +fragmented for a fresh chunk falls back to any empty cell. Row lists hold +long runs the row-attention kernels read at dense speed. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + src/llama-kv-cache.cpp | 84 ++++++++++++++++++++++++++++++++++++++++++ + src/llama-kv-cache.h | 7 ++++ + src/llama-kv-cells.h | 24 ++++++++++++ + 3 files changed, 115 insertions(+) + +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index d00c1fe4a..a2d3418e9 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -9,6 +9,7 @@ + #include "skippy.h" + + #include ++#include + #include + #include + #include +@@ -1045,6 +1046,81 @@ bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_co + return updated; + } + ++// Unified pool placement that keeps each sequence's cells together: a token ++// goes to the cell after its sequence's highest one while that stays inside the ++// same chunk and free, else to the first cell of a fresh all-empty chunk. Row ++// lists then hold long runs instead of one cell per decode step, which is what ++// the row-attention kernels read at dense speed. A pool too fragmented for a ++// fresh chunk falls back to any empty cell. ++std::vector llama_kv_cache::find_chunked_cells( ++ const llama_ubatch & ubatch, const llama_kv_cells & cells, uint32_t head_cur) const { ++ const uint32_t n_tokens = ubatch.n_tokens; ++ const uint32_t n_cells = cells.size(); ++ const uint32_t n_chunks = n_cells / kv_chunk_cells; ++ ++ std::vector idxs; ++ idxs.reserve(n_tokens); ++ ++ std::vector taken(n_cells, 0); ++ const auto free_cell = [&](uint32_t idx) { return cells.is_empty(idx) && !taken[idx]; }; ++ const auto take = [&](uint32_t idx) { taken[idx] = 1; idxs.push_back(idx); }; ++ ++ // next cell of each sequence's open chunk, resolved on first use ++ std::array next; ++ next.fill(-2); ++ ++ uint32_t chunk_cur = n_chunks ? (head_cur / kv_chunk_cells) % n_chunks : 0; ++ ++ for (uint32_t i = 0; i < n_tokens; ++i) { ++ const llama_seq_id seq_id = ubatch.n_seq_id[i] > 0 ? ubatch.seq_id[i][0] : 0; ++ ++ if (next[seq_id] == -2) { ++ const int64_t last = cells.seq_cell_max(seq_id); ++ next[seq_id] = last >= 0 && (last + 1) % kv_chunk_cells != 0 ? last + 1 : -1; ++ } ++ ++ const int64_t cand = next[seq_id]; ++ if (cand >= 0 && cand < (int64_t) n_cells && free_cell((uint32_t) cand)) { ++ take((uint32_t) cand); ++ next[seq_id] = (cand + 1) % kv_chunk_cells != 0 ? cand + 1 : -1; ++ continue; ++ } ++ ++ // a fresh chunk: every cell empty and unclaimed, searched from the head onward ++ bool placed = false; ++ for (uint32_t tested = 0; tested < n_chunks && !placed; ++tested) { ++ const uint32_t start = chunk_cur * kv_chunk_cells; ++ chunk_cur = (chunk_cur + 1) % n_chunks; ++ bool empty = true; ++ for (uint32_t c = start; c < start + kv_chunk_cells && empty; ++c) { ++ empty = free_cell(c); ++ } ++ if (empty) { ++ take(start); ++ next[seq_id] = kv_chunk_cells > 1 ? start + 1 : -1; ++ placed = true; ++ } ++ } ++ if (placed) { ++ continue; ++ } ++ ++ // the pool is fragmented: any empty cell keeps the batch going ++ for (uint32_t tested = 0; tested < n_cells && !placed; ++tested) { ++ const uint32_t idx = (head_cur + tested) % n_cells; ++ if (free_cell(idx)) { ++ take(idx); ++ placed = true; ++ } ++ } ++ if (!placed) { ++ return { }; ++ } ++ } ++ ++ return idxs; ++} ++ + llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, bool cont) const { + + if (debug > 0) { +@@ -1194,6 +1270,14 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, + head_cur = 0; + } + ++ if (n_stream == 1 && n_swa == 0) { ++ res.idxs[s] = find_chunked_cells(ubatch, cells, head_cur); ++ if (res.idxs[s].size() < n_tokens) { ++ return { }; ++ } ++ continue; ++ } ++ + uint32_t n_tested = 0; + + // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index 874c3739d..fd3054514 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -272,6 +272,13 @@ public: + // return empty slot_info on failure + slot_info find_slot(const llama_ubatch & ubatch, bool cont) const; + ++ // cells a sequence claims at a time in the unified pool; a multiple of the ++ // row-attention kernels' 32-row block ++ static constexpr uint32_t kv_chunk_cells = 64; ++ ++ std::vector find_chunked_cells( ++ const llama_ubatch & ubatch, const llama_kv_cells & cells, uint32_t head_cur) const; ++ + // emplace the ubatch context into slot: [sinfo.idxs[0...ubatch.n_tokens - 1]] + void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch); + +diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h +index 4b50afe71..9190ad55f 100644 +--- a/src/llama-kv-cells.h ++++ b/src/llama-kv-cells.h +@@ -34,6 +34,17 @@ static inline int ctz64(uint64_t x) { + #endif + } + ++// Index of the highest set bit; called for x != 0. ++static inline int fls64(uint64_t x) { ++#if defined(_MSC_VER) ++ unsigned long i; ++ _BitScanReverse64(&i, x); ++ return (int) i; ++#else ++ return 63 - __builtin_clzll(x); ++#endif ++} ++ + struct llama_kv_cell_ext { + // 2D spatial positions, typically used for M-RoPE + llama_pos x = 0; +@@ -514,6 +525,19 @@ public: + positions.size() == static_cast(pos_max) + 1; + } + ++ // The highest cell the sequence occupies, or -1. ++ int64_t seq_cell_max(llama_seq_id seq_id) const { ++ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); ++ const auto & bits = seq_bits[seq_id]; ++ const uint32_t n_words = std::min((used_max_p1() + 63) / 64, bits.size()); ++ for (uint32_t w = n_words; w-- > 0;) { ++ if (bits[w] != 0) { ++ return 64 * w + fls64(bits[w]); ++ } ++ } ++ return -1; ++ } ++ + // note: call only if the cell is not empty + llama_pos pos_get(uint32_t i) const { + assert(i < pos.size()); +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0024-ggml-metal-compile-a-gather-free-row-list-attention-.patch b/skippy/llama_cpp/patches/0024-ggml-metal-compile-a-gather-free-row-list-attention-.patch new file mode 100644 index 0000000000..c980d5191a --- /dev/null +++ b/skippy/llama_cpp/patches/0024-ggml-metal-compile-a-gather-free-row-list-attention-.patch @@ -0,0 +1,162 @@ +From cfea699fd49ce5579cbdb5c226a66279e10f61ba Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 10:55:48 +1100 +Subject: [PATCH 24/32] ggml-metal: compile a gather-free row-list attention + variant + +When every block of every row list is consecutive or padding, the +host picks a vec pipeline whose gather code is compiled out +(FC_flash_attn_ext_vec_rows_dense): one uniform load per block gives +the base row and the K/V loads are the dense path's. The lists are +host-visible inputs, so the check is a scan of the block ends. + +Every Metal buffer type reports is_host false, so the host asks the +buffer's own is_shared whether it may read the lists. + +Co-Authored-By: Claude Opus 5.5 +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/src/ggml-metal/ggml-metal-device.cpp | 5 +++- + ggml/src/ggml-metal/ggml-metal-device.h | 1 + + ggml/src/ggml-metal/ggml-metal-ops.cpp | 23 +++++++++++++++++-- + .../ggml-metal/kernels/fa_vec_common.metal | 16 +++++++++---- + 4 files changed, 38 insertions(+), 7 deletions(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index 0d18a5f01..17be454a5 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -2037,6 +2037,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + bool has_kvpad, + bool has_sparse, + bool has_rows, ++ bool rows_dense, + int32_t nqpsg, + int32_t ne, + int32_t nsg, +@@ -2066,7 +2067,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + dv, + qne_suffix); + +- snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", ++ snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_rowsd=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", + base, + has_mask, + has_sinks, +@@ -2075,6 +2076,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + has_kvpad, + has_sparse, + has_rows, ++ rows_dense, + ns10, + ns20, + nsg, nwg); +@@ -2090,6 +2092,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v + ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); + ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); + ggml_metal_cv_set_bool(cv, has_rows, FC_FLASH_ATTN_EXT_VEC + 6); ++ ggml_metal_cv_set_bool(cv, rows_dense, FC_FLASH_ATTN_EXT_VEC + 7); + + ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); + ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); +diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h +index 56b795790..7b66c9560 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.h ++++ b/ggml/src/ggml-metal/ggml-metal-device.h +@@ -238,6 +238,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att + bool has_kvpad, + bool has_sparse, + bool has_rows, ++ bool rows_dense, + int32_t nqpsg, + int32_t ne, + int32_t nsg, +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index 3d317a0a6..4173d7b1b 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -3605,6 +3605,25 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_NCPSG == 0); + GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); + ++ // the vec kernel compiles without gather code when every block of every list is either ++ // consecutive or padding; the lists are strictly ascending per slice and readable from the ++ // host whenever their Metal buffer is shared or mapped (every buffer type but private) ++ const bool rows_dense = has_rows && ++ ggml_metal_buffer_is_shared((ggml_metal_buffer_t) (kv_rows->view_src ? kv_rows->view_src->buffer : kv_rows->buffer)->context) && ++ [&] { ++ constexpr int64_t C = OP_FLASH_ATTN_EXT_VEC_NCPSG; ++ const int32_t * lists = (const int32_t *) kv_rows->data; ++ const int64_t n_blocks = (ne11_attn/C)*kv_rows->ne[1]; ++ for (int64_t b = 0; b < n_blocks; ++b) { ++ const int32_t first = lists[b*C]; ++ const int32_t last = lists[b*C + C - 1]; ++ if (first >= 0 && last != first + C - 1) { ++ return false; ++ } ++ } ++ return true; ++ }(); ++ + float scale; + float max_bias; + float logit_softcap; +@@ -4202,7 +4221,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + + auto fa_vec_smem = [&](int64_t nsg, int32_t nqptg) -> size_t { + const size_t smem_half = (size_t) (dk_pad + 4*ncpsg + 2*dv_pad)*nqptg*nsg; +- return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + ((use_sparse || has_rows) ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); ++ return GGML_PAD(smem_half*sizeof(ggml_fp16_t) + ((use_sparse || (has_rows && !rows_dense)) ? (size_t) nsg*ncpsg*sizeof(int) : 0), 16); + }; + + int64_t nsg = 1; +@@ -4283,7 +4302,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + /*.n_kv_max_padded =*/ n_kv_max_padded, + }; + +- auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); ++ auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, rows_dense, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); + + GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); + +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index 965216ae7..2dd6e4bef 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -14,6 +14,8 @@ constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EX + constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; + constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; + constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; ++// every block of every row list is consecutive or padding: no gather code is compiled in ++constant bool FC_flash_attn_ext_vec_rows_dense [[function_constant(FC_FLASH_ATTN_EXT_VEC + 7)]]; + template< + typename q4_t, // query types in shared memory + typename k4_t, // key types in shared memory +@@ -236,13 +238,19 @@ kernel void kernel_flash_attn_ext_vec( + // two uniform loads decide it, without staging the indices + int rows_base = -1; + if (FC_flash_attn_ext_vec_has_rows) { +- const int first = rows_list[ic]; +- const int last = rows_list[ic + C - 1]; ++ if (FC_flash_attn_ext_vec_rows_dense) { ++ // a padding block reads masked rows from the list position, like the dense path ++ rows_base = rows_list[ic]; ++ } else { ++ const int first = rows_list[ic]; ++ const int last = rows_list[ic + C - 1]; + +- rows_base = (first >= 0 && last == first + C - 1) ? first : -1; ++ rows_base = (first >= 0 && last == first + C - 1) ? first : -1; ++ } + } + +- const bool gather = FC_flash_attn_ext_vec_has_sparse || (FC_flash_attn_ext_vec_has_rows && rows_base < 0); ++ const bool gather = FC_flash_attn_ext_vec_has_sparse || ++ (FC_flash_attn_ext_vec_has_rows && !FC_flash_attn_ext_vec_rows_dense && rows_base < 0); + const int icr = rows_base >= 0 ? rows_base : ic; + + // load the KV row indices of a gathered block into shared memory +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0025-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch b/skippy/llama_cpp/patches/0025-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch new file mode 100644 index 0000000000..03c0212054 --- /dev/null +++ b/skippy/llama_cpp/patches/0025-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch @@ -0,0 +1,35 @@ +From 7097eea146967c70bcd88ba92487acd0294af3bb Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 11:03:23 +1100 +Subject: [PATCH 25/32] ggml-metal: let GGML_METAL_CAPTURE_DIR choose where a + capture is written + +A capture embeds every buffer the graph references, weights included, +so a 30B model's trace is tens of GB; /tmp is not always the disk with +that much room. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/src/ggml-metal/ggml-metal-context.m | 5 ++++- + 1 file changed, 4 insertions(+), 1 deletion(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-context.m b/ggml/src/ggml-metal/ggml-metal-context.m +index f89c8ebe6..063d458a8 100644 +--- a/ggml/src/ggml-metal/ggml-metal-context.m ++++ b/ggml/src/ggml-metal/ggml-metal-context.m +@@ -642,7 +642,10 @@ enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * + } + + if (!ctx->capture_started) { +- NSString * path = [NSString stringWithFormat:@"/tmp/perf-metal-%d.gputrace", getpid()]; ++ // GGML_METAL_CAPTURE_DIR picks the directory: a capture embeds every buffer the ++ // graph touches, weights included, so it may need more space than /tmp offers ++ const char * dir = getenv("GGML_METAL_CAPTURE_DIR"); ++ NSString * path = [NSString stringWithFormat:@"%s/perf-metal-%d.gputrace", dir && *dir ? dir : "/tmp", getpid()]; + + GGML_LOG_WARN("%s: capturing graph in %s\n", __func__, [path UTF8String]); + +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0026-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch b/skippy/llama_cpp/patches/0026-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch new file mode 100644 index 0000000000..e70d440468 --- /dev/null +++ b/skippy/llama_cpp/patches/0026-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch @@ -0,0 +1,336 @@ +From 2a0b0f5f7845449653c4251f1a2e72e794e4fded Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 11:52:39 +1100 +Subject: [PATCH 26/32] tests: per-call cost of ordinary vs row-list decode + attention + +test-flash-attn-rows-perf chains attention nodes the way a model's +layers run them and reads the backend's command timing, so one number +per call compares the ordinary kernel with row lists laid out as the +unified pool lays them out: one run, 64-cell chunks, one run per row, +and a padded tail. Small enough for the full Metal profiler. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + tests/CMakeLists.txt | 2 + + tests/test-flash-attn-rows-perf.cpp | 294 ++++++++++++++++++++++++++++ + 2 files changed, 296 insertions(+) + create mode 100644 tests/test-flash-attn-rows-perf.cpp + +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index 638e84e37..bcb407ae8 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -392,6 +392,8 @@ endif() + llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) + + llama_build_and_test(test-backend-tensor.cpp LINK ggml) ++# per-call cost of ordinary vs row-list decode attention; a tool, not a test ++llama_build(test-flash-attn-rows-perf.cpp LINK ggml) + + llama_build_and_test(test-tiled-mulmat.cpp LABEL "main behavior backend" LINK ggml) + llama_build_and_test(test-model-load-cancel.cpp LABEL "model behavior") +diff --git a/tests/test-flash-attn-rows-perf.cpp b/tests/test-flash-attn-rows-perf.cpp +new file mode 100644 +index 000000000..dbffc27e4 +--- /dev/null ++++ b/tests/test-flash-attn-rows-perf.cpp +@@ -0,0 +1,294 @@ ++// Per-call cost of decode attention over the KV cache: the ordinary kernel ++// against ggml_flash_attn_ext_rows with the row-list shapes the unified pool ++// produces. One graph chains `depth` attention nodes (each query is the ++// previous output, so they run back to back like a model's layers) and the ++// backend's command timing gives the GPU time of the whole chain. ++// ++// test-flash-attn-rows-perf [--backend NAME] [--iters N] [--depth N] ++// ++// GGML_METAL_CAPTURE_COMPUTE=N (with METAL_CAPTURE_ENABLED=1) captures one ++// chain for Xcode; a chain is small enough for the full Metal profiler. ++#include "ggml.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++ ++// Qwen3-Coder-30B-A3B: 32 query heads over 4 K/V heads, 128-wide, F16 cache ++constexpr int64_t dk = 128; ++constexpr int64_t dv = 128; ++constexpr int64_t heads = 32; ++constexpr int64_t kv_heads = 4; ++constexpr int64_t mask_queries = 64; ++constexpr int64_t slack = 256; ++ ++enum class layout { dense, identity, chunk64, stride, padded }; ++ ++const char * layout_name(layout value) { ++ switch (value) { ++ case layout::dense: return "dense"; ++ case layout::identity: return "rows:identity"; ++ case layout::chunk64: return "rows:chunk64"; ++ case layout::stride: return "rows:stride"; ++ case layout::padded: return "rows:padded"; ++ } ++ return "?"; ++} ++ ++void require(bool condition, const char * message) { ++ if (!condition) { ++ throw std::runtime_error(message); ++ } ++} ++ ++// the cell of list position `i` of slice `s` ++int32_t cell_of(layout value, int64_t rows, int64_t slices, int64_t s, int64_t i) { ++ switch (value) { ++ case layout::identity: return int32_t(s*rows + i); ++ case layout::padded: return i < rows - 128 ? int32_t(s*rows + i) : -1; ++ case layout::stride: return int32_t(i*slices + s); ++ case layout::chunk64: return int32_t((i/64)*(64*slices) + s*64 + i%64); ++ case layout::dense: break; ++ } ++ return -1; ++} ++ ++struct timing_sink { ++ std::atomic gpu_ns{0}; ++ std::atomic commands{0}; ++ ++ static void record(const ggml_backend_command_timing * timing, void * user_data) { ++ auto & sink = *static_cast(user_data); ++ if (timing->status == 0 && timing->execute_end_unix_ns > timing->execute_start_unix_ns) { ++ sink.gpu_ns += timing->execute_end_unix_ns - timing->execute_start_unix_ns; ++ } ++ ++sink.commands; ++ } ++ ++ void reset() { ++ gpu_ns = 0; ++ commands = 0; ++ } ++}; ++ ++struct chain { ++ ggml_context * ctx = nullptr; ++ ggml_backend_buffer_t buffer = nullptr; ++ ggml_tensor * q = nullptr; ++ ggml_tensor * k = nullptr; ++ ggml_tensor * v = nullptr; ++ ggml_tensor * mask = nullptr; ++ ggml_tensor * rows = nullptr; ++ ggml_tensor * last = nullptr; ++ ggml_cgraph * graph = nullptr; ++ ++ chain(ggml_backend_t backend, layout value, int64_t rows_per_slice, int64_t slices, int depth) { ++ const bool row_based = value != layout::dense; ++ ggml_init_params params{(size_t) (8 + 2*depth)*ggml_tensor_overhead() + ggml_graph_overhead_custom(2*depth + 8, false), nullptr, true}; ++ ctx = ggml_init(params); ++ require(ctx != nullptr, "allocate graph context"); ++ ++ q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, dk, 1, heads, slices); ++ const int64_t pool = row_based ? rows_per_slice*slices + slack : rows_per_slice; ++ k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, dk, pool, kv_heads, row_based ? 1 : slices); ++ v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, dv, pool, kv_heads, row_based ? 1 : slices); ++ mask = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, rows_per_slice, mask_queries, 1, slices); ++ if (row_based) { ++ rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, rows_per_slice, slices); ++ } ++ ggml_set_input(q); ++ ggml_set_input(k); ++ ggml_set_input(v); ++ ggml_set_input(mask); ++ if (rows) { ++ ggml_set_input(rows); ++ } ++ ++ ggml_tensor * cur = q; ++ for (int i = 0; i < depth; ++i) { ++ ggml_tensor * out = row_based ++ ? ggml_flash_attn_ext_rows(ctx, cur, k, v, mask, rows, 1.0f/std::sqrt(float(dk)), 0.0f, 0.0f) ++ : ggml_flash_attn_ext(ctx, cur, k, v, mask, 1.0f/std::sqrt(float(dk)), 0.0f, 0.0f); ++ ggml_prec_set_acc(out, GGML_PREC_F32); ++ require(ggml_backend_supports_op(backend, out), "backend does not support this attention shape"); ++ last = out; ++ // [dv, heads, 1, slices] -> [dv, 1, heads, slices]: the next query, as a view ++ cur = ggml_permute(ctx, out, 0, 2, 1, 3); ++ } ++ ggml_set_output(last); ++ graph = ggml_new_graph_custom(ctx, 2*depth + 8, false); ++ ggml_build_forward_expand(graph, last); ++ buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); ++ require(buffer != nullptr, "allocate backend tensors"); ++ } ++ ++ ~chain() { ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++ } ++ chain(const chain &) = delete; ++ chain & operator=(const chain &) = delete; ++ ++ void fill(layout value, int64_t rows_per_slice, int64_t slices) { ++ std::mt19937 random(34791); ++ std::uniform_real_distribution sample(-0.75f, 0.75f); ++ ++ std::vector qf(ggml_nelements(q)); ++ std::generate(qf.begin(), qf.end(), [&] { return sample(random); }); ++ ggml_backend_tensor_set(q, qf.data(), 0, ggml_nbytes(q)); ++ ++ std::vector kv(ggml_nelements(k)); ++ std::generate(kv.begin(), kv.end(), [&] { return ggml_fp32_to_fp16(sample(random)); }); ++ ggml_backend_tensor_set(k, kv.data(), 0, ggml_nbytes(k)); ++ std::generate(kv.begin(), kv.end(), [&] { return ggml_fp32_to_fp16(sample(random)); }); ++ ggml_backend_tensor_set(v, kv.data(), 0, ggml_nbytes(v)); ++ ++ std::vector list; ++ if (rows) { ++ list.resize(rows_per_slice*slices); ++ for (int64_t s = 0; s < slices; ++s) { ++ for (int64_t i = 0; i < rows_per_slice; ++i) { ++ list[s*rows_per_slice + i] = cell_of(value, rows_per_slice, slices, s, i); ++ } ++ } ++ ggml_backend_tensor_set(rows, list.data(), 0, ggml_nbytes(rows)); ++ } ++ ++ // visible rows score 0, padding -inf; the dense case has no padding ++ std::vector m(ggml_nelements(mask)); ++ const ggml_fp16_t zero = ggml_fp32_to_fp16(0.0f); ++ const ggml_fp16_t ninf = ggml_fp32_to_fp16(-std::numeric_limits::infinity()); ++ for (int64_t s = 0; s < slices; ++s) { ++ for (int64_t query = 0; query < mask_queries; ++query) { ++ for (int64_t i = 0; i < rows_per_slice; ++i) { ++ const bool visible = !rows || list[s*rows_per_slice + i] >= 0; ++ m[(s*mask_queries + query)*rows_per_slice + i] = visible ? zero : ninf; ++ } ++ } ++ } ++ ggml_backend_tensor_set(mask, m.data(), 0, ggml_nbytes(mask)); ++ } ++ ++ float checksum() const { ++ std::vector out(ggml_nelements(last)); ++ ggml_backend_tensor_get(last, out.data(), 0, ggml_nbytes(last)); ++ return std::accumulate(out.begin(), out.end(), 0.0f, [](float a, float b) { return a + std::fabs(b); }); ++ } ++}; ++ ++ggml_backend_t open_backend(const char * name) { ++ for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { ++ ggml_backend_dev_t device = ggml_backend_dev_get(i); ++ if (std::strcmp(ggml_backend_dev_name(device), name) == 0) { ++ return ggml_backend_dev_init(device, nullptr); ++ } ++ } ++ return nullptr; ++} ++ ++struct result { ++ layout value; ++ int64_t rows; ++ int64_t slices; ++ double gpu_us; // per attention call, device time ++ double wall_us; // per attention call, host wall time of the compute ++ double commands; // command buffers per chain ++ float checksum; ++}; ++ ++result measure(ggml_backend_t backend, timing_sink & sink, layout value, int64_t rows, int64_t slices, int depth, int iters) { ++ chain c(backend, value, rows, slices, depth); ++ c.fill(value, rows, slices); ++ for (int i = 0; i < 5; ++i) { ++ require(ggml_backend_graph_compute(backend, c.graph) == GGML_STATUS_SUCCESS, "warm-up compute"); ++ } ++ ggml_backend_synchronize(backend); ++ std::this_thread::sleep_for(std::chrono::milliseconds(20)); ++ sink.reset(); ++ const auto t0 = std::chrono::steady_clock::now(); ++ for (int i = 0; i < iters; ++i) { ++ require(ggml_backend_graph_compute(backend, c.graph) == GGML_STATUS_SUCCESS, "timed compute"); ++ } ++ ggml_backend_synchronize(backend); ++ const auto t1 = std::chrono::steady_clock::now(); ++ // the completion handlers run on a backend thread after the wait returns ++ std::this_thread::sleep_for(std::chrono::milliseconds(50)); ++ const double calls = double(iters)*depth; ++ return { ++ value, rows, slices, ++ double(sink.gpu_ns.load())/1e3/calls, ++ std::chrono::duration(t1 - t0).count()/calls, ++ double(sink.commands.load())/iters, ++ c.checksum(), ++ }; ++} ++ ++} // namespace ++ ++int main(int argc, char ** argv) { ++ try { ++ const char * backend_name = nullptr; ++ int iters = 50; ++ int depth = 48; ++ for (int i = 1; i < argc; ++i) { ++ if (std::strcmp(argv[i], "--backend") == 0 && i + 1 < argc) { ++ backend_name = argv[++i]; ++ } else if (std::strcmp(argv[i], "--iters") == 0 && i + 1 < argc) { ++ iters = std::stoi(argv[++i]); ++ } else if (std::strcmp(argv[i], "--depth") == 0 && i + 1 < argc) { ++ depth = std::stoi(argv[++i]); ++ } else { ++ require(false, "usage: test-flash-attn-rows-perf [--backend NAME] [--iters N] [--depth N]"); ++ } ++ } ++ ggml_backend_load_all(); ++ using backend_ptr = std::unique_ptr; ++ backend_ptr backend(backend_name ? open_backend(backend_name) ++ : ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr), ggml_backend_free); ++ require(backend != nullptr, "backend unavailable"); ++ ++ timing_sink sink; ++ const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get())); ++ auto set_callback = (ggml_backend_set_command_timing_callback_t) ++ ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_command_timing_callback"); ++ require(set_callback != nullptr, "backend reports no command timing; GPU time needs the Metal timing patch"); ++ set_callback(timing_sink::record, &sink); ++ ++ std::printf("backend=%s dk=%lld dv=%lld heads=%lld kv_heads=%lld depth=%d iters=%d\n", ++ ggml_backend_name(backend.get()), (long long) dk, (long long) dv, (long long) heads, ++ (long long) kv_heads, depth, iters); ++ std::printf("%-14s %6s %6s %12s %12s %8s %12s\n", "layout", "rows", "slices", "gpu_us/call", "wall_us/call", "cmd/chain", "checksum"); ++ for (int64_t slices : {1, 4}) { ++ for (int64_t rows : {768, 4864}) { ++ for (layout value : {layout::dense, layout::identity, layout::chunk64, layout::stride, layout::padded}) { ++ if (slices == 1 && (value == layout::chunk64 || value == layout::stride)) { ++ continue; // identical to identity with one slice ++ } ++ const result r = measure(backend.get(), sink, value, rows, slices, depth, iters); ++ std::printf("%-14s %6lld %6lld %12.2f %12.2f %8.1f %12.4g\n", layout_name(r.value), ++ (long long) r.rows, (long long) r.slices, r.gpu_us, r.wall_us, r.commands, r.checksum); ++ } ++ } ++ } ++ set_callback(nullptr, nullptr); ++ return 0; ++ } catch (const std::exception & error) { ++ std::fprintf(stderr, "test-flash-attn-rows-perf: %s\n", error.what()); ++ return 1; ++ } ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0027-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch b/skippy/llama_cpp/patches/0027-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch new file mode 100644 index 0000000000..073c3559c2 --- /dev/null +++ b/skippy/llama_cpp/patches/0027-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch @@ -0,0 +1,433 @@ +From caee87540aeafa8cbb374efd57847e0e425dec01 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 12:17:27 +1100 +Subject: [PATCH 27/32] llama, ggml-metal: start every row-list run on an + attention block + +A slice's cell list now pads with -1 before a run that does not continue +the previous cell, so each run starts on a multiple of the kernels' 32-row +block; the list grows by the padding. The gather-free Metal variant then +applies to any list the chunked pool produces: a block is one consecutive +range (a run ending inside it reads on to the block's end under the mask, +so the host checks the read stays inside the cache) or all padding, which +the kernel skips. The perf tool gains the run-end and two-run layouts. + +The aligned lists are built beside llama.cpp's own: get_seq_cells_aligned +walks the same per-slice cell sets, including a slice over several +sequences. A pool so fragmented that an aligned list would be longer than +the cache keeps the plain list, which the general kernel gathers, so the +mask never grows past what llama.cpp already allows. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/src/ggml-metal/ggml-metal-ops.cpp | 22 +++- + .../ggml-metal/kernels/fa_vec_common.metal | 6 +- + src/llama-kv-cache.cpp | 23 +++- + src/llama-kv-cache.h | 3 + + src/llama-kv-cells.h | 95 ++++++++++++++++ + tests/CMakeLists.txt | 1 + + tests/test-flash-attn-rows-perf.cpp | 21 +++- + tests/test-skippy-kv-rows-aligned.cpp | 106 ++++++++++++++++++ + 8 files changed, 267 insertions(+), 10 deletions(-) + create mode 100644 tests/test-skippy-kv-rows-aligned.cpp + +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index 4173d7b1b..a18d41ad8 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -3605,19 +3605,29 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_NCPSG == 0); + GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); + +- // the vec kernel compiles without gather code when every block of every list is either +- // consecutive or padding; the lists are strictly ascending per slice and readable from the +- // host whenever their Metal buffer is shared or mapped (every buffer type but private) ++ // the vec kernel compiles without gather code when every block of every list is one ++ // consecutive range (possibly ending in padding) or all padding. a run ascends, so its ends ++ // decide; the lists are readable from the host whenever their Metal buffer is shared or ++ // mapped (every buffer type but private) + const bool rows_dense = has_rows && + ggml_metal_buffer_is_shared((ggml_metal_buffer_t) (kv_rows->view_src ? kv_rows->view_src->buffer : kv_rows->buffer)->context) && + [&] { + constexpr int64_t C = OP_FLASH_ATTN_EXT_VEC_NCPSG; + const int32_t * lists = (const int32_t *) kv_rows->data; + const int64_t n_blocks = (ne11_attn/C)*kv_rows->ne[1]; ++ const int64_t n_cache_rows = op->src[1]->ne[1]; + for (int64_t b = 0; b < n_blocks; ++b) { +- const int32_t first = lists[b*C]; +- const int32_t last = lists[b*C + C - 1]; +- if (first >= 0 && last != first + C - 1) { ++ const int32_t * block = lists + b*C; ++ const int32_t first = block[0]; ++ if (first < 0 || block[C - 1] == first + C - 1) { ++ continue; // all padding (the kernel skips it), or one consecutive range ++ } ++ // a run ending inside the block: the kernel reads C rows from `first` and the mask ++ // drops the padded columns, so the read must stay inside the cache ++ const int32_t * tail = std::find(block, block + C, -1); ++ const int64_t live = tail - block; ++ if (tail == block + C || block[live - 1] != first + live - 1 || first + C > n_cache_rows || ++ std::any_of(tail, block + C, [](int32_t row) { return row >= 0; })) { + return false; + } + } +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index 2dd6e4bef..3876e9334 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -239,8 +239,12 @@ kernel void kernel_flash_attn_ext_vec( + int rows_base = -1; + if (FC_flash_attn_ext_vec_has_rows) { + if (FC_flash_attn_ext_vec_rows_dense) { +- // a padding block reads masked rows from the list position, like the dense path ++ // a block is one consecutive range from its first entry, or all padding; ++ // a range ending inside the block reads on to the block's end, masked + rows_base = rows_list[ic]; ++ if (rows_base < 0) { ++ continue; ++ } + } else { + const int first = rows_list[ic]; + const int last = rows_list[ic + C - 1]; +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index a2d3418e9..1ab98ee59 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -2696,6 +2696,22 @@ uint32_t llama_kv_cache::get_n_kv_rows(const llama_ubatch & ubatch) const { + + const auto slices = get_kv_rows_slices(ubatch, n_slices, n_swa, swa_type); + ++ // lists whose runs start on the attention kernels' block are longer by the padding between ++ // the runs; a pool too fragmented for them to fit the cache keeps the plain lists below ++ { ++ int64_t n_max_aligned = 0; ++ ++ for (uint32_t s = 0; s < n_slices; ++s) { ++ n_max_aligned = std::max(n_max_aligned, cells.seq_cells_aligned_len(slices[s], kv_rows_block)); ++ } ++ ++ const int64_t n_rows_aligned = std::max(n_pad_cur, GGML_PAD(n_max_aligned, (int64_t) n_pad_cur)); ++ ++ if (n_rows_aligned <= (int64_t) get_size()) { ++ return (uint32_t) n_rows_aligned; ++ } ++ } ++ + for (uint32_t s = 0; s < n_slices; ++s) { + // a cell shared by several sequences of the slice is counted once per sequence, an upper bound is enough + uint32_t n = 0; +@@ -3275,7 +3291,12 @@ void llama_kv_cache::set_input_attn_mask(const llm_attn_mask & attn_mask, const + const auto & cells = v_cells[0]; + int32_t * data = (int32_t *) attn_mask.rows->data; + +- cells.get_seq_cells(get_kv_rows_slices(*ubatch, n_slices, n_swa, swa_type), data, n_rows); ++ const auto slices = get_kv_rows_slices(*ubatch, n_slices, n_swa, swa_type); ++ ++ // the runs start on the attention kernels' block whenever get_n_kv_rows made room for that ++ if (!cells.get_seq_cells_aligned(slices, data, n_rows, kv_rows_block)) { ++ cells.get_seq_cells(slices, data, n_rows); ++ } + skippy_trace_kv_rows(data, n_rows, n_slices); + } + +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index fd3054514..2be616364 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -275,6 +275,9 @@ public: + // cells a sequence claims at a time in the unified pool; a multiple of the + // row-attention kernels' 32-row block + static constexpr uint32_t kv_chunk_cells = 64; ++ // the attention kernels walk a cell list in blocks of this many rows ++ // (OP_FLASH_ATTN_EXT_VEC_NCPSG); the runs of a list start on a block boundary ++ static constexpr uint32_t kv_rows_block = 32; + + std::vector find_chunked_cells( + const llama_ubatch & ubatch, const llama_kv_cells & cells, uint32_t head_cur) const; +diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h +index 9190ad55f..0e42a587a 100644 +--- a/src/llama-kv-cells.h ++++ b/src/llama-kv-cells.h +@@ -482,6 +482,101 @@ public: + } + } + ++ // the cells of a slice in ascending order: those that contain any of its sequences at a ++ // position >= slice.p_min ++ template ++ void for_slice_cells(const llama_kv_rows_slice & slice, F && visit) const { ++ const uint32_t n_words = (used_max_p1() + 63)/64; ++ ++ for (uint32_t w = 0; w < n_words; ++w) { ++ uint64_t word = 0; ++ for (const llama_seq_id seq_id : slice.seq_ids) { ++ const auto & bits = seq_bits[seq_id]; ++ if (w < bits.size()) { ++ word |= bits[w]; ++ } ++ } ++ ++ for (uint64_t b = word; b != 0; b &= b - 1) { ++ const int32_t i = 64*w + ctz64(b); ++ if (pos[i] >= slice.p_min) { ++ visit(i); ++ } ++ } ++ } ++ } ++ ++ // length of a slice's cell list once every run of consecutive cells after the first starts on ++ // a multiple of `block` list positions (see get_seq_cells_aligned) ++ int64_t seq_cells_aligned_len(const llama_kv_rows_slice & slice, uint32_t block) const { ++ int64_t n = 0; ++ int32_t previous = -2; ++ ++ for_slice_cells(slice, [&](int32_t i) { ++ if (i != previous + 1 && n%block != 0) { ++ n += block - n%block; ++ } ++ n++; ++ previous = i; ++ }); ++ ++ return n; ++ } ++ ++ // same as get_seq_cells, with -1 before each run of consecutive cells that does not continue ++ // the previous cell, so that every run starts on a multiple of `block` list positions: ++ // a block of the list is then one consecutive range of cells, possibly ending in padding, ++ // or all padding ++ // returns false, with `data` left unspecified, if a list padded this way exceeds `n_per_seq` ++ bool get_seq_cells_aligned(const std::vector & slices, int32_t * data, int64_t n_per_seq, uint32_t block) const { ++ assert(slices.size() >= 1); ++ assert(block >= 1); ++ ++ const int64_t n_slices = (int64_t) slices.size(); ++ ++ for (int64_t s = 0; s < n_slices; ++s) { ++ int32_t * const begin = data + s*n_per_seq; ++ int32_t * const end = begin + n_per_seq; ++ ++ int32_t * dst = begin; ++ int32_t previous = -2; ++ bool fits = true; ++ ++ for_slice_cells(slices[s], [&](int32_t i) { ++ if (!fits) { ++ return; ++ } ++ ++ const int64_t at = dst - begin; ++ if (i != previous + 1 && at%block != 0) { ++ const int64_t at_aligned = at + (block - at%block); ++ if (at_aligned >= n_per_seq) { ++ fits = false; ++ return; ++ } ++ std::fill(dst, begin + at_aligned, -1); ++ dst = begin + at_aligned; ++ } ++ ++ if (dst == end) { ++ fits = false; ++ return; ++ } ++ ++ *dst++ = i; ++ previous = i; ++ }); ++ ++ if (!fits) { ++ return false; ++ } ++ ++ std::fill(dst, end, -1); ++ } ++ ++ return true; ++ } ++ + // the minimum position of sequence seq_id currently present in any of the cells + // return -1 if the sequence is not present + llama_pos seq_pos_min(llama_seq_id seq_id) const { +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index bcb407ae8..cc27837c5 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -193,6 +193,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) + llama_build_and_test(test-skippy-kv-page-export.cpp) + llama_build_and_test(test-skippy-verify-checkpoint-retirement.cpp) + llama_build_and_test(test-skippy-kv-cells-contiguous.cpp) ++ llama_build_and_test(test-skippy-kv-rows-aligned.cpp) + llama_build_and_test(test-skippy-recurrent-state-roundtrip.cpp) + # these tests are disabled on Windows because they use internal functions not exported with LLAMA_API (when building with shared libraries) + llama_build_and_test(test-unicode.cpp LABEL behavior LINK llama) +diff --git a/tests/test-flash-attn-rows-perf.cpp b/tests/test-flash-attn-rows-perf.cpp +index dbffc27e4..fd3179a06 100644 +--- a/tests/test-flash-attn-rows-perf.cpp ++++ b/tests/test-flash-attn-rows-perf.cpp +@@ -37,7 +37,7 @@ constexpr int64_t kv_heads = 4; + constexpr int64_t mask_queries = 64; + constexpr int64_t slack = 256; + +-enum class layout { dense, identity, chunk64, stride, padded }; ++enum class layout { dense, identity, chunk64, stride, padded, tail, split }; + + const char * layout_name(layout value) { + switch (value) { +@@ -46,6 +46,8 @@ const char * layout_name(layout value) { + case layout::chunk64: return "rows:chunk64"; + case layout::stride: return "rows:stride"; + case layout::padded: return "rows:padded"; ++ case layout::tail: return "rows:tail"; ++ case layout::split: return "rows:split"; + } + return "?"; + } +@@ -63,6 +65,21 @@ int32_t cell_of(layout value, int64_t rows, int64_t slices, int64_t s, int64_t i + case layout::padded: return i < rows - 128 ? int32_t(s*rows + i) : -1; + case layout::stride: return int32_t(i*slices + s); + case layout::chunk64: return int32_t((i/64)*(64*slices) + s*64 + i%64); ++ // one run whose last block is partly padding ++ case layout::tail: return i < rows - 17 ? int32_t(s*rows + i) : -1; ++ // two runs: the first ends inside a block, padding to the next block, the second 64 cells on ++ case layout::split: { ++ const int64_t first = rows/2 - 10; ++ const int64_t second = (first + 31)/32*32; ++ if (i < first) { ++ return int32_t(s*rows + i); ++ } ++ if (i < second) { ++ return -1; ++ } ++ const int64_t cell = s*rows + first + 64 + (i - second); ++ return cell < s*rows + rows + 64 ? int32_t(cell) : -1; ++ } + case layout::dense: break; + } + return -1; +@@ -275,7 +292,7 @@ int main(int argc, char ** argv) { + std::printf("%-14s %6s %6s %12s %12s %8s %12s\n", "layout", "rows", "slices", "gpu_us/call", "wall_us/call", "cmd/chain", "checksum"); + for (int64_t slices : {1, 4}) { + for (int64_t rows : {768, 4864}) { +- for (layout value : {layout::dense, layout::identity, layout::chunk64, layout::stride, layout::padded}) { ++ for (layout value : {layout::dense, layout::identity, layout::chunk64, layout::stride, layout::padded, layout::tail, layout::split}) { + if (slices == 1 && (value == layout::chunk64 || value == layout::stride)) { + continue; // identical to identity with one slice + } +diff --git a/tests/test-skippy-kv-rows-aligned.cpp b/tests/test-skippy-kv-rows-aligned.cpp +new file mode 100644 +index 000000000..5cc440ab3 +--- /dev/null ++++ b/tests/test-skippy-kv-rows-aligned.cpp +@@ -0,0 +1,106 @@ ++// Block-aligned row lists (llama_kv_cells::get_seq_cells_aligned) against llama.cpp's own lists: ++// the same cells, every run on a block boundary, every block one consecutive range or padding. ++#include "../src/llama-kv-cells.h" ++ ++#include ++#include ++#include ++#include ++ ++static int failures = 0; ++#define CHECK(cond) do { if (!(cond)) { ++failures; std::printf("FAIL line %d: %s\n", __LINE__, #cond); } } while (0) ++ ++static std::vector live(const std::vector & list) { ++ std::vector out; ++ std::copy_if(list.begin(), list.end(), std::back_inserter(out), [](int32_t c) { return c >= 0; }); ++ return out; ++} ++ ++int main() { ++ std::mt19937 rng(7); ++ const uint32_t block = 32; ++ for (int round = 0; round < 400; ++round) { ++ const uint32_t n_cells = 256 * (1 + rng() % 8); ++ llama_kv_cells cells; ++ cells.resize(n_cells); ++ const int n_seq = 1 + rng() % 4; ++ std::vector next_pos(n_seq, 0); ++ const uint32_t fill = rng() % n_cells; ++ const bool fragmented = rng() % 3 == 0; ++ for (uint32_t i = 0; i < fill; ++i) { ++ const uint32_t cell = fragmented ? rng() % n_cells : i; ++ if (!cells.is_empty(cell)) { ++ continue; ++ } ++ // runs of one sequence, unless fragmented ++ const llama_seq_id seq = fragmented ? (llama_seq_id) (rng() % n_seq) : (llama_seq_id) ((i / (16 + rng() % 3)) % n_seq); ++ cells.pos_set(cell, next_pos[seq]++); ++ cells.seq_add(cell, seq); ++ if (rng() % 50 == 0 && n_seq > 1) { ++ cells.seq_add(cell, (seq + 1) % n_seq); ++ } ++ } ++ ++ std::vector slices; ++ if (rng() % 4 == 0) { ++ llama_kv_rows_slice all; ++ for (int s = 0; s < n_seq; ++s) { all.seq_ids.push_back(s); } ++ slices.push_back(all); ++ } else { ++ for (int s = 0; s < n_seq; ++s) { ++ llama_kv_rows_slice one; ++ one.seq_ids = { s }; ++ one.p_min = rng() % 3 == 0 ? (llama_pos) (rng() % 40) : -1; ++ slices.push_back(one); ++ } ++ } ++ ++ int64_t longest = 0; ++ for (const auto & slice : slices) { ++ longest = std::max(longest, cells.seq_cells_aligned_len(slice, block)); ++ } ++ const int64_t n_plain = n_cells; ++ std::vector plain(slices.size() * n_plain); ++ cells.get_seq_cells(slices, plain.data(), n_plain); ++ ++ // room for the aligned lists: same cells, runs on block boundaries, blocks consecutive or padding ++ const int64_t n_rows = std::max(256, (longest + 255) / 256 * 256); ++ std::vector aligned(slices.size() * n_rows, 12345); ++ CHECK(cells.get_seq_cells_aligned(slices, aligned.data(), n_rows, block)); ++ for (size_t s = 0; s < slices.size(); ++s) { ++ const std::vector a(aligned.begin() + s * n_rows, aligned.begin() + (s + 1) * n_rows); ++ const std::vector p(plain.begin() + s * n_plain, plain.begin() + (s + 1) * n_plain); ++ CHECK(live(a) == live(p)); ++ int64_t last_live = -1; ++ for (int64_t i = 0; i < n_rows; ++i) { ++ if (a[i] >= 0) { last_live = i; } ++ if (a[i] >= 0 && i % block != 0) { ++ CHECK(a[i - 1] == a[i] - 1); ++ } ++ } ++ CHECK(last_live + 1 == cells.seq_cells_aligned_len(slices[s], block)); ++ for (int64_t b = 0; b + block <= n_rows; b += block) { ++ const int32_t first = a[b]; ++ const auto tail = std::find(a.begin() + b, a.begin() + b + block, -1); ++ const int64_t n_live = tail - (a.begin() + b); ++ CHECK(std::all_of(tail, a.begin() + b + block, [](int32_t c) { return c == -1; })); ++ CHECK(first < 0 ? n_live == 0 : a[b + n_live - 1] == first + n_live - 1); ++ } ++ } ++ ++ // block 1 is the plain list ++ std::vector unit(slices.size() * n_plain, 12345); ++ CHECK(cells.get_seq_cells_aligned(slices, unit.data(), n_plain, 1)); ++ CHECK(unit == plain); ++ ++ // no room: reports it instead of writing past the list ++ if (longest > 1) { ++ std::vector tight(slices.size() * (longest - 1) + 1, 777); ++ const bool fits = cells.get_seq_cells_aligned(slices, tight.data(), longest - 1, block); ++ CHECK(!fits); ++ CHECK(tight.back() == 777); ++ } ++ } ++ std::printf("%s\n", failures ? "FAILED" : "aligned row lists: all checks passed"); ++ return failures != 0; ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0028-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch b/skippy/llama_cpp/patches/0028-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch new file mode 100644 index 0000000000..32846b7b2e --- /dev/null +++ b/skippy/llama_cpp/patches/0028-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch @@ -0,0 +1,77 @@ +From 79422cd665d31cec86fcc9d6bbd69b308a87d83f Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 13:07:18 +1100 +Subject: [PATCH 28/32] ggml-metal: GGML_METAL_ROWS_DEBUG counts the + row-attention variant choices + +At exit, how many dispatches took the gather-free variant, the general +kernel, or found their lists not host-visible; the first blocks that +disqualified a list are printed as they happen. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/src/ggml-metal/ggml-metal-ops.cpp | 28 ++++++++++++++++++++++++-- + 1 file changed, 26 insertions(+), 2 deletions(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index a18d41ad8..e2319db33 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -12,6 +12,8 @@ + + #include + #include ++#include ++#include + #include + #include + +@@ -3609,8 +3611,21 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + // consecutive range (possibly ending in padding) or all padding. a run ascends, so its ends + // decide; the lists are readable from the host whenever their Metal buffer is shared or + // mapped (every buffer type but private) +- const bool rows_dense = has_rows && +- ggml_metal_buffer_is_shared((ggml_metal_buffer_t) (kv_rows->view_src ? kv_rows->view_src->buffer : kv_rows->buffer)->context) && ++ // GGML_METAL_ROWS_DEBUG=1 reports, at exit, how often the gather-free variant was chosen and ++ // prints the first blocks that disqualified a list ++ static const bool rows_debug = getenv("GGML_METAL_ROWS_DEBUG") != nullptr; ++ static std::atomic rows_dense_hits{0}, rows_dense_misses{0}, rows_private{0}; ++ static const bool rows_debug_registered = rows_debug && (atexit([] { ++ GGML_LOG_INFO("rows attention: gather-free %lld, general %lld, lists not host-visible %lld\n", ++ (long long) rows_dense_hits.load(), (long long) rows_dense_misses.load(), (long long) rows_private.load()); ++ }), true); ++ GGML_UNUSED(rows_debug_registered); ++ const bool rows_shared = has_rows && ++ ggml_metal_buffer_is_shared((ggml_metal_buffer_t) (kv_rows->view_src ? kv_rows->view_src->buffer : kv_rows->buffer)->context); ++ if (has_rows && !rows_shared) { ++ ++rows_private; ++ } ++ const bool rows_dense = rows_shared && + [&] { + constexpr int64_t C = OP_FLASH_ATTN_EXT_VEC_NCPSG; + const int32_t * lists = (const int32_t *) kv_rows->data; +@@ -3628,11 +3643,20 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + const int64_t live = tail - block; + if (tail == block + C || block[live - 1] != first + live - 1 || first + C > n_cache_rows || + std::any_of(tail, block + C, [](int32_t row) { return row >= 0; })) { ++ if (rows_debug && rows_dense_misses.load() < 4) { ++ GGML_LOG_INFO("rows attention: general kernel: list %lld block %lld of %lld: first %d last %d live %lld [%d..%d] cache rows %lld\n", ++ (long long) (b/(ne11_attn/C)), (long long) (b % (ne11_attn/C)), (long long) (ne11_attn/C), ++ first, block[C - 1], (long long) live, block[std::max(live - 1, 0)], tail < block + C ? *tail : -2, ++ (long long) n_cache_rows); ++ } + return false; + } + } + return true; + }(); ++ if (rows_shared) { ++ (rows_dense ? rows_dense_hits : rows_dense_misses)++; ++ } + + float scale; + float max_bias; +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0029-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch b/skippy/llama_cpp/patches/0029-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch new file mode 100644 index 0000000000..9dcad14acc --- /dev/null +++ b/skippy/llama_cpp/patches/0029-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch @@ -0,0 +1,230 @@ +From cdbfb54e00727c01cbf03067036a3c9348dec0b2 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 19:48:49 +1100 +Subject: [PATCH 29/32] ggml, skippy: report every backend buffer's life as a + trace span + +ggml_backend_set_buffer_event_callback hears each buffer a backend creates, +its usage once llama sets it, and its release; buffers alive at install are +replayed. Skippy forwards them as instant native spans (ggml.buffer_alloc, +ggml.buffer_usage, ggml.buffer_free) whose detail is ' ' and +whose value is the size, so a trace can say what device memory is made of. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/include/ggml-backend.h | 29 ++++++++++++++++ + ggml/src/ggml-backend.cpp | 67 +++++++++++++++++++++++++++++++++++++ + src/skippy/tracing.cpp | 36 ++++++++++++++++++++ + 3 files changed, 132 insertions(+) + +diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h +index f326769a3..4383bd3ff 100644 +--- a/ggml/include/ggml-backend.h ++++ b/ggml/include/ggml-backend.h +@@ -373,6 +373,35 @@ extern "C" { + ggml_backend_trace_span_callback_t callback, + void * user_data); + ++ // Buffer events: every buffer a backend creates, its usage once set, and ++ // its release, so a host can say what device memory is made of. Container ++ // buffers (multi, meta) are not reported; their parts are. On install the ++ // buffers alive at that moment are replayed as allocations, with their ++ // usage, from the installing thread. ++ enum ggml_backend_buffer_event_kind { ++ GGML_BACKEND_BUFFER_EVENT_ALLOC, ++ GGML_BACKEND_BUFFER_EVENT_USAGE, ++ GGML_BACKEND_BUFFER_EVENT_FREE, ++ }; ++ ++ struct ggml_backend_buffer_event { ++ enum ggml_backend_buffer_event_kind kind; ++ // identity only: on a free the buffer is gone once the callback returns ++ const struct ggml_backend_buffer * buffer; ++ // the buffer type's name, such as "Metal" or "Metal_Mapped"; static storage ++ const char * buft_name; ++ size_t size; ++ enum ggml_backend_buffer_usage usage; ++ }; ++ ++ typedef void (*ggml_backend_buffer_event_callback_t)( ++ const struct ggml_backend_buffer_event * event, ++ void * user_data); ++ // Process-wide; a null callback stops reporting. ++ GGML_API void ggml_backend_set_buffer_event_callback( ++ ggml_backend_buffer_event_callback_t callback, ++ void * user_data); ++ + // + // Backend registry + // +diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp +index 9c8980505..7cf2c6580 100644 +--- a/ggml/src/ggml-backend.cpp ++++ b/ggml/src/ggml-backend.cpp +@@ -20,6 +20,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -233,6 +234,68 @@ ggml_backend_dev_t ggml_backend_buft_get_device(ggml_backend_buffer_type_t buft) + + // backend buffer + ++// buffer events (see ggml-backend.h): the callback, and the buffers alive so ++// a late install can be told what already exists ++namespace { ++ ++struct buffer_events { ++ std::mutex mutex; ++ ggml_backend_buffer_event_callback_t callback = nullptr; ++ void * user_data = nullptr; ++ std::unordered_map live; ++}; ++ ++buffer_events & buffer_event_state() { ++ static buffer_events state; ++ return state; ++} ++ ++// container buffers only wrap buffers that are reported on their own ++bool buffer_is_reported(ggml_backend_buffer_t buffer) { ++ return !ggml_backend_buffer_is_multi_buffer(buffer) && !ggml_backend_buffer_is_meta(buffer); ++} ++ ++void report_buffer(buffer_events & state, enum ggml_backend_buffer_event_kind kind, ggml_backend_buffer_t buffer) { ++ if (state.callback == nullptr) { ++ return; ++ } ++ const ggml_backend_buffer_event event = { ++ /* .kind = */ kind, ++ /* .buffer = */ buffer, ++ /* .buft_name = */ ggml_backend_buft_name(buffer->buft), ++ /* .size = */ buffer->size, ++ /* .usage = */ buffer->usage, ++ }; ++ state.callback(&event, state.user_data); ++} ++ ++void buffer_event(enum ggml_backend_buffer_event_kind kind, ggml_backend_buffer_t buffer) { ++ if (!buffer_is_reported(buffer)) { ++ return; ++ } ++ buffer_events & state = buffer_event_state(); ++ std::lock_guard lock(state.mutex); ++ switch (kind) { ++ case GGML_BACKEND_BUFFER_EVENT_ALLOC: state.live[buffer] = buffer->usage; break; ++ case GGML_BACKEND_BUFFER_EVENT_USAGE: state.live[buffer] = buffer->usage; break; ++ case GGML_BACKEND_BUFFER_EVENT_FREE: state.live.erase(buffer); break; ++ } ++ report_buffer(state, kind, buffer); ++} ++ ++} // namespace ++ ++void ggml_backend_set_buffer_event_callback(ggml_backend_buffer_event_callback_t callback, void * user_data) { ++ buffer_events & state = buffer_event_state(); ++ std::lock_guard lock(state.mutex); ++ state.callback = callback; ++ state.user_data = user_data; ++ std::for_each(state.live.begin(), state.live.end(), [&state](const auto & entry) { ++ // the buffer object is alive while it is in the table; its fields are what the event reports ++ report_buffer(state, GGML_BACKEND_BUFFER_EVENT_ALLOC, const_cast(entry.first)); ++ }); ++} ++ + ggml_backend_buffer_t ggml_backend_buffer_init( + ggml_backend_buffer_type_t buft, + struct ggml_backend_buffer_i iface, +@@ -245,6 +308,7 @@ ggml_backend_buffer_t ggml_backend_buffer_init( + /* .size = */ size, + /* .usage = */ GGML_BACKEND_BUFFER_USAGE_ANY + }; ++ buffer_event(GGML_BACKEND_BUFFER_EVENT_ALLOC, buffer); + + return buffer; + } +@@ -257,6 +321,7 @@ void ggml_backend_buffer_free(ggml_backend_buffer_t buffer) { + if (buffer == NULL) { + return; + } ++ buffer_event(GGML_BACKEND_BUFFER_EVENT_FREE, buffer); + + if (buffer->iface.free_buffer != NULL) { + buffer->iface.free_buffer(buffer); +@@ -333,6 +398,8 @@ void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backe + ggml_backend_multi_buffer_set_usage(buffer, usage); + } else if (ggml_backend_buffer_is_meta(buffer)) { + ggml_backend_meta_buffer_set_usage(buffer, usage); ++ } else { ++ buffer_event(GGML_BACKEND_BUFFER_EVENT_USAGE, buffer); + } + } + +diff --git a/src/skippy/tracing.cpp b/src/skippy/tracing.cpp +index 29e9047b1..48d827d34 100644 +--- a/src/skippy/tracing.cpp ++++ b/src/skippy/tracing.cpp +@@ -6,6 +6,7 @@ + #include + #include + #include ++#include + + namespace { + +@@ -86,6 +87,39 @@ void forward_backend_span(const ggml_backend_trace_span * span, void *) { + span->start_unix_ns, span->end_unix_ns, nullptr, 0); + } + ++const char * buffer_usage_name(enum ggml_backend_buffer_usage usage) { ++ switch (usage) { ++ case GGML_BACKEND_BUFFER_USAGE_WEIGHTS: return "weights"; ++ case GGML_BACKEND_BUFFER_USAGE_COMPUTE: return "compute"; ++ case GGML_BACKEND_BUFFER_USAGE_ANY: return "any"; ++ } ++ return "other"; ++} ++ ++const char * buffer_event_name(enum ggml_backend_buffer_event_kind kind) { ++ switch (kind) { ++ case GGML_BACKEND_BUFFER_EVENT_ALLOC: return "ggml.buffer_alloc"; ++ case GGML_BACKEND_BUFFER_EVENT_USAGE: return "ggml.buffer_usage"; ++ case GGML_BACKEND_BUFFER_EVENT_FREE: return "ggml.buffer_free"; ++ } ++ return "ggml.buffer"; ++} ++ ++// A buffer's life as instant spans, so a trace can say what device memory ++// is made of: detail is " ", the value its size in bytes. ++void forward_buffer_event(const ggml_backend_buffer_event * event, void *) { ++ if (event == nullptr) { ++ return; ++ } ++ char detail[96]; ++ std::snprintf(detail, sizeof(detail), "%s %s %p", ++ event->buft_name != nullptr ? event->buft_name : "?", ++ buffer_usage_name(event->usage), static_cast(event->buffer)); ++ const int64_t now = unix_now_ns(); ++ deliver_span(next_span_id(), t_current != 0 ? t_current : t_tag, buffer_event_name(event->kind), detail, ++ now, now, "bytes", static_cast(event->size)); ++} ++ + // the names skippy/tracing.h documents for ggml_backend_op_class + const char * op_class_name(int32_t op_class) { + switch (op_class) { +@@ -234,6 +268,8 @@ enum skippy_status skippy_set_native_span_callback( + set_callback(callback != nullptr ? forward_backend_span : nullptr, nullptr); + } + } ++ // Buffers alive now are replayed from this thread as allocations. ++ ggml_backend_set_buffer_event_callback(callback != nullptr ? forward_buffer_event : nullptr, nullptr); + + // Skippy and llama report their own spans with or without a backend. + return SKIPPY_STATUS_OK; +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0030-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch b/skippy/llama_cpp/patches/0030-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch new file mode 100644 index 0000000000..6d620f5b2c --- /dev/null +++ b/skippy/llama_cpp/patches/0030-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch @@ -0,0 +1,252 @@ +From ef158eb319a95c174fab6627065df0ff93563210 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sun, 8 Nov 2026 20:18:33 +1100 +Subject: [PATCH 30/32] llama: zero KV pool cells as the high-water mark + advances, not at creation + +Clearing the whole pool at creation makes every page resident before the +first request: with four lanes at the default context that is 48 GiB charged +to the process for cells that may never be used. Attention reads only the +cells get_n_kv() covers, so clear_cells_through zeroes up to that padding +boundary above the highest cell each ubatch writes, once, and a page below +the mark holds zeros or data. + +The pool is still cleared at creation when a cell range is not one byte +range of each tensor (a transposed V) or a buffer cannot zero a tensor range +(ggml_backend_buffer_has_memset; ggml_backend_tensor_memset asserts +otherwise). A cache that shares another's cells applies no ubatch itself, so +it has no mark: it skips the creation clear only on Metal, whose fresh +buffers read as zeros, and is cleared at creation everywhere else. +clear_eagerly() restores llama.cpp's behaviour for a caller that wants it. + +llama_memory_bufs::emplace gains a clear flag so an owner can zero its +buffers itself. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + ggml/include/ggml-backend.h | 2 + + ggml/src/ggml-backend.cpp | 4 ++ + src/llama-kv-cache.cpp | 78 ++++++++++++++++++++++++++++++++++++- + src/llama-kv-cache.h | 15 +++++++ + src/llama-memory.cpp | 6 ++- + src/llama-memory.h | 3 +- + 6 files changed, 103 insertions(+), 5 deletions(-) + +diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h +index 4383bd3ff..fced5e821 100644 +--- a/ggml/include/ggml-backend.h ++++ b/ggml/include/ggml-backend.h +@@ -64,6 +64,8 @@ extern "C" { + GGML_API size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor); + GGML_API void ggml_backend_buffer_clear (ggml_backend_buffer_t buffer, uint8_t value); + GGML_API bool ggml_backend_buffer_is_host (ggml_backend_buffer_t buffer); ++ // whether ggml_backend_tensor_memset is implemented for tensors of this buffer ++ GGML_API bool ggml_backend_buffer_has_memset (ggml_backend_buffer_t buffer); + GGML_API void ggml_backend_buffer_set_usage (ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage); + GGML_API enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage (ggml_backend_buffer_t buffer); + GGML_API ggml_backend_buffer_type_t ggml_backend_buffer_get_type (ggml_backend_buffer_t buffer); +diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp +index 7cf2c6580..6988537ed 100644 +--- a/ggml/src/ggml-backend.cpp ++++ b/ggml/src/ggml-backend.cpp +@@ -385,6 +385,10 @@ size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const st + return ggml_backend_buft_get_alloc_size(ggml_backend_buffer_get_type(buffer), tensor); + } + ++bool ggml_backend_buffer_has_memset(ggml_backend_buffer_t buffer) { ++ return buffer != NULL && buffer->iface.memset_tensor != NULL; ++} ++ + bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) { + return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer)); + } +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index 1ab98ee59..a36b29e5a 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -62,6 +62,14 @@ static void ggml_gen_hadamard(ggml_tensor * tensor) { + } + } + ++// Whether a buffer of this kind reads as zeros until something is written to it. Metal hands out ++// zero-filled buffers; host memory from an allocator may be recycled, and device memory elsewhere ++// starts undefined. ++static bool kv_buffer_starts_zeroed(ggml_backend_buffer_t buf) { ++ const char * name = ggml_backend_buffer_name(buf); ++ return strncmp(name, "MTL", 3) == 0 && name[3] != '\0' && strspn(name + 3, "0123456789") == strlen(name + 3); ++} ++ + // + // llama_kv_cache + // +@@ -266,6 +274,12 @@ llama_kv_cache::llama_kv_cache( + map_layer_ids[il] = layers.size(); + + layers.push_back({ il, k, v, k_idx, k_stream, v_stream, k_idx_stream }); ++ ++ for (ggml_tensor * t : { k, v, k_idx }) { ++ if (t) { ++ cell_tensors.push_back(t); ++ } ++ } + } + + if (reuse) { +@@ -292,13 +306,37 @@ llama_kv_cache::llama_kv_cache( + } + } + +- // allocate the tensors and initialize the buffers to avoid NaNs in the padding ++ // allocate the tensors; how their padding is kept free of NaNs is decided below + for (auto & [buft, ctx] : ctx_map) { +- ggml_backend_buffer_t buf = ctxs_bufs.emplace(std::move(ctx), buft, "kv cache"); ++ ggml_backend_buffer_t buf = ctxs_bufs.emplace(std::move(ctx), buft, "kv cache", /*clear =*/ false); + + LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0); + } + ++ // The cells are zeroed as they come into use instead of all at once here (see ++ // clear_cells_through). That needs a cell range to be one byte range of each tensor, which a ++ // transposed V is not, and buffers that can zero a range. One decision covers every buffer: ++ // a pool cleared lazily in part would leave the rest never zeroed. ++ // A cache that shares the cells of another one applies no ubatch of its own, so nothing would ++ // zero its tensors later; it skips the clear only where fresh memory already reads as zeros. ++ { ++ const bool by_range = !v_trans && !no_alloc && ++ std::all_of(cell_tensors.begin(), cell_tensors.end(), [](const ggml_tensor * t) { ++ return ggml_backend_buffer_has_memset(t->buffer); ++ }); ++ const bool starts_zeroed = std::all_of(ctxs_bufs.begin(), ctxs_bufs.end(), [](const auto & ctx_buf) { ++ return kv_buffer_starts_zeroed(ctx_buf.second.get()); ++ }); ++ ++ clear_lazily = by_range && !other; ++ ++ if (!clear_lazily && !(by_range && starts_zeroed)) { ++ for (auto & [_, buf] : ctxs_bufs) { ++ ggml_backend_buffer_clear(buf.get(), 0); ++ } ++ } ++ } ++ + { + const size_t memory_size_k = size_k_bytes(); + const size_t memory_size_v = size_v_bytes(); +@@ -465,9 +503,37 @@ void llama_kv_cache::clear(bool data) { + for (auto & [_, buf] : ctxs_bufs) { + ggml_backend_buffer_clear(buf.get(), 0); + } ++ cells_cleared = get_size(); + } + } + ++void llama_kv_cache::clear_cells_through(uint32_t cell) { ++ if (!clear_lazily || cell < cells_cleared) { ++ return; ++ } ++ // attention reads the cells below get_n_kv(), which pads the highest cell in use to a multiple of ++ // kv_clear_step, so the mark advances in the same steps ++ const uint32_t upto = std::min(get_size(), GGML_PAD(cell + 1, kv_clear_step)); ++ skippy_trace::scope trace("llama.kv_clear_cells", "cells", (int64_t) (upto - cells_cleared)); ++ // [row, cell, stream]: a cell range of one stream is contiguous ++ for (ggml_tensor * t : cell_tensors) { ++ for (uint32_t s = 0; s < n_stream; ++s) { ++ ggml_backend_tensor_memset(t, 0, s*t->nb[2] + (size_t) cells_cleared*t->nb[1], (size_t) (upto - cells_cleared)*t->nb[1]); ++ } ++ } ++ cells_cleared = upto; ++} ++ ++void llama_kv_cache::clear_eagerly() { ++ if (!clear_lazily) { ++ return; ++ } ++ if (get_size() > 0) { ++ clear_cells_through(get_size() - 1); ++ } ++ clear_lazily = false; ++} ++ + bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + skippy_trace::scope trace("llama.kv_seq_rm", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] +@@ -1376,6 +1442,14 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & + + assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size()); + ++ // every cell this ubatch writes, and so every cell attention may read, lies below the mark ++ for (const auto & idxs : sinfo.idxs) { ++ const auto top = std::max_element(idxs.begin(), idxs.end()); ++ if (top != idxs.end()) { ++ clear_cells_through(*top); ++ } ++ } ++ + for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { + for (uint32_t ii = 0; ii < sinfo.size(); ++ii) { + const uint32_t i = s*sinfo.size() + ii; +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index 2be616364..5e4dd63cb 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -282,6 +282,21 @@ public: + std::vector find_chunked_cells( + const llama_ubatch & ubatch, const llama_kv_cells & cells, uint32_t head_cur) const; + ++ // Cells are zeroed as the pool's high-water mark advances, not all at creation: attention ++ // reads nothing above the cells get_n_kv() covers, and a page never written costs no memory. ++ // Cells below `cells_cleared` in every stream hold zeros or data. A layout or a buffer that ++ // cannot zero a cell range clears at creation instead, and a cache sharing another's cells ++ // keeps no mark (see the constructor). ++ static constexpr uint32_t kv_clear_step = 256; // the padding of get_n_kv() ++ uint32_t cells_cleared = 0; ++ bool clear_lazily = false; ++ void clear_cells_through(uint32_t cell); ++ // zero every cell now, as llama.cpp does at creation, and stop zeroing them lazily ++ void clear_eagerly(); ++ ++ // the K, V and K_idx tensors this cache allocated; a layer shared with another cache has none here ++ std::vector cell_tensors; ++ + // emplace the ubatch context into slot: [sinfo.idxs[0...ubatch.n_tokens - 1]] + void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch); + +diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp +index 042aab608..80dbd10c8 100644 +--- a/src/llama-memory.cpp ++++ b/src/llama-memory.cpp +@@ -86,11 +86,13 @@ ggml_backend_buffer_ptr llama_memory_bufs::alloc_buf(ggml_context * ctx, ggml_ba + return buf; + } + +-ggml_backend_buffer_t llama_memory_bufs::emplace(ggml_context_ptr ctx, ggml_backend_buffer_type_t buft, const char * name) { ++ggml_backend_buffer_t llama_memory_bufs::emplace(ggml_context_ptr ctx, ggml_backend_buffer_type_t buft, const char * name, bool clear) { + ggml_backend_buffer_ptr buf = alloc_buf(ctx.get(), buft, no_alloc, name); + + // initialize the buffer to avoid NaNs in the padding +- ggml_backend_buffer_clear(buf.get(), 0); ++ if (clear) { ++ ggml_backend_buffer_clear(buf.get(), 0); ++ } + + bufs.emplace_back(std::move(ctx), std::move(buf)); + +diff --git a/src/llama-memory.h b/src/llama-memory.h +index 37d01ed11..b6b84c315 100644 +--- a/src/llama-memory.h ++++ b/src/llama-memory.h +@@ -37,8 +37,9 @@ struct llama_memory_bufs { + explicit llama_memory_bufs(bool no_alloc) : no_alloc(no_alloc) {} + + // allocate the tensors of ctx on buft, or attach a dummy buffer if no_alloc is set ++ // the buffer is zeroed, unless its owner does that itself (clear = false) + // returns the buffer, for logging +- ggml_backend_buffer_t emplace(ggml_context_ptr ctx, ggml_backend_buffer_type_t buft, const char * name); ++ ggml_backend_buffer_t emplace(ggml_context_ptr ctx, ggml_backend_buffer_type_t buft, const char * name, bool clear = true); + + // the memory used by the tensors: the buffer sizes, or the simulated sizes if no_alloc is set + std::map memory_breakdown() const; +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0031-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch b/skippy/llama_cpp/patches/0031-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch new file mode 100644 index 0000000000..e08ccb455f --- /dev/null +++ b/skippy/llama_cpp/patches/0031-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch @@ -0,0 +1,312 @@ +From 90f39c2bf6ed09ba619d9e2a47e48b85334529b7 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Mon, 9 Nov 2026 10:27:08 +1100 +Subject: [PATCH 31/32] llama: give the pages of freed KV chunks back to the + kernel + +With the pool zeroed lazily, resident memory follows the high-water mark: +cells a finished request held stay resident after seq_rm frees them, so a +long-running server's footprint climbs to the pool and stays there. + +Now a chunk whose cells are all free again hands its whole pages back to the +kernel (MADV_FREE_REUSABLE on Apple, MADV_DONTNEED elsewhere), from seq_rm, +seq_keep, seq_add and clear, run by run and tensor by tensor. Only +host-visible buffers take part: the CPU buffer and Metal's shared buffer, +which vm_allocates its memory. A released chunk comes back as a fresh one +when a ubatch writes into it: announced to the kernel (MADV_FREE_REUSE) and +zeroed from the CPU before the GPU writes, so cells below the mark still +hold zeros or data. + +set_page_release(false) keeps the pages resident, as before. Spans +llama.kv_release_cells and llama.kv_reclaim_cells carry the bytes moved. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + src/llama-kv-cache.cpp | 154 ++++++++++++++++++++++++++++++++++++++++- + src/llama-kv-cache.h | 17 +++++ + src/llama-kv-cells.h | 7 ++ + 3 files changed, 177 insertions(+), 1 deletion(-) + +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index a36b29e5a..7d099082c 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -15,13 +15,66 @@ + #include + #include + #include ++#include + #include + #include + ++#if !defined(_WIN32) ++#include ++#include ++#endif ++ + static bool ggml_is_power_of_2(int n) { + return (n & (n - 1)) == 0; + } + ++// Whether the kernel may take pages of this buffer back and hand them out ++// again on demand: the CPU buffer, and Metal's shared buffer, which holds ++// vm_allocate'd memory but does not report itself as host so the scheduler ++// keeps it on the GPU. Metal's private and mapped buffers do not qualify. ++static bool skippy_kv_buffer_pages_are_host(ggml_backend_buffer_t buf) { ++ if (buf == nullptr) { ++ return false; ++ } ++ if (ggml_backend_buffer_is_host(buf)) { ++ return true; ++ } ++ const char * name = ggml_backend_buffer_name(buf); ++ return strncmp(name, "MTL", 3) == 0 && strspn(name + 3, "0123456789") == strlen(name + 3); ++} ++ ++// The advice that gives pages back, and the one that announces their reuse. ++#if defined(MADV_FREE_REUSABLE) ++static const int skippy_kv_release_advice = MADV_FREE_REUSABLE; ++static const int skippy_kv_reuse_advice = MADV_FREE_REUSE; ++#elif defined(MADV_DONTNEED) ++static const int skippy_kv_release_advice = MADV_DONTNEED; ++static const int skippy_kv_reuse_advice = -1; ++#else ++static const int skippy_kv_release_advice = -1; ++static const int skippy_kv_reuse_advice = -1; ++#endif ++ ++// Applies `advice` to the whole pages inside [data, data + size); returns ++// how many bytes that covered. ++static size_t skippy_kv_advise_pages(void * data, size_t size, int advice) { ++#if defined(_WIN32) ++ GGML_UNUSED(data); GGML_UNUSED(size); GGML_UNUSED(advice); ++ return 0; ++#else ++ if (advice < 0) { ++ return 0; ++ } ++ const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); ++ const uintptr_t begin = ((uintptr_t) data + page - 1) & ~(page - 1); ++ const uintptr_t end = ((uintptr_t) data + size) & ~(page - 1); ++ if (end <= begin || madvise((void *) begin, end - begin, advice) != 0) { ++ return 0; ++ } ++ return end - begin; ++#endif ++} ++ + // orthonormal Walsh-Hadamard rotation matrix + // note: res^2 == I + static void ggml_gen_hadamard(ggml_tensor * tensor) { +@@ -337,6 +390,8 @@ llama_kv_cache::llama_kv_cache( + } + } + ++ set_page_release(true); ++ + { + const size_t memory_size_k = size_k_bytes(); + const size_t memory_size_v = size_v_bytes(); +@@ -504,7 +559,9 @@ void llama_kv_cache::clear(bool data) { + ggml_backend_buffer_clear(buf.get(), 0); + } + cells_cleared = get_size(); ++ std::fill(chunk_released.begin(), chunk_released.end(), false); + } ++ release_free_chunks(); + } + + void llama_kv_cache::clear_cells_through(uint32_t cell) { +@@ -532,6 +589,88 @@ void llama_kv_cache::clear_eagerly() { + clear_cells_through(get_size() - 1); + } + clear_lazily = false; ++ set_page_release(false); ++} ++ ++void llama_kv_cache::set_page_release(bool enabled) { ++ release_pages = enabled && clear_lazily && skippy_kv_release_advice >= 0; ++ chunk_released.assign(release_pages ? (size_t) n_stream*(get_size()/kv_chunk_cells) : 0, false); ++} ++ ++void llama_kv_cache::for_each_chunk_range(uint32_t stream, uint32_t chunk0, uint32_t chunk1, ++ const std::function & fn) const { ++ std::for_each(cell_tensors.begin(), cell_tensors.end(), [&](ggml_tensor * t) { ++ if (!skippy_kv_buffer_pages_are_host(t->buffer)) { ++ return; ++ } ++ // [row, cell, stream]: a cell range of one stream is contiguous ++ fn(t, (size_t) stream*t->nb[2] + (size_t) chunk0*kv_chunk_cells*t->nb[1], (size_t) (chunk1 - chunk0)*kv_chunk_cells*t->nb[1]); ++ }); ++} ++ ++void llama_kv_cache::release_free_chunks() { ++ std::vector streams(n_stream); ++ std::iota(streams.begin(), streams.end(), 0); ++ std::for_each(streams.begin(), streams.end(), [this](uint32_t s) { release_free_chunks(s); }); ++} ++ ++void llama_kv_cache::release_free_chunks(uint32_t stream) { ++ if (!release_pages) { ++ return; ++ } ++ skippy_trace::scope trace("llama.kv_release_cells"); ++ const auto & cells = v_cells[stream]; ++ const size_t base = (size_t) stream*(get_size()/kv_chunk_cells); ++ // only chunks below the mark were ever written; a released one stays released ++ std::vector ids(cells_cleared/kv_chunk_cells); ++ std::iota(ids.begin(), ids.end(), 0); ++ std::vector freed(ids.size()); ++ std::transform(ids.begin(), ids.end(), freed.begin(), [&](uint32_t chunk) { ++ return !chunk_released[base + chunk] && cells.is_empty_range(chunk*kv_chunk_cells, kv_chunk_cells); ++ }); ++ size_t bytes = 0; ++ auto run = std::find(freed.begin(), freed.end(), true); ++ while (run != freed.end()) { ++ const auto run_end = std::find(run, freed.end(), false); ++ const uint32_t chunk0 = (uint32_t) (run - freed.begin()); ++ const uint32_t chunk1 = (uint32_t) (run_end - freed.begin()); ++ std::fill(chunk_released.begin() + base + chunk0, chunk_released.begin() + base + chunk1, true); ++ for_each_chunk_range(stream, chunk0, chunk1, [&](ggml_tensor * t, size_t offset, size_t size) { ++ bytes += skippy_kv_advise_pages((char *) t->data + offset, size, skippy_kv_release_advice); ++ }); ++ run = std::find(run_end, freed.end(), true); ++ } ++ trace.set_value("bytes", (int64_t) bytes); ++} ++ ++void llama_kv_cache::reclaim_chunks(uint32_t stream, const std::vector & idxs) { ++ if (!release_pages) { ++ return; ++ } ++ const size_t base = (size_t) stream*(get_size()/kv_chunk_cells); ++ std::vector chunks(idxs.size()); ++ std::transform(idxs.begin(), idxs.end(), chunks.begin(), [](uint32_t idx) { return idx/kv_chunk_cells; }); ++ std::sort(chunks.begin(), chunks.end()); ++ chunks.erase(std::unique(chunks.begin(), chunks.end()), chunks.end()); ++ chunks.erase(std::remove_if(chunks.begin(), chunks.end(), [&](uint32_t chunk) { ++ return chunk >= get_size()/kv_chunk_cells || !chunk_released[base + chunk]; ++ }), chunks.end()); ++ if (chunks.empty()) { ++ return; ++ } ++ // a released chunk comes back as a fresh one: announced to the kernel, ++ // then zeroed from the CPU so its pages exist before the GPU writes them ++ skippy_trace::scope trace("llama.kv_reclaim_cells"); ++ size_t bytes = 0; ++ std::for_each(chunks.begin(), chunks.end(), [&](uint32_t chunk) { ++ chunk_released[base + chunk] = false; ++ for_each_chunk_range(stream, chunk, chunk + 1, [&](ggml_tensor * t, size_t offset, size_t size) { ++ skippy_kv_advise_pages((char *) t->data + offset, size, skippy_kv_reuse_advice); ++ ggml_backend_tensor_memset(t, 0, offset, size); ++ bytes += size; ++ }); ++ }); ++ trace.set_value("bytes", (int64_t) bytes); + } + + bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { +@@ -634,6 +773,12 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + } + } + ++ if (seq_id >= 0) { ++ release_free_chunks(seq_to_stream[seq_id]); ++ } else { ++ release_free_chunks(); ++ } ++ + return true; + } + +@@ -756,6 +901,8 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { + if (new_head != cells.size() && new_head < head) { + head = new_head; + } ++ ++ release_free_chunks(seq_to_stream[seq_id]); + } + + void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { +@@ -807,6 +954,8 @@ void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, ll + // If we freed up a slot, set head to it so searching can start there. + // Otherwise we just start the next search from the beginning. + head = new_head != cells.size() ? new_head : 0; ++ ++ release_free_chunks(seq_to_stream[seq_id]); + } + + void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) { +@@ -1443,11 +1592,14 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & + assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size()); + + // every cell this ubatch writes, and so every cell attention may read, lies below the mark +- for (const auto & idxs : sinfo.idxs) { ++ // and holds zeros or data: released chunks are zeroed again ++ for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { ++ const auto & idxs = sinfo.idxs[s]; + const auto top = std::max_element(idxs.begin(), idxs.end()); + if (top != idxs.end()) { + clear_cells_through(*top); + } ++ reclaim_chunks(sinfo.strm[s], idxs); + } + + for (uint32_t s = 0; s < sinfo.n_stream(); ++s) { +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index 5e4dd63cb..24212edb2 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -5,6 +5,7 @@ + #include "llama-kv-cells.h" + #include "llama-memory.h" + ++#include + #include + #include + #include +@@ -297,6 +298,22 @@ public: + // the K, V and K_idx tensors this cache allocated; a layer shared with another cache has none here + std::vector cell_tensors; + ++ // A chunk whose cells are all free again hands its pages back to the ++ // kernel, so the pool's resident memory follows the cells in use rather ++ // than the high-water mark. A released chunk is zeroed again before a ++ // ubatch writes into it, as a chunk above the mark is. Indexed ++ // [stream][chunk]; only host-visible buffers take part. ++ bool release_pages = false; ++ std::vector chunk_released; ++ // on wherever the pool is zeroed lazily and the platform can take pages back ++ void set_page_release(bool enabled); ++ void release_free_chunks(); ++ void release_free_chunks(uint32_t stream); ++ void reclaim_chunks(uint32_t stream, const std::vector & idxs); ++ // the byte range of chunks [chunk0, chunk1) of `stream` in each cache tensor ++ void for_each_chunk_range(uint32_t stream, uint32_t chunk0, uint32_t chunk1, ++ const std::function & fn) const; ++ + // emplace the ubatch context into slot: [sinfo.idxs[0...ubatch.n_tokens - 1]] + void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch); + +diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h +index 0e42a587a..1743c8fae 100644 +--- a/src/llama-kv-cells.h ++++ b/src/llama-kv-cells.h +@@ -131,6 +131,13 @@ public: + return pos[i] == -1; + } + ++ // whether no cell in [i, i + n) is used ++ bool is_empty_range(uint32_t i, uint32_t n) const { ++ assert(i + n <= pos.size()); ++ ++ return std::all_of(pos.begin() + i, pos.begin() + i + n, [](llama_pos p) { return p == -1; }); ++ } ++ + uint32_t get_used() const { + return used.size(); + } +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/0032-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch b/skippy/llama_cpp/patches/0032-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch new file mode 100644 index 0000000000..77aa038112 --- /dev/null +++ b/skippy/llama_cpp/patches/0032-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch @@ -0,0 +1,329 @@ +From f7f6ad386e582cc402594df8d82053ddd75e95c7 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Tue, 10 Nov 2026 17:05:21 +1100 +Subject: [PATCH 32/32] skippy: size the unified KV pool and choose its memory + behaviour from the runtime config + +A unified pool was always ctx_size x lane_count cells: every lane holds a +full window at once. With Qwen3-Coder's 131072 window and four lanes that is +524288 cells, 48 GiB of Metal allocation before a request arrives, where +llama-server with -c 32768 -np 4 shares 32768 cells among its slots. + +skippy_runtime_config gains four KV controls: + +- kv_pool_tokens: the cells of a unified pool. 0 keeps ctx_size x + lane_count. Any other value is the whole pool, which the lanes share as + llama-server's slots do with --kv-unified; it must hold at least one + lane's ctx_size and needs a unified cache, since a split cache gives each + lane n_ctx / lanes. The MTP draft context takes the target's pool rather + than recomputing it. +- kv_lazy_clear: FALSE zeroes the whole pool at creation, as llama.cpp does. +- kv_release_pages: FALSE keeps the pages of free chunks. +- kv_row_attention: FALSE keeps ordinary attention over the unified pool, to + measure the row path against it. + +AUTO and TRUE take what each cache supports, so only FALSE changes a cache's +own choice; skippy_apply_kv_memory_config applies the two memory controls to +every attention cache behind a context's memory. + +skippy_model_kv_pool_cells reports the pool so the host admits against what +native allocated instead of mirroring the product. + +ABI inventory (backward compatibility with older runtimes is not kept; the +Rust mirror changes in lockstep): +- added: uint32_t skippy_model_kv_pool_cells(const struct skippy_model *), + include/skippy/state.h, src/skippy/state_memory.cpp +- changed: struct skippy_runtime_config gains uint32_t kv_pool_tokens and + int32_t kv_lazy_clear, kv_release_pages, kv_row_attention after swa_full, + include/skippy/runtime.h +- removed: none + +Bumps the Skippy ABI from 0.1.71 to 0.1.72 at this patch; the model-support +lane's bumps follow from there. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + include/skippy/common.h | 2 +- + include/skippy/runtime.h | 10 +++++++++ + include/skippy/state.h | 3 +++ + src/llama-context.cpp | 4 +++- + src/llama-graph.h | 3 +++ + src/skippy/graph_build_inputs.h | 1 + + src/skippy/model_loading.cpp | 31 +++++++++++++++++++++---- + src/skippy/state_memory.cpp | 40 +++++++++++++++++++++++++++++++++ + src/skippy/state_memory.h | 6 +++++ + 9 files changed, 94 insertions(+), 6 deletions(-) + +diff --git a/include/skippy/common.h b/include/skippy/common.h +index 0e7b4f8a2..b16229b1b 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -46,7 +46,7 @@ extern "C" { + + #define SKIPPY_ABI_VERSION_MAJOR 0 + #define SKIPPY_ABI_VERSION_MINOR 1 +-#define SKIPPY_ABI_VERSION_PATCH 71 ++#define SKIPPY_ABI_VERSION_PATCH 72 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) +diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h +index 10ea60e7c..31ce347ea 100644 +--- a/include/skippy/runtime.h ++++ b/include/skippy/runtime.h +@@ -101,6 +101,16 @@ struct skippy_runtime_config { + /** @brief Whether sliding-window-attention layers use a full, unshifted cache window (mirrors upstream `swa_full`). */ + int32_t swa_full; + ++ // How the KV pool is sized and what it does with memory it is not using. ++ /** @brief Cells in the unified KV pool, which the lanes share. 0 reserves `ctx_size` for every lane (`ctx_size` x `lane_count`), so each lane can reach its window whatever the others hold. Any other value is the whole pool: it must hold at least one lane's `ctx_size`, and requires a unified cache. */ ++ uint32_t kv_pool_tokens; ++ /** @brief Whether KV cells are zeroed as the pool's high-water mark advances rather than all at creation. AUTO and TRUE zero lazily wherever the cache layout and its buffers allow; FALSE zeroes the whole pool at creation and keeps every page, as upstream does. */ ++ int32_t kv_lazy_clear; ++ /** @brief Whether chunks of free KV cells hand their pages back to the kernel. AUTO and TRUE release wherever cells are zeroed lazily and the pool's memory is host-visible; FALSE keeps the pages. */ ++ int32_t kv_release_pages; ++ /** @brief Whether attention reads a unified pool through per-owner row lists. AUTO and TRUE use row lists wherever the backend supports them; FALSE keeps ordinary attention over the whole pool, to measure one against the other. */ ++ int32_t kv_row_attention; ++ + // Model-load and context-creation controls resolved from `hardware` + // config. + /** @brief Whether the backend offloads host tensor operations to device (mirrors upstream `op_offload`). SKIPPY_TRISTATE_AUTO preserves llama.cpp's derived default (enabled); FALSE/TRUE force the value. */ +diff --git a/include/skippy/state.h b/include/skippy/state.h +index 6d9028a18..fc5dcd389 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -30,6 +30,9 @@ enum skippy_memory_cache_capability { + */ + LLAMA_API uint32_t skippy_model_memory_cache_capabilities(const struct skippy_model * model); + ++/** @brief Cells in the model's KV pool, the capacity admission shares among its lanes; 0 before a context exists. */ ++LLAMA_API uint32_t skippy_model_kv_pool_cells(const struct skippy_model * model); ++ + enum skippy_kv_page_flag { + SKIPPY_KV_PAGE_FLAG_V_TRANSPOSED = 1 << 0, + SKIPPY_KV_PAGE_FLAG_HAS_K_IDX = 1 << 1, +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index d9068d348..5ed43df0e 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -435,9 +435,11 @@ llama_context::llama_context( + { + cparams.fused_kv_rows = false; + ++ // the caller may also keep ordinary attention over the unified pool, to measure ++ // the row path against it; nothing forces a row operation onto an unsupported backend + const char * LLAMA_KV_ROWS_DISABLE = getenv("LLAMA_KV_ROWS_DISABLE"); + if (!LLAMA_KV_ROWS_DISABLE) { +- cparams.auto_fkvr = cparams.kv_unified; ++ cparams.auto_fkvr = cparams.kv_unified && this->graph_build_inputs.kv_rows; + } else { + LLAMA_LOG_INFO("%s: LLAMA_KV_ROWS_DISABLE set, disabling kv_rows\n", __func__); + cparams.auto_fkvr = false; +diff --git a/src/llama-graph.h b/src/llama-graph.h +index 54fd815ef..b00c42eba 100644 +--- a/src/llama-graph.h ++++ b/src/llama-graph.h +@@ -101,6 +101,9 @@ struct skippy_graph_build_inputs { + std::vector activation_export_bindings; + std::vector resident_tensor_names; + std::string execution_contract; ++ // whether a context may read a unified pool through per-owner row lists ++ // where its backend supports them; false keeps ordinary attention ++ bool kv_rows = true; + + bool topology_equal(const skippy_graph_build_inputs & other) const; + }; +diff --git a/src/skippy/graph_build_inputs.h b/src/skippy/graph_build_inputs.h +index c08f2d510..d5f13eaf2 100644 +--- a/src/skippy/graph_build_inputs.h ++++ b/src/skippy/graph_build_inputs.h +@@ -15,6 +15,7 @@ inline skippy_graph_build_inputs skippy_graph_build_inputs_from_config( + const skippy_runtime_config * config, + int32_t glm_dsa_phase_hint = SKIPPY_GLM_DSA_PHASE_HINT_AUTO) { + skippy_graph_build_inputs inputs; ++ inputs.kv_rows = config == nullptr || config->kv_row_attention != SKIPPY_TRISTATE_FALSE; + const bool has_phase_hint = glm_dsa_phase_hint != SKIPPY_GLM_DSA_PHASE_HINT_AUTO; + if ((config != nullptr && (skippy_runtime_has_stage_plan(config) || config->glm_dsa_policy_profile != 0)) || + has_phase_hint) { +diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp +index a4bf2a475..5f100aa46 100644 +--- a/src/skippy/model_loading.cpp ++++ b/src/skippy/model_loading.cpp +@@ -22,6 +22,7 @@ + #include "llama-model-loader.h" + #include "model_load_config_internal.h" + #include "skippy/graph_identity.h" ++#include "skippy/state_memory.h" + #include "skippy/trace_scope.h" + #include "../vendor/nlohmann/json.hpp" + +@@ -589,6 +590,9 @@ struct skippy_runtime_config skippy_runtime_config_default(void) { + config.kv_offload = SKIPPY_TRISTATE_AUTO; + config.kv_unified = SKIPPY_TRISTATE_AUTO; + config.swa_full = SKIPPY_TRISTATE_AUTO; ++ config.kv_lazy_clear = SKIPPY_TRISTATE_AUTO; ++ config.kv_release_pages = SKIPPY_TRISTATE_AUTO; ++ config.kv_row_attention = SKIPPY_TRISTATE_AUTO; + config.op_offload = SKIPPY_TRISTATE_AUTO; + config.split_mode = SKIPPY_TRISTATE_AUTO; + config.recurrent_rollback_tokens = 2; +@@ -750,9 +754,7 @@ enum skippy_status skippy_finish_model_open( + params.n_rs_seq = skippy_env_u32("SKIPPY_RS_SEQ", default_rs_seq, 0, 64); + params.kv_unified = true; + } +- // Multi-lane activation exports rely on the shared KV pool's batch order. +- if (activation_export_stage && stage_model->lane_count > 1 && !params.kv_unified) { +- const char * message = "an exporting stage with multiple lanes requires a unified KV cache"; ++ const auto reject_configuration = [&](const char * message) { + if (event_scope != nullptr) { + event_scope->emit_failure(SKIPPY_STATUS_INVALID_ARGUMENT, message); + } +@@ -760,6 +762,23 @@ enum skippy_status skippy_finish_model_open( + delete stage_model; + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, message); + return SKIPPY_STATUS_INVALID_ARGUMENT; ++ }; ++ // A configured pool is the whole pool: the lanes share it instead of each ++ // holding a ctx_size window, as llama-server's slots do with --kv-unified. ++ // A split cache gives every lane n_ctx / lanes, so it cannot be shared. ++ const uint32_t kv_pool_tokens = config != nullptr ? config->kv_pool_tokens : 0; ++ if (kv_pool_tokens != 0) { ++ if (!params.kv_unified) { ++ return reject_configuration("kv_pool_tokens requires a unified KV cache"); ++ } ++ if (kv_pool_tokens < context_size_per_lane) { ++ return reject_configuration("kv_pool_tokens must hold at least one lane's ctx_size"); ++ } ++ params.n_ctx = kv_pool_tokens; ++ } ++ // Multi-lane activation exports rely on the shared KV pool's batch order. ++ if (activation_export_stage && stage_model->lane_count > 1 && !params.kv_unified) { ++ return reject_configuration("an exporting stage with multiple lanes requires a unified KV cache"); + } + + const skippy_graph_build_inputs graph_build_inputs = skippy_graph_build_inputs_from_config(config); +@@ -777,6 +796,7 @@ enum skippy_status skippy_finish_model_open( + skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, message); + return SKIPPY_STATUS_RUNTIME_ERROR; + } ++ skippy_apply_kv_memory_config(stage_model->ctx->get_memory(), config); + + const auto fail_boundary_load = [&](const char * message) { + if (event_scope != nullptr) { +@@ -880,6 +900,7 @@ enum skippy_status skippy_finish_model_open( + stage_model->mtp_ctx = llama_init_from_model_with_graph_inputs(model, mtp_params, graph_build_inputs); + mtp_trace.end(); + if (stage_model->mtp_ctx != nullptr) { ++ skippy_apply_kv_memory_config(stage_model->mtp_ctx->get_memory(), config); + llama_set_embeddings_nextn(stage_model->ctx, true, false); + llama_set_embeddings_nextn(stage_model->mtp_ctx, true, false); + } else { +@@ -1192,7 +1213,8 @@ enum skippy_status skippy_model_attach_mtp_draft_model( + llama_context_params ctx_params = llama_context_default_params(); + ctx_params.ctx_type = LLAMA_CONTEXT_TYPE_MTP; + ctx_params.ctx_other = target_model->ctx; +- ctx_params.n_ctx = context_size_total; ++ // the draft shares the target's cells, so it takes the target's pool ++ ctx_params.n_ctx = target_model->ctx->n_ctx(); + ctx_params.n_batch = config->n_batch > 0 ? static_cast(config->n_batch) : context_size_per_lane; + ctx_params.n_ubatch = config != nullptr && config->n_ubatch > 0 ? static_cast(config->n_ubatch) : 0u; + ctx_params.n_threads = config != nullptr && config->n_threads > 0 ? config->n_threads : skippy_default_thread_count(); +@@ -1216,6 +1238,7 @@ enum skippy_status skippy_model_attach_mtp_draft_model( + skippy_set_error(out_error, SKIPPY_STATUS_RUNTIME_ERROR, "failed to create MTP draft context"); + return SKIPPY_STATUS_RUNTIME_ERROR; + } ++ skippy_apply_kv_memory_config(target_model->mtp_ctx->get_memory(), config); + + llama_set_embeddings_nextn(target_model->ctx, true, false); + target_model->mtp_model = draft_model; +diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp +index 806e79d72..c62b1e629 100644 +--- a/src/skippy/state_memory.cpp ++++ b/src/skippy/state_memory.cpp +@@ -1,5 +1,6 @@ + #include "skippy/state_memory.h" + #include "skippy/state.h" ++#include "skippy/runtime.h" + #include "skippy/runtime_types.h" + #include "llama-kv-cache.h" + #include "llama-kv-cache-iswa.h" +@@ -9,7 +10,9 @@ + #include "llama-memory-recurrent.h" + #include "llama-graph.h" + #include "skippy/state_effects.h" ++#include + #include ++#include + + llama_kv_cache * skippy_memory_kv_adapter(llama_memory_t memory) { + if (auto * hybrid = dynamic_cast(memory)) { +@@ -24,6 +27,39 @@ llama_kv_cache * skippy_memory_kv_adapter(llama_memory_t memory) { + return nullptr; + } + ++// Every attention cache a memory owns, composite memories included. ++static std::vector skippy_memory_attention_caches(llama_memory_t memory) { ++ if (auto * dsa = dynamic_cast(memory)) { ++ return { dsa->get_mla(), dsa->get_lid() }; ++ } ++ if (auto * iswa = skippy_memory_iswa_adapter(memory)) { ++ return { iswa->get_base(), iswa->get_swa() }; ++ } ++ if (auto * kv = skippy_memory_kv_adapter(memory)) { ++ return { kv }; ++ } ++ return {}; ++} ++ ++void skippy_apply_kv_memory_config(llama_memory_t memory, const skippy_runtime_config * config) { ++ if (memory == nullptr || config == nullptr) { ++ return; ++ } ++ // AUTO takes what a cache supports, so only FALSE changes its choice. ++ const bool lazy_clear = config->kv_lazy_clear != SKIPPY_TRISTATE_FALSE; ++ const bool release_pages = config->kv_release_pages != SKIPPY_TRISTATE_FALSE; ++ const std::vector caches = skippy_memory_attention_caches(memory); ++ std::for_each(caches.begin(), caches.end(), [&](llama_kv_cache * cache) { ++ if (cache == nullptr) { ++ return; ++ } ++ if (!lazy_clear) { ++ cache->clear_eagerly(); ++ } ++ cache->set_page_release(release_pages); ++ }); ++} ++ + llama_kv_cache_iswa * skippy_memory_iswa_adapter(llama_memory_t memory) { + if (auto * iswa = dynamic_cast(memory)) { + return iswa; +@@ -107,6 +143,10 @@ uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result) { + return supported; + } + ++extern "C" uint32_t skippy_model_kv_pool_cells(const skippy_model * model) { ++ return model && model->ctx ? model->ctx->n_ctx() : 0; ++} ++ + extern "C" uint32_t skippy_model_memory_cache_capabilities(const skippy_model * model) { + uint32_t capabilities = model && model->ctx + ? model->ctx->admit_skippy_cache_capabilities( +diff --git a/src/skippy/state_memory.h b/src/skippy/state_memory.h +index 4875cf398..84e5d9c61 100644 +--- a/src/skippy/state_memory.h ++++ b/src/skippy/state_memory.h +@@ -13,4 +13,10 @@ llama_kv_cache * skippy_memory_kv_adapter(llama_memory_t memory); + llama_kv_cache_iswa * skippy_memory_iswa_adapter(llama_memory_t memory); + llama_memory_recurrent * skippy_memory_recurrent_adapter(llama_memory_t memory); + uint32_t skippy_memory_cache_capabilities(llama_memory_t memory); ++ ++struct skippy_runtime_config; ++// Sets how every attention cache behind `memory` zeroes its cells and whether ++// it returns the pages of free ones, from the configuration's KV memory ++// controls. A null configuration keeps what each cache chose for itself. ++void skippy_apply_kv_memory_config(llama_memory_t memory, const skippy_runtime_config * config); + uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result); +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/model_support/0001-models-add-inkling-family-support.patch b/skippy/llama_cpp/patches/model_support/0001-models-add-inkling-family-support.patch index c1a78d0952..e1aa32bc9c 100644 --- a/skippy/llama_cpp/patches/model_support/0001-models-add-inkling-family-support.patch +++ b/skippy/llama_cpp/patches/model_support/0001-models-add-inkling-family-support.patch @@ -1870,18 +1870,18 @@ index 35145e26d..2c51ebb7c 100644 ggml_tensor * tok_embd_w = layer.nextn.embed_tokens ? layer.nextn.embed_tokens : (model.tok_embd ? model.tok_embd diff --git a/src/skippy/speculative_decoding.cpp b/src/skippy/speculative_decoding.cpp -index 7f55c0d88..5ab739c9d 100644 +index 3fb86667d..8a53ceb51 100644 --- a/src/skippy/speculative_decoding.cpp +++ b/src/skippy/speculative_decoding.cpp -@@ -7,6 +7,7 @@ - #include "skippy/sampling_internal.h" +@@ -8,6 +8,7 @@ #include "skippy/speculative_internal.h" + #include "skippy/trace_scope.h" +#include "llama-arch.h" #include "llama-context.h" #include "llama-graph.h" #include "llama-impl.h" -@@ -23,10 +24,28 @@ +@@ -24,10 +25,28 @@ thread_local skippy_session * g_skippy_external_decode_session = nullptr; @@ -1913,7 +1913,7 @@ index 7f55c0d88..5ab739c9d 100644 return nullptr; } -@@ -71,6 +90,10 @@ struct skippy_mtp_depth_scope { +@@ -72,6 +91,10 @@ struct skippy_mtp_depth_scope { return depth_count > 1; } @@ -1924,7 +1924,7 @@ index 7f55c0d88..5ab739c9d 100644 llama_context * ctx; uint32_t depth_count; }; -@@ -175,8 +198,12 @@ void skippy_mtp_trim_session_state(skippy_session * session, llama_pos token_cou +@@ -176,8 +199,12 @@ void skippy_mtp_trim_session_state(skippy_session * session, llama_pos token_cou static bool skippy_mtp_shares_target_memory( const llama_context * mtp_ctx, const llama_context * target_ctx) { @@ -1939,7 +1939,7 @@ index 7f55c0d88..5ab739c9d 100644 } enum skippy_status skippy_mtp_sync_target_inputs( -@@ -200,7 +227,7 @@ enum skippy_status skippy_mtp_sync_target_inputs( +@@ -202,7 +229,7 @@ enum skippy_status skippy_mtp_sync_target_inputs( skippy_mtp_depth_scope mtp_depth_scope(mtp_ctx); const bool mtp_shares_target_memory = skippy_mtp_shares_target_memory(mtp_ctx, session->ctx); const bool chain_heads = mtp_depth_scope.chains_heads(); @@ -1948,7 +1948,7 @@ index 7f55c0d88..5ab739c9d 100644 // MTP consumes complete pre-norm output rows, which can be wider than // token embeddings (for example DeepSeek4 hyperconnections). const int32_t n_hidden = llama_model_n_embd_out(session->stage_model->model); -@@ -416,9 +443,55 @@ enum skippy_status skippy_mtp_sync_target_inputs( +@@ -418,9 +445,55 @@ enum skippy_status skippy_mtp_sync_target_inputs( } int skippy_external_decode_observe(llama_context * ctx, const llama_batch & batch) { @@ -2007,7 +2007,7 @@ index 7f55c0d88..5ab739c9d 100644 } skippy_graph_build_inputs skippy_external_decode_build_inputs(llama_context * ctx) { -@@ -469,7 +542,7 @@ enum skippy_status skippy_mtp_propose_next( +@@ -471,7 +544,7 @@ enum skippy_status skippy_mtp_propose_next( max_draft_tokens, SKIPPY_NATIVE_MTP_MAX_DRAFT_TOKENS); const bool chain_heads = mtp_depth_scope.chains_heads(); diff --git a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch index 7daca3241a..617760cc44 100644 --- a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch @@ -38,8 +38,8 @@ index 3448095a1..d04825da4 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 70 -+#define SKIPPY_ABI_VERSION_PATCH 71 +-#define SKIPPY_ABI_VERSION_PATCH 72 ++#define SKIPPY_ABI_VERSION_PATCH 73 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch index aafbc5288d..6619fb10a1 100644 --- a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch +++ b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch @@ -76,8 +76,8 @@ index d04825da4..54c87b6f2 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 71 -+#define SKIPPY_ABI_VERSION_PATCH 73 +-#define SKIPPY_ABI_VERSION_PATCH 73 ++#define SKIPPY_ABI_VERSION_PATCH 75 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index 22ad6fa18f..b28ac444f5 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -223,8 +223,8 @@ index 54c87b6f2..80710eb3b 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 73 -+#define SKIPPY_ABI_VERSION_PATCH 75 +-#define SKIPPY_ABI_VERSION_PATCH 75 ++#define SKIPPY_ABI_VERSION_PATCH 77 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index 5bb7366cf2..c7017a5589 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -24,7 +24,7 @@ to touch common.h it carries the queue's ABI version, 0.1.77. src/skippy/sampling.cpp | 21 +++++++- src/skippy/sampling_internal.h | 7 +++ src/skippy/session.cpp | 1 + - src/skippy/state.cpp | 1 + + src/skippy/resident_prefix.cpp | 1 + src/skippy/workloads.cpp | 1 + 12 files changed, 193 insertions(+), 2 deletions(-) create mode 100644 include/skippy/logprobs.h @@ -50,8 +50,8 @@ index 80710eb3b..93232a2b8 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 75 -+#define SKIPPY_ABI_VERSION_PATCH 78 +-#define SKIPPY_ABI_VERSION_PATCH 77 ++#define SKIPPY_ABI_VERSION_PATCH 80 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) @@ -255,12 +255,24 @@ index 000000000..43260dfc2 + *out_count = taken; + return skippy_success(out_error); +} +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +index 418ebabaf..3e2d65a21 100644 +--- a/src/skippy/resident_prefix.cpp ++++ b/src/skippy/resident_prefix.cpp +@@ -183,6 +183,7 @@ skippy_status restore_checkpoint(skippy_session * session, int32_t cache_seq_id, + session->n_past = static_cast(count); + session->token_history = std::move(history); + session->signal_history.clear(); ++ session->token_logprobs.clear(); + skippy_mtp_clear_session_state(session); + skippy_clear_verify_windows(session); + return skippy_success(error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index ec9fb94b1..cd8a82f7a 100644 +index 3a2e3147e..e610e8205 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h -@@ -146,6 +146,8 @@ struct skippy_session { - int32_t preserve_prefix_tokens = 0; +@@ -153,6 +153,8 @@ struct skippy_session { + int32_t borrowed_prefix_tokens = 0; std::vector token_history; std::vector signal_history; + // Recorded by sampling with SKIPPY_SAMPLING_FLAG_LOGPROBS until the caller takes them. @@ -350,18 +362,6 @@ index a9251d2c9..13e318534 100644 // Keep a reusable backend sampler attached across reset. Detaching it // makes the next sampled decode reattach the chain and mark the scheduler // for reserve, which rebuilds compute buffers at every request boundary. -diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index 45a53c4ba..1f2e58a37 100644 ---- a/src/skippy/state.cpp -+++ b/src/skippy/state.cpp -@@ -1037,6 +1037,7 @@ enum skippy_status skippy_session_restore_prefix( - session->token_history.assign(token_ids, token_ids + token_count); - } - session->signal_history.clear(); -+ session->token_logprobs.clear(); - skippy_mtp_clear_session_state(session); - skippy_clear_verify_windows(session); - return skippy_success(out_error); diff --git a/src/skippy/workloads.cpp b/src/skippy/workloads.cpp index d3de66cbe..3ca967bf3 100644 --- a/src/skippy/workloads.cpp diff --git a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch index 894d1b02b9..d66058038f 100644 --- a/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch +++ b/skippy/llama_cpp/patches/model_support/0011-models-expose-glm5-next-stage-graph-semantics.patch @@ -39,9 +39,9 @@ index beded64e4..0e619d785 100644 # lfm2's fixture slides its attention window, so it checkpoints every window. add_skippy_verify_rollback_test(lfm2 lfm2-dense.gguf sliding-window) + add_skippy_verify_rollback_test(glm5-next glm5-next-moe.gguf) - add_executable(skippy-sampling-history skippy/tests/sampling_history.cpp) - target_include_directories(skippy-sampling-history PRIVATE .) - target_compile_features(skippy-sampling-history PRIVATE cxx_std_17) + add_executable(skippy-backend-sample-capacity skippy/tests/backend_sample_capacity.cpp) + target_include_directories(skippy-backend-sample-capacity PRIVATE .) + target_compile_features(skippy-backend-sample-capacity PRIVATE cxx_std_17) diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp index 5789b3013..901170bcb 100644 --- a/src/models/glm5-next.cpp diff --git a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch index 37683bfb94..bfc409f8db 100644 --- a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch @@ -187,8 +187,8 @@ index 93232a2b8..d2ab5d538 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 78 -+#define SKIPPY_ABI_VERSION_PATCH 81 +-#define SKIPPY_ABI_VERSION_PATCH 80 ++#define SKIPPY_ABI_VERSION_PATCH 83 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 53bf94caf5..b4a15d05ab 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -529,6 +529,7 @@ fi if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then BUILD_TARGETS+=( skippy-asr-decode-boundary + skippy-backend-sample-capacity skippy-diffusion-host-fallback skippy-graph-build-inputs skippy-hardware-application-probe @@ -539,6 +540,7 @@ if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then skippy-concurrent-sampling skippy-selected-logits skippy-noalloc-graph-planning + skippy-recurrent-retention skippy-renamed-multishard-planning skippy-stage-slice-plan skippy-verify-rollback @@ -551,14 +553,16 @@ if [[ "$LLAMA_STAGE_FULL_REPLAY" == "ON" ]]; then test-skippy-cachegen-import test-skippy-kv-cells-contiguous test-skippy-kv-page-export + test-skippy-kv-rows-aligned test-skippy-model-loader-accounting test-skippy-recurrent-state-roundtrip test-skippy-rerank-template test-skippy-sampling-suppress + test-skippy-tracing test-skippy-verify-checkpoint-retirement ) if [[ "$LLAMA_BACKEND" == "metal" ]]; then - BUILD_TARGETS+=(test-skippy-cachegen-metal) + BUILD_TARGETS+=(test-skippy-cachegen-metal test-skippy-tracing-metal) fi fi diff --git a/tools/xtask/src/cli.rs b/tools/xtask/src/cli.rs index 3117d6956f..12fb4ac9a3 100644 --- a/tools/xtask/src/cli.rs +++ b/tools/xtask/src/cli.rs @@ -100,7 +100,7 @@ pub(crate) fn print_usage() { const NATIVE_USAGE: &str = "usage:\n cargo xtool native select-runtime --root --os --arch --backend [--cuda-major ]\n cargo xtool native verify-host-dependencies [--format {elf|macho|pe}] [--report ] [--bind-sha256] [--no-import-policy] [--max-glibc ]\n cargo xtool native linux-runtime-deps {collect|verify|order} --lib-dir [--scan-dir ]... [--arch {x86_64|aarch64|arm}] [--search-dir ]... [--cuda-major {12|13}] [--primary ]\n cargo xtool native windows-runtime-deps {collect|verify} --lib-dir [--scan-dir ]... [--search-dir ]...\n cargo xtool native release-matrix --manifest [--required-target //]... [...]\n cargo xtool native verify-runtime-package [--portable] [--expected-backend KIND] [--expected-target TARGET] ...\n cargo xtool native package-source-version {workspace|abi|runtime} SOURCE (experimental)"; -const USAGE: &str = "usage:\n cargo xtool artifact verify-checksum \n cargo xtool artifact extract-tar \n cargo xtool artifact extract-zip \n cargo xtool automation {inventory|policy} --check\n cargo xtool automation bootstrap\n cargo xtool automation ui-build --ui-dir PATH [--logs-dir PATH] [--timeout-secs 1..3600] [--pnpm-command PATH [--pnpm-script PATH]]\n cargo xtool automation parity --suite ci [--evidence ] [--interpreter | --rust-only]\n cargo xtool automation guardrail-corpus --help\n cargo xtool automation event-benchmark-run --help\n cargo xtool automation replay-matrix validate --matrix \n cargo xtool ci plan [--manifest-root ] < plan-input.json\n cargo xtool ci validate-lane --lane-plan --needs [--workflow ] [--plan-digest --canonical-plan ]\n cargo xtool ci validate-graph --workflows \n cargo xtool ci-ops runner-identity [--root ] [--catalog ] {validate|check|diagnose|lookup|seed-key|bind} ...\n cargo xtool ci-ops build-cache {status|prune|build} [--workspace ] [--target-dir ] [--max-size ] [--max-age ] [--json] [--execute] [-- ...]\n cargo xtool ci-ops sccache-stats --artifact-name --output [--github-output ] [--cache-expectation {cold|warm|opportunistic}] [--minimum-hit-rate ]\n cargo xtool ci-ops sccache-summary [--format text|json] [--minimum-hit-rate <0..1>] ...\n cargo xtool ci-ops performance-history --artifact --output --report [--baseline ] [--gate]\n cargo xtool ci-ops collect-metrics --input [--json-out ] [--status ] [--top ] [--label KEY=VALUE]...\n cargo xtool models generate [--registry ] [--check]\n cargo xtool models resolve --cadence [--artifact-id ] [--require-single-file] [--github-output [--github-output-prefix ]] [--verify-root ]\n cargo xtool models restore-inputs --github-output [--model-url --model-file | --model-manifest --model-cadence [--model-artifact-id ]]\n cargo xtool models parity-download --manifest --model-manifest --cadence manual --hf-command [--dry-run] [--status ] [--priority ] [--timeout-secs <1..86400>]\n cargo xtool prepared-input ... (UI, static ABI, native SDK inputs)\n cargo xtool release inventory [--repo ] [--head ] [--release-tag ] [--output ]\n cargo xtool release notes-base < tags.txt\n cargo xtool release notes-link --body --range --repo --out-body --out-links [--repo-root ] [--api-budget ]\n cargo xtool release notes-classify --body (--has-entries | --range --version --date --out ) [--repo-root ] [--links ]\n cargo xtool repo-consistency release-targets\n cargo xtool repo-consistency ci-crate-lists\n cargo xtool repo-consistency publish-crates\n cargo xtool repo-consistency test-all-rust-crate-coverage\n cargo xtool repo-consistency no-console-print\n cargo xtool repository docker-precheck --dockerfile PATH --shared-core true|false --fly-ui-builder true|false --entrypoint-modes true|false --workflow-no-qemu true|false\n cargo xtool repository affected-crates [--stdin | ...]\n cargo xtool repository bundled-plugins --target [--defaults ]\n cargo xtool repository bundled-plugins-check --bundle \n cargo xtool repository conventional-commits (--message | --range | ) [--trailers-only]\n cargo xtool repository env-mutation-census [--root ] [--file ]...\n cargo xtool repository llama-upstream-pin [--repository ] [--upstream-url ] \n cargo xtool repository selected-ref --ref --expected-origin --event workflow_dispatch [--repository ] [--upstream ] [--github-output --summary ] [--timeout-secs ]\n cargo xtool split-payloads {certify|artifact-for-sha256} ...\n cargo xtool release-attestation generate-keypair --private-key-out --public-key-out \n cargo xtool release-attestation stamp --binary --signing-key-file [--node-version ] [--build-id ] [--commit ] [--target-triple ] [--protocol-min ] [--protocol-max ]\n cargo xtool release-attestation inspect --binary [--public-key-file ] [--json]\n (cargo run -p xtask -- ... remains supported)"; +const USAGE: &str = "usage:\n cargo xtool artifact verify-checksum \n cargo xtool artifact extract-tar \n cargo xtool artifact extract-zip \n cargo xtool automation {inventory|policy} --check\n cargo xtool automation bootstrap\n cargo xtool automation ui-build --ui-dir PATH [--logs-dir PATH] [--timeout-secs 1..3600] [--pnpm-command PATH [--pnpm-script PATH]]\n cargo xtool automation parity --suite ci [--evidence ] [--interpreter | --rust-only]\n cargo xtool automation guardrail-corpus --help\n cargo xtool automation event-benchmark-run --help\n cargo xtool automation replay-matrix validate --matrix \n cargo xtool ci plan [--manifest-root ] < plan-input.json\n cargo xtool ci validate-lane --lane-plan --needs [--workflow ] [--plan-digest --canonical-plan ]\n cargo xtool ci validate-graph --workflows \n cargo xtool ci-ops runner-identity [--root ] [--catalog ] {validate|check|diagnose|lookup|seed-key|bind} ...\n cargo xtool ci-ops build-cache {status|prune|build} [--workspace ] [--target-dir ] [--max-size ] [--max-age ] [--json] [--execute] [-- ...]\n cargo xtool ci-ops sccache-stats --artifact-name --output [--github-output ] [--cache-expectation {cold|warm|opportunistic}] [--minimum-hit-rate ]\n cargo xtool ci-ops sccache-summary [--format text|json] [--minimum-hit-rate <0..1>] ...\n cargo xtool ci-ops performance-history --artifact --output --report [--baseline ] [--gate]\n cargo xtool ci-ops collect-metrics --input [--json-out ] [--status ] [--top ] [--label KEY=VALUE]...\n cargo xtool models generate [--registry ] [--check]\n cargo xtool models resolve --cadence [--artifact-id ] [--require-single-file] [--github-output [--github-output-prefix ]] [--verify-root ]\n cargo xtool models restore-inputs --github-output [--model-url --model-file | --model-manifest --model-cadence [--model-artifact-id ]]\n cargo xtool models fetch --cadence --root [--artifact-id ] [--timeout-secs <1..86400>] [--dry-run]\n cargo xtool models pin [@ --id --family --selector --suite ... --tag ... [--cadence ...] [--notes ] [--expect-sha256 ]] [--registry ] [--timeout-secs <1..3600>] [--dry-run]\n cargo xtool models parity-download --manifest --model-manifest --cadence manual --hf-command [--dry-run] [--status ] [--priority ] [--timeout-secs <1..86400>]\n cargo xtool prepared-input ... (UI, static ABI, native SDK inputs)\n cargo xtool release inventory [--repo ] [--head ] [--release-tag ] [--output ]\n cargo xtool release notes-base < tags.txt\n cargo xtool release notes-link --body --range --repo --out-body --out-links [--repo-root ] [--api-budget ]\n cargo xtool release notes-classify --body (--has-entries | --range --version --date --out ) [--repo-root ] [--links ]\n cargo xtool repo-consistency release-targets\n cargo xtool repo-consistency ci-crate-lists\n cargo xtool repo-consistency publish-crates\n cargo xtool repo-consistency test-all-rust-crate-coverage\n cargo xtool repo-consistency no-console-print\n cargo xtool repository docker-precheck --dockerfile PATH --shared-core true|false --fly-ui-builder true|false --entrypoint-modes true|false --workflow-no-qemu true|false\n cargo xtool repository affected-crates [--stdin | ...]\n cargo xtool repository bundled-plugins --target [--defaults ]\n cargo xtool repository bundled-plugins-check --bundle \n cargo xtool repository conventional-commits (--message | --range | ) [--trailers-only]\n cargo xtool repository env-mutation-census [--root ] [--file ]...\n cargo xtool repository llama-upstream-pin [--repository ] [--upstream-url ] \n cargo xtool repository selected-ref --ref --expected-origin --event workflow_dispatch [--repository ] [--upstream ] [--github-output --summary ] [--timeout-secs ]\n cargo xtool split-payloads {certify|artifact-for-sha256} ...\n cargo xtool release-attestation generate-keypair --private-key-out --public-key-out \n cargo xtool release-attestation stamp --binary --signing-key-file [--node-version ] [--build-id ] [--commit ] [--target-triple ] [--protocol-min ] [--protocol-max ]\n cargo xtool release-attestation inspect --binary [--public-key-file ] [--json]\n (cargo run -p xtask -- ... remains supported)"; pub(crate) struct Cli<'a> { pub(crate) root: Option, diff --git a/tools/xtask/src/model_registry/derived.rs b/tools/xtask/src/model_registry/derived.rs new file mode 100644 index 0000000000..5dc42c8594 --- /dev/null +++ b/tools/xtask/src/model_registry/derived.rs @@ -0,0 +1,335 @@ +//! `registry.derived_suites`: suites whose members are declared as a pinned +//! evals model list (the kv-validation four) times a selector list, so the +//! registry states which rows must exist and `generate` refuses a registry +//! that lacks one. `models pin` registers exactly the missing rows. +//! +//! Each list entry at each selector derives one artifact: the file name is +//! the list's with its selector suffix swapped (`Qwen3.5-4B-Q4_K_M.gguf` at +//! `BF16` is `Qwen3.5-4B-BF16.gguf`), the id is `-` with the +//! selector slug swapped (`perf-qwen3.5-4b-bf16`), the family is the list's +//! and the tags are its parts plus `gguf`. The list's digest is enforced when +//! the selector is the list's own. + +use super::fields::{ModelError, ModelResult, fail, get, is_lower_hex}; +use crate::ci_plan::catalog::{os_error_text, python_path_display}; +use crate::ci_plan::document::Json; +use std::path::Path; + +/// One artifact a derived suite requires. +#[derive(Debug, PartialEq, Eq)] +pub(super) struct Entry { + pub(super) suites: Vec, + pub(super) id: String, + pub(super) family: String, + pub(super) tags: Vec, + pub(super) repo: String, + pub(super) revision: String, + pub(super) file: String, + pub(super) selector: String, + pub(super) expected: Option, + pub(super) notes: Option, +} + +/// Every artifact the registry's derived suites require, in declaration +/// order; the lists are read under `root`. +pub(super) fn expected(root: &Path, registry: &[(String, Json)]) -> ModelResult> { + let declared = get(registry, "derived_suites") + .and_then(Json::as_array) + .unwrap_or_default(); + declared + .iter() + .filter_map(Json::as_object) + .map(|derived| { + let text = |key: &str| get(derived, key).and_then(Json::as_str).unwrap_or_default(); + let selectors = get(derived, "selectors") + .and_then(Json::as_array) + .unwrap_or_default() + .iter() + .filter_map(Json::as_str) + .collect::>(); + let list = root.join(text("from")); + let models = read_list(&list)?; + selectors + .iter() + .map(|selector| { + entries( + &models, + &python_path_display(&list), + text("suite"), + selector, + text("id_prefix"), + ) + }) + .collect::>>() + .map(|per_selector| per_selector.into_iter().flatten().collect::>()) + }) + .collect::>>() + .map(|per_suite| per_suite.into_iter().flatten().collect()) +} + +/// The required artifacts the registry does not hold yet. One it holds under +/// the same id must match the derivation and belong to the suite. +pub(super) fn missing(root: &Path, registry: &[(String, Json)]) -> ModelResult> { + let rows = get(registry, "artifacts") + .and_then(Json::as_array) + .unwrap_or_default(); + expected(root, registry)? + .into_iter() + .filter_map(|entry| { + let row = rows + .iter() + .filter_map(Json::as_object) + .find(|row| get(row, "id").and_then(Json::as_str) == Some(entry.id.as_str())); + match row { + None => Some(Ok(entry)), + Some(row) => matches(row, &entry).err().map(Err), + } + }) + .collect() +} + +fn matches(row: &[(String, Json)], entry: &Entry) -> ModelResult<()> { + let artifact = get(row, "artifact") + .and_then(Json::as_object) + .unwrap_or_default(); + let text = |key: &str| { + get(artifact, key) + .and_then(Json::as_str) + .unwrap_or_default() + }; + let file = get(artifact, "files") + .and_then(Json::as_array) + .and_then(|files| files.first()) + .and_then(|file| file.get("path")) + .and_then(Json::as_str) + .unwrap_or_default(); + let declared = get(row, "suites") + .and_then(Json::as_array) + .unwrap_or_default(); + let outside = entry + .suites + .iter() + .find(|suite| !declared.iter().any(|item| item.as_str() == Some(suite))); + let same = text("repo") == entry.repo + && text("revision") == entry.revision + && text("selector") == entry.selector + && file == entry.file; + if !same { + return fail(format!( + "artifact {} is registered as something other than {}@{} {} ({})", + entry.id, entry.repo, entry.revision, entry.file, entry.selector + )); + } + if let Some(suite) = outside { + return fail(format!("artifact {} is not in suite {suite}", entry.id)); + } + Ok(()) +} + +/// `Q4_K_M` as it appears in ids: `q4-k-m`. +fn slug(selector: &str) -> String { + selector.to_ascii_lowercase().replace('_', "-") +} + +/// The selector suffix of a GGUF file name: `Qwen3.5-4B-Q4_K_M.gguf` carries +/// `Q4_K_M`. +fn selector_of(file: &str) -> Option<(&str, &str)> { + let stem = file.strip_suffix(".gguf")?; + let (base, selector) = stem.rsplit_once('-')?; + (!base.is_empty() && !selector.is_empty()).then_some((base, selector)) +} + +fn read_list(list: &Path) -> ModelResult> { + let shown = python_path_display(list); + let bytes = std::fs::read(list).map_err(|error| ModelError(os_error_text(&error, &shown)))?; + let models = Json::parse(&bytes).map_err(|error| ModelError(format!("{shown}: {error}")))?; + match models.as_array() { + Some(models) if !models.is_empty() => Ok(models.to_vec()), + _ => fail(format!("{shown} must be a non-empty array of models")), + } +} + +/// Every model of a list, re-targeted at `selector` for `suite`. +fn entries( + models: &[Json], + shown: &str, + suite: &str, + selector: &str, + prefix: &str, +) -> ModelResult> { + models + .iter() + .enumerate() + .map(|(index, model)| { + let field = format!("{shown}[{index}]"); + let model = model + .as_object() + .ok_or_else(|| ModelError(format!("{field} must be an object")))?; + let text = |key: &str| { + get(model, key) + .and_then(Json::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| ModelError(format!("{field}.{key} must be a non-empty string"))) + }; + let key = text("key")?; + let family = text("family")?; + let revision = text("revision")?; + if !is_lower_hex(revision, 40..=40) { + return fail(format!("{field}.revision must be a commit: {revision}")); + } + let files = get(model, "files") + .and_then(Json::as_array) + .unwrap_or_default(); + let [file] = files else { + return fail(format!("{field}.files must hold exactly one file")); + }; + let name = file + .get("name") + .and_then(Json::as_str) + .ok_or_else(|| ModelError(format!("{field}.files[0].name must be a string")))?; + let sha256 = file + .get("sha256") + .and_then(Json::as_str) + .filter(|sha| is_lower_hex(sha, 64..=64)) + .ok_or_else(|| ModelError(format!("{field}.files[0].sha256 must be 64 hex")))?; + let Some((base, own)) = selector_of(name) else { + return fail(format!( + "{field}: cannot read a selector suffix from {name}" + )); + }; + let stem = key.strip_suffix(&format!("-{}", slug(own))).unwrap_or(key); + let mut tags = family + .split('-') + .chain(["gguf"]) + .map(str::to_owned) + .collect::>(); + tags.sort(); + tags.dedup(); + Ok(Entry { + suites: vec![suite.to_owned()], + id: format!("{prefix}-{stem}-{}", slug(selector)), + family: family.to_owned(), + tags, + repo: text("repo")?.to_owned(), + revision: revision.to_owned(), + file: format!("{base}-{selector}.gguf"), + selector: selector.to_owned(), + expected: (own == selector).then(|| sha256.to_owned()), + notes: Some(format!("Derived from {shown}#{key} at {selector}.")), + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + const KV_VALIDATION: &str = "skippy/evals/kv-validation/models.json"; + + fn root() -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") + } + + fn with(selectors: &[&str], rows: &str) -> Json { + let selectors = selectors + .iter() + .map(|selector| format!("\"{selector}\"")) + .collect::>() + .join(","); + Json::parse( + format!( + r#"{{"suites":["performance-parity"],"derived_suites":[{{"suite":"performance-parity","from":"{KV_VALIDATION}","selectors":[{selectors}],"id_prefix":"perf"}}],"artifacts":[{rows}]}}"# + ) + .as_bytes(), + ) + .unwrap() + } + + fn row(id: &str, suite: &str, file: &str, selector: &str) -> String { + format!( + r#"{{"id":"{id}","suites":["{suite}"],"artifact":{{"repo":"unsloth/Qwen3-4B-Instruct-2507-GGUF","revision":"a06e946bb6b655725eafa393f4a9745d460374c9","selector":"{selector}","files":[{{"path":"{file}"}}]}}}}"# + ) + } + + #[test] + fn the_kv_validation_four_derive_one_entry_per_selector() { + let registry = with(&["Q4_K_M", "BF16"], ""); + let entries = expected(&root(), registry.as_object().unwrap()).unwrap(); + assert_eq!(entries.len(), 8); + let qwen3 = &entries[0]; + assert_eq!(qwen3.id, "perf-qwen3-4b-q4-k-m"); + assert_eq!(qwen3.file, "Qwen3-4B-Instruct-2507-Q4_K_M.gguf"); + assert_eq!(qwen3.family, "dense"); + assert_eq!(qwen3.tags, ["dense", "gguf"]); + assert!( + qwen3 + .expected + .as_deref() + .is_some_and(|sha| sha.starts_with("3605803b")) + ); + let hybrid = &entries[1]; + assert_eq!(hybrid.id, "perf-qwen3.5-4b-q4-k-m"); + assert_eq!(hybrid.tags, ["dense", "gguf", "hybrid"]); + let moe_bf16 = &entries[6]; + assert_eq!(moe_bf16.id, "perf-qwen3-coder-30b-a3b-bf16"); + assert_eq!(moe_bf16.file, "Qwen3-Coder-30B-A3B-Instruct-BF16.gguf"); + assert_eq!(moe_bf16.expected, None); + assert_eq!(moe_bf16.suites, ["performance-parity"]); + assert_eq!(slug("Q4_K_M"), "q4-k-m"); + assert_eq!(selector_of("x.gguf"), None); + } + + #[test] + fn a_registered_matching_row_is_not_missing() { + let rows = row( + "perf-qwen3-4b-q8-0", + "performance-parity", + "Qwen3-4B-Instruct-2507-Q8_0.gguf", + "Q8_0", + ); + let registry = with(&["Q8_0"], &rows); + let missing = missing(&root(), registry.as_object().unwrap()).unwrap(); + assert_eq!( + missing + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(), + [ + "perf-qwen3.5-4b-q8-0", + "perf-qwen3-coder-30b-a3b-q8-0", + "perf-qwen3.5-35b-a3b-q8-0" + ] + ); + } + + #[test] + fn a_row_registered_differently_or_outside_the_suite_is_an_error() { + let other_file = row( + "perf-qwen3-4b-q8-0", + "performance-parity", + "Qwen3-4B-Instruct-2507-BF16.gguf", + "Q8_0", + ); + let registry = with(&["Q8_0"], &other_file); + let error = missing(&root(), registry.as_object().unwrap()).unwrap_err(); + assert!( + error.0.contains("registered as something other than"), + "{}", + error.0 + ); + let other_suite = row( + "perf-qwen3-4b-q8-0", + "elsewhere", + "Qwen3-4B-Instruct-2507-Q8_0.gguf", + "Q8_0", + ); + let registry = with(&["Q8_0"], &other_suite); + let error = missing(&root(), registry.as_object().unwrap()).unwrap_err(); + assert!( + error.0.contains("is not in suite performance-parity"), + "{}", + error.0 + ); + } +} diff --git a/tools/xtask/src/model_registry/fetch.rs b/tools/xtask/src/model_registry/fetch.rs new file mode 100644 index 0000000000..2f34be28dd --- /dev/null +++ b/tools/xtask/src/model_registry/fetch.rs @@ -0,0 +1,377 @@ +//! `models fetch --cadence --root `: materialize a +//! suite's cadence-admitted artifacts under one root, each in a directory +//! named by its artifact id, through the pinned HTTPS transfer, and hold +//! every file to the manifest's size and SHA-256. A file that already +//! verifies is kept; one that fails verification is reported and left for the +//! operator, because the transfer publishes only fresh paths. The layout is +//! what `models resolve --artifact-id --verify-root /` checks. + +use super::fields::{ModelError, ModelResult, fail}; +use super::manifest::{PinnedFile, Resolved, Selection, admitted_ids, resolve}; +use crate::ci_plan::catalog::{os_error_text, python_path_display}; +use crate::ci_plan::document::Json; +use crate::command_interrupt::Interrupt; +use crate::repository::check_args::Grammar; +use crate::repository::check_report::CheckReport; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +const PROGRAM: &str = "models fetch"; +const GRAMMAR: Grammar = Grammar { + usage: "cargo xtool models fetch --cadence --root + [--artifact-id ] [--timeout-secs <1..86400>] [--dry-run]", + values: &["--cadence", "--root", "--artifact-id", "--timeout-secs"], + flags: &["--dry-run"], +}; +const DEFAULT_TIMEOUT_SECS: u64 = 3600; +/// The pinned transfer's byte cap; a larger model is split in the registry. +const TRANSFER_CAP: u64 = 64 * 1024 * 1024 * 1024; + +struct Request<'a> { + manifest: &'a str, + cadence: &'a str, + root: &'a Path, + artifact_id: Option<&'a str>, + timeout: Duration, + dry_run: bool, +} + +/// One manifest file and where it lives under the root. +struct Item<'a> { + artifact: &'a str, + file: &'a PinnedFile, + directory: PathBuf, +} + +enum State { + Verified, + Missing, + Corrupt(String), +} + +pub(super) fn run(args: &[String]) -> CheckReport { + if args.len() == 1 && matches!(args[0].as_str(), "-h" | "--help") { + return CheckReport::success(format!( + "usage: {}\n\nFetches every artifact the cadence admits, or one with --artifact-id, into\n//, verified against the manifest. --dry-run lists what\nwould be fetched. --timeout-secs bounds each file's transfer (default {DEFAULT_TIMEOUT_SECS}).\n", + GRAMMAR.usage + )); + } + let parsed = match super::argv::parse(&GRAMMAR, PROGRAM, args) { + Ok(parsed) => parsed, + Err(report) => return report, + }; + let missing = [ + ("manifest", parsed.positionals.is_empty()), + ("--cadence", parsed.last("--cadence").is_none()), + ("--root", parsed.last("--root").is_none()), + ] + .iter() + .filter(|(_, absent)| *absent) + .map(|(name, _)| *name) + .collect::>(); + if !missing.is_empty() { + let message = format!( + "the following arguments are required: {}", + missing.join(", ") + ); + return super::argv::usage(&GRAMMAR, PROGRAM, &message); + } + if let [_, extra @ ..] = parsed.positionals.as_slice() + && !extra.is_empty() + { + let message = format!("unrecognized arguments: {}", extra.join(" ")); + return super::argv::usage(&GRAMMAR, PROGRAM, &message); + } + let timeout = match parsed.last("--timeout-secs") { + None => DEFAULT_TIMEOUT_SECS, + Some(text) => match text.parse::() { + Ok(seconds) if (1..=86_400).contains(&seconds) => seconds, + _ => { + return super::argv::usage( + &GRAMMAR, + PROGRAM, + "argument --timeout-secs: expected an integer from 1 to 86400", + ); + } + }, + }; + let request = Request { + manifest: &parsed.positionals[0], + cadence: parsed.last("--cadence").unwrap_or_default(), + root: Path::new(parsed.last("--root").unwrap_or_default()), + artifact_id: parsed.last("--artifact-id"), + timeout: Duration::from_secs(timeout), + dry_run: parsed.flag("--dry-run"), + }; + let mut stdout = String::new(); + match fetch_into(&request, &mut stdout) { + Ok(()) => CheckReport::success(stdout), + Err(error) => CheckReport { + stdout, + stderr: format!("test-model fetch error: {error}\n"), + code: 2, + }, + } +} + +fn fetch_into(request: &Request<'_>, stdout: &mut String) -> ModelResult<()> { + let bytes = + std::fs::read(request.manifest).map_err(|error| io_error(&error, request.manifest))?; + let manifest = Json::parse(&bytes).map_err(|error| ModelError(error.to_string()))?; + let ids = match request.artifact_id { + Some(id) => vec![id], + None => admitted_ids(&manifest, request.cadence)?, + }; + if ids.is_empty() { + return fail(format!( + "no artifact in {} is allowed at cadence {}", + request.manifest, request.cadence + )); + } + let artifacts = ids + .iter() + .map(|id| { + resolve( + &manifest, + &Selection { + artifact_id: Some(id), + cadence: request.cadence, + }, + ) + }) + .collect::>>()?; + let classified = artifacts + .iter() + .flat_map(|artifact| items(request.root, artifact)) + .map(|item| { + let state = state(&item); + (item, state) + }) + .collect::>(); + + let mut wanted = Vec::new(); + let mut corrupt = 0_usize; + for (item, state) in &classified { + match state { + State::Verified => stdout.push_str(&line("cached", item, None)), + State::Missing => { + stdout.push_str(&line("missing", item, None)); + wanted.push(item); + } + State::Corrupt(reason) => { + corrupt += 1; + stdout.push_str(&line("corrupt", item, Some(reason))); + } + } + } + let pending = wanted.iter().map(|item| item.file.size_bytes).sum::(); + stdout.push_str(&format!( + "{} file(s) cached, {} to fetch ({}), {corrupt} corrupt\n", + classified.len() - wanted.len() - corrupt, + wanted.len(), + gib(pending) + )); + if corrupt != 0 { + return fail("corrupt files must be removed before they can be fetched again"); + } + if request.dry_run { + return Ok(()); + } + if let Some(item) = wanted + .iter() + .find(|item| item.file.size_bytes > TRANSFER_CAP) + { + return fail(format!( + "{} exceeds the {} transfer cap; split it in the registry", + shown(item), + gib(TRANSFER_CAP) + )); + } + + let interrupt = Interrupt::install().map_err(|reason| ModelError(reason.to_string()))?; + let cancellation = interrupt.cancellation(); + let mut failed = Vec::new(); + for item in &wanted { + if cancellation.is_cancelled() { + break; + } + stdout.push_str(&line("fetching", item, None)); + let deadline = Instant::now() + request.timeout; + let output = item.directory.join(&item.file.name); + match super::projector_download::acquire_pinned( + &item.file.url, + &output, + &item.file.sha256, + item.file.size_bytes, + deadline, + &cancellation, + ) { + Ok(_) => stdout.push_str(&line("fetched", item, None)), + Err(error) => { + stdout.push_str(&line("failed", item, Some(&error.to_string()))); + failed.push(shown(item)); + } + } + } + interrupt + .finish() + .map_err(|_| ModelError("fetch interrupted; rerun to continue".to_owned()))?; + if !failed.is_empty() { + return fail(format!( + "{} file(s) not fetched: {}", + failed.len(), + failed.join(", ") + )); + } + Ok(()) +} + +fn items<'a>(root: &Path, artifact: &'a Resolved<'a>) -> impl Iterator> { + let directory = root.join(artifact.id); + artifact.files.iter().map(move |file| Item { + artifact: artifact.id, + file, + directory: directory.clone(), + }) +} + +/// Verified, absent, or present but not the pinned bytes. +fn state(item: &Item<'_>) -> State { + if !item.directory.join(&item.file.name).exists() { + return State::Missing; + } + match super::resolve::verify(&item.directory.display().to_string(), item.file) { + Ok(_) => State::Verified, + Err(error) => State::Corrupt(error.to_string()), + } +} + +fn shown(item: &Item<'_>) -> String { + format!("{}/{}", item.artifact, item.file.name) +} + +fn line(state: &str, item: &Item<'_>, detail: Option<&str>) -> String { + let detail = detail.map_or_else(String::new, |text| format!(": {text}")); + format!( + "{state:<9}{} ({}){detail}\n", + shown(item), + gib(item.file.size_bytes) + ) +} + +fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / f64::from(1_u32 << 30)) +} + +fn io_error(error: &std::io::Error, path: &str) -> ModelError { + ModelError(os_error_text(error, &python_path_display(Path::new(path)))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::repository::check_report::CheckReport; + + fn manifest(dir: &Path, id: &str, cadence: &str, name: &str, bytes: &[u8]) -> PathBuf { + use sha2::{Digest, Sha256}; + let digest = hex::encode(Sha256::digest(bytes)); + let text = format!( + r#"{{"schema_version":1,"manifest_kind":"test-model-artifacts","suite":"s","artifacts":[{{"id":"{id}","repo":"acme/Tiny-GGUF","revision":"deadbeef","selector":"Q4_K_M","model_ref":"acme/Tiny-GGUF:Q4_K_M","cadences":["{cadence}"],"files":["{name}"],"urls":["https://huggingface.co/acme/Tiny-GGUF/resolve/deadbeef/{name}"],"file_integrity":{{"{name}":{{"size_bytes":{},"blob_id":"{digest}"}}}}}}]}}"#, + bytes.len() + ); + let path = dir.join("manifest.json"); + std::fs::write(&path, text).unwrap(); + path + } + + fn run_args(args: &[&str]) -> CheckReport { + run(&args.iter().map(|arg| (*arg).to_owned()).collect::>()) + } + + #[test] + fn dry_run_reports_cached_and_missing_files_without_fetching() { + let dir = tempfile::tempdir().unwrap(); + let bytes = b"GGUFtiny model bytes"; + let manifest = manifest(dir.path(), "tiny", "manual", "Tiny-Q4_K_M.gguf", bytes); + let root = dir.path().join("models"); + let args = |root: &Path| { + vec![ + manifest.to_string_lossy().into_owned(), + "--cadence".into(), + "manual".into(), + "--root".into(), + root.to_string_lossy().into_owned(), + "--dry-run".into(), + ] + }; + + let report = run(&args(&root)); + assert_eq!(report.code, 0, "{}", report.stderr); + assert!(report.stdout.contains("missing tiny/Tiny-Q4_K_M.gguf")); + assert!(report.stdout.contains("0 file(s) cached, 1 to fetch")); + assert!(!root.exists(), "a dry run writes nothing"); + + std::fs::create_dir_all(root.join("tiny")).unwrap(); + std::fs::write(root.join("tiny/Tiny-Q4_K_M.gguf"), bytes).unwrap(); + let report = run(&args(&root)); + assert_eq!(report.code, 0, "{}", report.stderr); + assert!(report.stdout.contains("cached tiny/Tiny-Q4_K_M.gguf")); + assert!(report.stdout.contains("1 file(s) cached, 0 to fetch")); + } + + #[test] + fn a_file_with_other_bytes_is_corrupt_and_blocks_the_fetch() { + let dir = tempfile::tempdir().unwrap(); + let manifest = manifest( + dir.path(), + "tiny", + "manual", + "Tiny-Q4_K_M.gguf", + b"GGUFright", + ); + let root = dir.path().join("models"); + std::fs::create_dir_all(root.join("tiny")).unwrap(); + std::fs::write(root.join("tiny/Tiny-Q4_K_M.gguf"), b"GGUFwrong").unwrap(); + let report = run_args(&[ + manifest.to_str().unwrap(), + "--cadence", + "manual", + "--root", + root.to_str().unwrap(), + ]); + assert_eq!(report.code, 2); + assert!(report.stdout.contains("corrupt tiny/Tiny-Q4_K_M.gguf")); + assert!(report.stderr.contains("corrupt files must be removed")); + } + + #[test] + fn the_cadence_must_admit_an_artifact() { + let dir = tempfile::tempdir().unwrap(); + let manifest = manifest(dir.path(), "tiny", "nightly", "Tiny-Q4_K_M.gguf", b"GGUF"); + let report = run_args(&[ + manifest.to_str().unwrap(), + "--cadence", + "manual", + "--root", + dir.path().to_str().unwrap(), + "--dry-run", + ]); + assert_eq!(report.code, 2); + assert!(report.stderr.contains("is allowed at cadence manual")); + } + + #[test] + fn options_are_required_and_bounded() { + assert!(run_args(&["m.json"]).stderr.contains("--cadence, --root")); + let report = run_args(&[ + "m.json", + "--cadence", + "manual", + "--root", + "r", + "--timeout-secs", + "0", + ]); + assert!(report.stderr.contains("1 to 86400")); + } +} diff --git a/tools/xtask/src/model_registry/generate.rs b/tools/xtask/src/model_registry/generate.rs index 3ad4521ae8..a5ba96d6f7 100644 --- a/tools/xtask/src/model_registry/generate.rs +++ b/tools/xtask/src/model_registry/generate.rs @@ -33,7 +33,7 @@ pub(super) fn run(root: &Path, args: &[String]) -> CheckReport { let registry = parsed .last("--registry") .map_or_else(|| root.join(REGISTRY), |path| Path::new(path).to_path_buf()); - match expected(®istry) { + match expected(root, ®istry) { Ok(files) if parsed.flag("--check") => check(root, &files), Ok(files) => write(root, &files), Err(error) => CheckReport { @@ -48,12 +48,31 @@ fn io_error(error: &std::io::Error, path: &Path) -> ModelError { ModelError(os_error_text(error, &python_path_display(path))) } -fn expected(registry: &Path) -> Result, ModelError> { +fn expected(root: &Path, registry: &Path) -> Result, ModelError> { let bytes = std::fs::read(registry).map_err(|error| io_error(&error, registry))?; let text = String::from_utf8(bytes).map_err(|error| ModelError(error.to_string()))?; let raw = Json::parse(text.as_bytes()).map_err(|error| ModelError(error.to_string()))?; let digest = hex::encode(Sha256::digest(text.as_bytes())); - outputs(validate(&raw)?, &digest) + let entries = validate(&raw)?; + let missing = super::derived::missing(root, entries)?; + if !missing.is_empty() { + let listed = missing + .iter() + .map(|entry| { + format!( + " {} ({}) {} {}\n", + entry.suites.join(","), + entry.id, + entry.repo, + entry.file + ) + }) + .collect::(); + return Err(ModelError(format!( + "derived suites lack registered artifacts; run `cargo xtool models pin`:\n{listed}" + ))); + } + outputs(entries, &digest) } fn check(root: &Path, files: &[Output]) -> CheckReport { diff --git a/tools/xtask/src/model_registry/manifest.rs b/tools/xtask/src/model_registry/manifest.rs index 9b4d2b558e..c03b6dedfd 100644 --- a/tools/xtask/src/model_registry/manifest.rs +++ b/tools/xtask/src/model_registry/manifest.rs @@ -65,6 +65,24 @@ pub(super) fn resolve<'a>( }) } +/// The ids of every artifact the cadence admits, in manifest order; each is +/// then shaped and pinned by `resolve`. +pub(super) fn admitted_ids<'a>(manifest: &'a Json, cadence: &str) -> ModelResult> { + let artifacts = match manifest.get("artifacts").and_then(Json::as_array) { + Some(artifacts) if !artifacts.is_empty() => artifacts, + _ => return fail("manifest must contain artifacts"), + }; + let rows = artifacts.iter().filter_map(Json::as_object); + Ok(rows + .filter(|row| { + get(row, "cadences") + .and_then(Json::as_array) + .is_some_and(|items| items.iter().any(|item| item.as_str() == Some(cadence))) + }) + .filter_map(|row| nonempty(get(row, "id"))) + .collect()) +} + fn select<'a>(artifacts: &'a [Json], wanted: Option<&str>) -> ModelResult<&'a [(String, Json)]> { let Some(wanted) = wanted else { return match artifacts { diff --git a/tools/xtask/src/model_registry/mod.rs b/tools/xtask/src/model_registry/mod.rs index f49b0261a0..d99371a7cf 100644 --- a/tools/xtask/src/model_registry/mod.rs +++ b/tools/xtask/src/model_registry/mod.rs @@ -3,16 +3,22 @@ //! roster; `resolve` and `restore-inputs` hand consumers exactly one //! cadence-authorized, integrity-pinned artifact. Their established consumer //! formats are retained. `parity-download` owns manual discovery and verified -//! candidate materialization without inline Python. +//! candidate materialization without inline Python. `pin` registers one +//! Hub file with the integrity the Hub reports; `fetch` materializes a +//! suite's cadence-admitted artifacts under one root through the pinned +//! transfer. mod argv; mod certification; +mod derived; mod family_roster; +mod fetch; mod fields; mod generate; pub(crate) mod json_bytes; mod manifest; pub(crate) mod parity_download; +mod pin; mod projection; mod projector_download; mod registry; @@ -26,28 +32,33 @@ use std::path::Path; /// A `models` subcommand. #[derive(Clone, Copy)] pub(crate) enum ModelsCommand { + Fetch, Generate, Resolve, RestoreInputs, ParityDownload, + Pin, ProjectorDownload, } impl ModelsCommand { pub(crate) fn parse(name: &str) -> Option { match name { + "fetch" => Some(Self::Fetch), "generate" => Some(Self::Generate), "resolve" => Some(Self::Resolve), "restore-inputs" => Some(Self::RestoreInputs), "projector-download" => Some(Self::ProjectorDownload), "parity-download" => Some(Self::ParityDownload), + "pin" => Some(Self::Pin), _ => None, } } } -/// `root` is only resolved for `generate`, whose outputs are checkout paths; -/// the resolver takes paths relative to the working directory. +/// `root` is only resolved for `generate` and `pin`, whose registry paths +/// are checkout paths; the resolver takes paths relative to the working +/// directory. pub(crate) fn run( command: ModelsCommand, args: &[String], @@ -57,10 +68,12 @@ pub(crate) fn run( return projector_download::run(args); } let report = match command { + ModelsCommand::Fetch => fetch::run(args), ModelsCommand::Generate => generate::run(Path::new(&root()?), args), ModelsCommand::Resolve => resolve::run(args), ModelsCommand::RestoreInputs => restore_inputs::run(args), ModelsCommand::ParityDownload => parity_download::run(args), + ModelsCommand::Pin => pin::run(Path::new(&root()?), args), ModelsCommand::ProjectorDownload => unreachable!("projector dispatch returned"), }; report.emit() diff --git a/tools/xtask/src/model_registry/pin.rs b/tools/xtask/src/model_registry/pin.rs new file mode 100644 index 0000000000..057bac51ba --- /dev/null +++ b/tools/xtask/src/model_registry/pin.rs @@ -0,0 +1,711 @@ +//! `models pin`: register Hugging Face files as new artifacts. Each revision +//! is resolved to its commit and each file's size and LFS SHA-256 are read +//! from the Hub's tree API over the pinned HTTPS transport, so a row never +//! enters the registry with integrity typed by hand. With no arguments it +//! registers every artifact the registry's `derived_suites` lack (see +//! `derived`); with `@ ` it registers that one file. +//! `models generate` then projects the suites. + +use super::derived::Entry; +use super::fields::{ModelError, ModelResult, fail, get, is_identifier, is_lower_hex}; +use super::json_bytes::{PRETTY, dumps}; +use crate::ci_plan::catalog::{os_error_text, python_path_display}; +use crate::ci_plan::document::Json; +use crate::command_interrupt::Interrupt; +use crate::repository::check_args::Grammar; +use crate::repository::check_report::CheckReport; +use std::path::Path; +use std::time::{Duration, Instant}; + +const PROGRAM: &str = "models pin"; +const GRAMMAR: Grammar = Grammar { + usage: "cargo xtool models pin [@ --id --family + --selector --suite ... --tag ... [--cadence ...] + [--notes ] [--expect-sha256 ]] [--registry ] + [--timeout-secs <1..3600>] [--dry-run]", + values: &[ + "--id", + "--family", + "--selector", + "--suite", + "--tag", + "--cadence", + "--notes", + "--expect-sha256", + "--registry", + "--timeout-secs", + ], + flags: &["--dry-run"], +}; +const DEFAULT_REGISTRY: &str = "ci/model-artifacts/registry.json"; +const DEFAULT_TIMEOUT_SECS: u64 = 600; +const API: &str = "https://huggingface.co/api/models"; +/// A tree listing or a revision document; a model directory is far smaller. +const REPLY_CAP: u64 = 16 * 1024 * 1024; +const SINGLE_OPTIONS: [&str; 7] = [ + "--id", + "--family", + "--selector", + "--suite", + "--tag", + "--cadence", + "--notes", +]; + +struct Request<'a> { + registry: &'a Path, + cadences: Vec<&'a str>, + timeout: Duration, + dry_run: bool, +} + +/// What the Hub reports for one file at one commit. +struct Pinned { + commit: String, + size_bytes: u64, + sha256: String, +} + +pub(super) fn run(root: &Path, args: &[String]) -> CheckReport { + if args.len() == 1 && matches!(args[0].as_str(), "-h" | "--help") { + return CheckReport::success(format!( + "usage: {}\n\nWith no file, registers every artifact the registry's derived_suites lack.\nWith @ , registers that file. Either way each revision\nis resolved to its commit and the file's size and LFS SHA-256 come from the\nHub, the rows are appended to the registry (default {DEFAULT_REGISTRY} under\nthe repository root) and any new suite is declared. Cadence defaults to\nmanual. --dry-run prints the rows instead. Run `models generate` afterwards.\n", + GRAMMAR.usage + )); + } + let parsed = match super::argv::parse(&GRAMMAR, PROGRAM, args) { + Ok(parsed) => parsed, + Err(report) => return report, + }; + let single = !parsed.positionals.is_empty(); + if !single + && let Some(name) = SINGLE_OPTIONS + .iter() + .chain(["--expect-sha256"].iter()) + .find(|name| !parsed.all(name).is_empty()) + { + let message = format!("argument {name}: only with @ "); + return super::argv::usage(&GRAMMAR, PROGRAM, &message); + } + let timeout = match parsed.last("--timeout-secs") { + None => DEFAULT_TIMEOUT_SECS, + Some(text) => match text.parse::() { + Ok(seconds) if (1..=3600).contains(&seconds) => seconds, + _ => { + return super::argv::usage( + &GRAMMAR, + PROGRAM, + "argument --timeout-secs: expected an integer from 1 to 3600", + ); + } + }, + }; + let registry = parsed + .last("--registry") + .map_or_else(|| root.join(DEFAULT_REGISTRY), |path| root.join(path)); + let mut cadences = parsed.all("--cadence"); + if cadences.is_empty() { + cadences.push("manual"); + } + let request = Request { + registry: ®istry, + cadences, + timeout: Duration::from_secs(timeout), + dry_run: parsed.flag("--dry-run"), + }; + let entries = if single { + match single_entry(&parsed) { + Ok(entry) => Some(vec![entry]), + Err(report) => return report, + } + } else { + None + }; + let mut stdout = String::new(); + match pin_into(root, &request, entries, &mut stdout) { + Ok(()) => CheckReport::success(stdout), + Err(error) => CheckReport { + stdout, + stderr: format!("test-model pin error: {error}\n"), + code: 2, + }, + } +} + +/// The one artifact named on the command line. +fn single_entry(parsed: &crate::repository::check_args::ParsedArgs) -> Result { + let required = [ + ("", parsed.positionals.len() < 2), + ("--id", parsed.last("--id").is_none()), + ("--family", parsed.last("--family").is_none()), + ("--selector", parsed.last("--selector").is_none()), + ("--suite", parsed.all("--suite").is_empty()), + ("--tag", parsed.all("--tag").is_empty()), + ]; + let missing = required + .iter() + .filter(|(_, absent)| *absent) + .map(|(name, _)| *name) + .collect::>(); + if !missing.is_empty() { + let message = format!( + "the following arguments are required: {}", + missing.join(", ") + ); + return Err(super::argv::usage(&GRAMMAR, PROGRAM, &message)); + } + if let [_, _, extra @ ..] = parsed.positionals.as_slice() + && !extra.is_empty() + { + let message = format!("unrecognized arguments: {}", extra.join(" ")); + return Err(super::argv::usage(&GRAMMAR, PROGRAM, &message)); + } + let Some((repo, revision)) = parsed.positionals[0].split_once('@') else { + return Err(super::argv::usage( + &GRAMMAR, + PROGRAM, + "argument @: expected owner/name@revision", + )); + }; + let mut tags = parsed + .all("--tag") + .iter() + .map(|tag| (*tag).to_owned()) + .collect::>(); + tags.sort(); + tags.dedup(); + Ok(Entry { + suites: parsed + .all("--suite") + .iter() + .map(|suite| (*suite).to_owned()) + .collect(), + id: parsed.last("--id").unwrap_or_default().to_owned(), + family: parsed.last("--family").unwrap_or_default().to_owned(), + tags, + repo: repo.to_owned(), + revision: revision.to_owned(), + file: parsed.positionals[1].clone(), + selector: parsed.last("--selector").unwrap_or_default().to_owned(), + expected: parsed.last("--expect-sha256").map(str::to_owned), + notes: parsed.last("--notes").map(str::to_owned), + }) +} + +fn pin_into( + root: &Path, + request: &Request<'_>, + entries: Option>, + stdout: &mut String, +) -> ModelResult<()> { + let shown = python_path_display(request.registry); + let bytes = std::fs::read(request.registry).map_err(|error| io_error(&error, &shown))?; + let registry = Json::parse(&bytes).map_err(|error| ModelError(error.to_string()))?; + let object = registry + .as_object() + .ok_or_else(|| ModelError("registry must be an object".to_owned()))?; + let entries = match entries { + Some(entries) => entries, + None => super::derived::missing(root, object)?, + }; + if entries.is_empty() { + stdout.push_str("every derived artifact is registered; nothing to pin\n"); + return Ok(()); + } + validate(request, &entries)?; + let rows = get(object, "artifacts") + .and_then(Json::as_array) + .unwrap_or_default(); + let taken = rows + .iter() + .filter_map(Json::as_object) + .filter_map(|row| get(row, "id").and_then(Json::as_str)) + .find(|id| entries.iter().any(|entry| entry.id == *id)); + if let Some(id) = taken { + return fail(format!("artifact id is already registered: {id}")); + } + let declared = get(object, "cadences") + .and_then(Json::as_array) + .unwrap_or_default(); + if let Some(cadence) = request + .cadences + .iter() + .find(|cadence| !declared.iter().any(|item| item.as_str() == Some(cadence))) + { + return fail(format!("registry does not declare cadence {cadence}")); + } + + let rows = pin_entries(request, &entries, stdout)?; + if request.dry_run { + for row in &rows { + stdout.push_str(&dumps(row, PRETTY)); + stdout.push('\n'); + } + return Ok(()); + } + let suites = entries + .iter() + .flat_map(|entry| entry.suites.iter().map(String::as_str)) + .collect::>(); + let text = dumps(&with_rows(®istry, &suites, rows), PRETTY) + "\n"; + std::fs::write(request.registry, text).map_err(|error| io_error(&error, &shown))?; + stdout.push_str(&format!( + "registered {} artifact(s) in {shown}; run `cargo xtool models generate`\n", + entries.len() + )); + Ok(()) +} + +fn validate(request: &Request<'_>, entries: &[Entry]) -> ModelResult<()> { + let segment = |text: &str| { + !text.is_empty() + && text != "." + && text != ".." + && text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) + }; + if let Some(cadence) = request + .cadences + .iter() + .find(|cadence| !is_identifier(cadence)) + { + return fail(format!("cadence must be a lowercase identifier: {cadence}")); + } + for entry in entries { + match entry.repo.split_once('/') { + Some((owner, name)) if segment(owner) && segment(name) => {} + _ => return fail(format!("repo must be owner/name: {}", entry.repo)), + } + if !segment(&entry.revision) { + return fail(format!("revision is invalid: {}", entry.revision)); + } + if entry.file.is_empty() + || entry.file.starts_with('/') + || entry.file.contains('\\') + || entry.file.split('/').any(|part| !segment(part)) + { + return fail(format!("file path is unsafe: {}", entry.file)); + } + if !is_identifier(&entry.id) { + return fail(format!("id must be a lowercase identifier: {}", entry.id)); + } + if let Some(suite) = entry.suites.iter().find(|suite| !is_identifier(suite)) { + return fail(format!("suite must be a lowercase identifier: {suite}")); + } + if let Some(tag) = entry.tags.iter().find(|tag| !is_identifier(tag)) { + return fail(format!("tag must be a lowercase identifier: {tag}")); + } + for (name, text) in [("family", &entry.family), ("selector", &entry.selector)] { + if text.is_empty() || text.lines().count() != 1 { + return fail(format!("{name} must be a single-line value")); + } + } + if entry + .expected + .as_deref() + .is_some_and(|expected| !is_lower_hex(expected, 64..=64)) + { + return fail("--expect-sha256 must be 64 lowercase hex digits"); + } + } + let mut ids = entries + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(); + ids.sort_unstable(); + if let Some(pair) = ids.windows(2).find(|pair| pair[0] == pair[1]) { + return fail(format!("artifact id is repeated: {}", pair[0])); + } + Ok(()) +} + +/// Every entry's row, with the Hub asked under one interruption scope. +fn pin_entries( + request: &Request<'_>, + entries: &[Entry], + stdout: &mut String, +) -> ModelResult> { + let interrupt = Interrupt::install().map_err(|reason| ModelError(reason.to_string()))?; + let cancellation = interrupt.cancellation(); + let deadline = Instant::now() + request.timeout; + let document = |url: String| -> ModelResult { + let bytes = + super::projector_download::fetch_trusted(&url, deadline, &cancellation, REPLY_CAP) + .map_err(|error| ModelError(format!("{url}: {error}")))?; + Json::parse(&bytes).map_err(|error| ModelError(format!("{url}: {error}"))) + }; + let rows = entries + .iter() + .map(|entry| { + let pinned = pin_file(entry, &document)?; + stdout.push_str(&format!( + "{} {}@{} {} ({} bytes, sha256 {})\n", + entry.id, entry.repo, pinned.commit, entry.file, pinned.size_bytes, pinned.sha256 + )); + Ok(row(entry, &request.cadences, &pinned)) + }) + .collect::>>(); + interrupt + .finish() + .map_err(|_| ModelError("pin interrupted".to_owned()))?; + rows +} + +/// The commit, size and LFS digest the Hub reports, checked against the +/// expected digest when one was given. +fn pin_file(entry: &Entry, document: &dyn Fn(String) -> ModelResult) -> ModelResult { + let commit = if is_lower_hex(&entry.revision, 40..=40) { + entry.revision.clone() + } else { + let info = document(format!("{API}/{}/revision/{}", entry.repo, entry.revision))?; + match info.get("sha").and_then(Json::as_str) { + Some(sha) if is_lower_hex(sha, 40..=40) => sha.to_owned(), + _ => { + return fail(format!( + "{} has no commit for {}", + entry.repo, entry.revision + )); + } + } + }; + let (directory, name) = entry + .file + .rsplit_once('/') + .map_or(("", entry.file.as_str()), |(directory, name)| { + (directory, name) + }); + let listing = document(format!( + "{API}/{}/tree/{commit}{}{directory}", + entry.repo, + if directory.is_empty() { "" } else { "/" } + ))?; + let found = listing + .as_array() + .unwrap_or_default() + .iter() + .filter_map(Json::as_object) + .find(|item| { + get(item, "type").and_then(Json::as_str) == Some("file") + && get(item, "path").and_then(Json::as_str) == Some(entry.file.as_str()) + }); + let Some(found) = found else { + return fail(format!( + "{}@{commit} has no file {name} in {directory:?}", + entry.repo + )); + }; + let Some(lfs) = get(found, "lfs").and_then(Json::as_object) else { + return fail(format!( + "{} is not an LFS object; nothing to pin", + entry.file + )); + }; + let sha256 = match get(lfs, "oid").and_then(Json::as_str) { + Some(oid) if is_lower_hex(oid, 64..=64) => oid.to_owned(), + _ => return fail(format!("{} has no LFS SHA-256", entry.file)), + }; + let size_bytes = get(lfs, "size") + .and_then(Json::as_int) + .and_then(|size| u64::try_from(size).ok()) + .filter(|size| *size > 0) + .ok_or_else(|| ModelError(format!("{} has no LFS size", entry.file)))?; + if let Some(expected) = &entry.expected + && *expected != sha256 + { + return fail(format!( + "{}: expected sha256 {expected}, the Hub reports {sha256}", + entry.file + )); + } + Ok(Pinned { + commit, + size_bytes, + sha256, + }) +} + +fn text(value: &str) -> Json { + Json::String(value.to_owned()) +} + +fn strings<'a>(values: impl Iterator) -> Json { + Json::Array(values.map(text).collect()) +} + +fn row(entry: &Entry, cadences: &[&str], pinned: &Pinned) -> Json { + let file = Json::Object(vec![ + ("path".to_owned(), text(&entry.file)), + ( + "size_bytes".to_owned(), + Json::Number(serde_json::Number::from(pinned.size_bytes)), + ), + ("sha256".to_owned(), text(&pinned.sha256)), + ]); + let artifact = Json::Object(vec![ + ("repo".to_owned(), text(&entry.repo)), + ("revision".to_owned(), text(&pinned.commit)), + ("selector".to_owned(), text(&entry.selector)), + ("files".to_owned(), Json::Array(vec![file])), + ]); + let mut entries = vec![ + ("id".to_owned(), text(&entry.id)), + ("family".to_owned(), text(&entry.family)), + ( + "suites".to_owned(), + strings(entry.suites.iter().map(String::as_str)), + ), + ("cadences".to_owned(), strings(cadences.iter().copied())), + ( + "capability_tags".to_owned(), + strings(entry.tags.iter().map(String::as_str)), + ), + ("artifact".to_owned(), artifact), + ]; + entries.extend( + entry + .notes + .as_deref() + .map(|notes| ("notes".to_owned(), text(notes))), + ); + Json::Object(entries) +} + +/// The registry with `rows` appended and every suite they name declared. +fn with_rows(registry: &Json, suites: &[&str], rows: Vec) -> Json { + let entries = registry.as_object().unwrap_or_default(); + Json::Object( + entries + .iter() + .map(|(key, value)| match (key.as_str(), value) { + ("suites", Json::Array(declared)) => { + let mut added = suites + .iter() + .filter(|suite| !declared.iter().any(|item| item.as_str() == Some(suite))) + .copied() + .collect::>(); + added.dedup(); + ( + key.clone(), + Json::Array( + declared + .iter() + .cloned() + .chain(added.into_iter().map(text)) + .collect(), + ), + ) + } + ("artifacts", Json::Array(existing)) => ( + key.clone(), + Json::Array( + existing + .iter() + .cloned() + .chain(rows.iter().cloned()) + .collect(), + ), + ), + _ => (key.clone(), value.clone()), + }) + .collect(), + ) +} + +fn io_error(error: &std::io::Error, shown: &str) -> ModelError { + ModelError(os_error_text(error, shown)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SMALL: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/models/registry-small.json" + ); + + fn entry(id: &str) -> Entry { + Entry { + suites: vec!["performance-core".to_owned()], + id: id.to_owned(), + family: "tiny".to_owned(), + tags: vec!["dense".to_owned(), "gguf".to_owned()], + repo: "acme/Tiny-GGUF".to_owned(), + revision: "main".to_owned(), + file: "Tiny-Q4_K_M.gguf".to_owned(), + selector: "Q4_K_M".to_owned(), + expected: None, + notes: Some("a note".to_owned()), + } + } + + fn request(registry: &Path) -> Request<'_> { + Request { + registry, + cadences: vec!["manual"], + timeout: Duration::from_secs(1), + dry_run: false, + } + } + + fn owned(args: &[&str]) -> Vec { + args.iter().map(|arg| (*arg).to_owned()).collect() + } + + #[test] + fn the_registry_round_trips_byte_for_byte_before_a_row_is_added() { + let bytes = std::fs::read(SMALL).unwrap(); + let registry = Json::parse(&bytes).unwrap(); + assert_eq!( + dumps(®istry, PRETTY) + "\n", + String::from_utf8(bytes).unwrap() + ); + } + + #[test] + fn a_row_is_appended_and_its_new_suite_declared() { + let bytes = std::fs::read(SMALL).unwrap(); + let registry = Json::parse(&bytes).unwrap(); + let pinned = Pinned { + commit: "0123456789abcdef0123456789abcdef01234567".to_owned(), + size_bytes: 12, + sha256: "ab".repeat(32), + }; + let rows = vec![row(&entry("tiny-q4-perf"), &["manual"], &pinned)]; + let updated = with_rows(®istry, &["performance-core", "performance-core"], rows); + let suites = updated.get("suites").and_then(Json::as_array).unwrap(); + assert_eq!( + suites + .iter() + .filter(|suite| suite.as_str() == Some("performance-core")) + .count(), + 1 + ); + let rows = updated.get("artifacts").and_then(Json::as_array).unwrap(); + let last = rows.last().and_then(Json::as_object).unwrap(); + assert_eq!(get(last, "id").and_then(Json::as_str), Some("tiny-q4-perf")); + assert_eq!( + last.iter().map(|(key, _)| key.as_str()).collect::>(), + [ + "id", + "family", + "suites", + "cadences", + "capability_tags", + "artifact", + "notes" + ] + ); + let files = get(last, "artifact") + .and_then(|artifact| artifact.get("files")) + .and_then(Json::as_array) + .unwrap(); + assert_eq!(files[0].get("size_bytes").and_then(Json::as_int), Some(12)); + assert_eq!( + rows.len(), + registry + .get("artifacts") + .and_then(Json::as_array) + .unwrap() + .len() + + 1 + ); + } + + #[test] + fn the_request_is_validated_before_the_hub_is_asked() { + let registry = Path::new(SMALL); + let bad = |entry: Entry| validate(&request(registry), &[entry]).unwrap_err().0; + assert!(bad(entry("Perf")).contains("lowercase identifier")); + let mut escape = entry("ok"); + escape.file = "../escape.gguf".to_owned(); + assert!(bad(escape).contains("unsafe")); + let mut owner = entry("ok"); + owner.repo = "no-owner".to_owned(); + assert!(bad(owner).contains("owner/name")); + let mut sha = entry("ok"); + sha.expected = Some("abc".to_owned()); + assert!(bad(sha).contains("64 lowercase hex")); + let twice = [entry("ok"), entry("ok")]; + assert!( + validate(&request(registry), &twice) + .unwrap_err() + .0 + .contains("repeated") + ); + assert!(validate(&request(registry), &[entry("ok")]).is_ok()); + } + + #[test] + fn a_taken_id_is_refused_without_a_network_call() { + let bytes = std::fs::read(SMALL).unwrap(); + let first = Json::parse(&bytes).unwrap(); + let id = first.get("artifacts").and_then(Json::as_array).unwrap()[0] + .get("id") + .and_then(Json::as_str) + .unwrap() + .to_owned(); + let mut stdout = String::new(); + let error = pin_into( + Path::new("."), + &request(Path::new(SMALL)), + Some(vec![entry(&id)]), + &mut stdout, + ) + .unwrap_err(); + assert!(error.0.contains("already registered"), "{}", error.0); + } + + #[test] + fn a_registry_without_derived_suites_has_nothing_to_pin() { + let mut stdout = String::new(); + pin_into( + Path::new("."), + &request(Path::new(SMALL)), + None, + &mut stdout, + ) + .unwrap(); + assert!(stdout.contains("nothing to pin")); + } + + #[test] + fn single_mode_options_are_required_and_exclusive() { + let report = run( + Path::new("."), + &owned(&["acme/Tiny-GGUF@main", "Tiny.gguf"]), + ); + assert!( + report + .stderr + .contains("--id, --family, --selector, --suite, --tag") + ); + let complete = [ + "acme/Tiny-GGUF", + "Tiny.gguf", + "--id", + "tiny", + "--family", + "tiny", + "--selector", + "Q4", + "--suite", + "s", + "--tag", + "gguf", + ]; + let report = run(Path::new("."), &owned(&complete)); + assert!( + report.stderr.contains("owner/name@revision"), + "{}", + report.stderr + ); + let report = run(Path::new("."), &owned(&["--suite", "s"])); + assert!( + report.stderr.contains("only with @ "), + "{}", + report.stderr + ); + } +} diff --git a/tools/xtask/src/model_registry/projection.rs b/tools/xtask/src/model_registry/projection.rs index e16f11322e..5a746fe831 100644 --- a/tools/xtask/src/model_registry/projection.rs +++ b/tools/xtask/src/model_registry/projection.rs @@ -25,6 +25,16 @@ const SUITES: [&str; 12] = [ "competitive-benchmark", "radix-cache", ]; +/// Suites projected only once the registry declares them. Historical +/// registries used by retained contract fixtures predate each; a registry +/// admitting one must populate it, and older registries retain exactly +/// their established output set. +const DECLARED_SUITES: [&str; 4] = [ + "skippy-cpp-api", + "performance-core", + "performance-coverage", + "performance-parity", +]; const SUITE_DEFAULT_ARTIFACTS: [(&str, &str); 3] = [ ("product-smoke", "smollm2-q8-inference"), ("scripted-binary-smoke", "smollm2-q8-inference"), @@ -139,18 +149,15 @@ pub(super) fn outputs(registry: &Entries, registry_sha256: &str) -> ModelResult< path: FAMILY_MANIFEST.to_owned(), text: render(registry, &rows)?, }]; - // Historical registries used by retained contract fixtures predate the - // standalone facade. A registry admitting this suite must populate it; - // older registries retain exactly their established output set. - let cpp_api_suite = get(registry, "suites") + let declared = get(registry, "suites") .and_then(Json::as_array) - .is_some_and(|suites| { - suites - .iter() - .any(|suite| suite.as_str() == Some("skippy-cpp-api")) - }) - .then_some("skippy-cpp-api"); - for suite in SUITES.into_iter().chain(cpp_api_suite) { + .unwrap_or_default(); + let declared_suites = DECLARED_SUITES.into_iter().filter(|suite| { + declared + .iter() + .any(|candidate| candidate.as_str() == Some(suite)) + }); + for suite in SUITES.into_iter().chain(declared_suites) { let members = rows .iter() .filter(|row| in_suite(row, suite)) diff --git a/tools/xtask/src/model_registry/projector_download.rs b/tools/xtask/src/model_registry/projector_download.rs index 62170c0e9a..1ea30759be 100644 --- a/tools/xtask/src/model_registry/projector_download.rs +++ b/tools/xtask/src/model_registry/projector_download.rs @@ -65,6 +65,19 @@ pub(super) fn acquire_pinned( ) } +/// A small trusted-host document, such as a Hugging Face API reply. +pub(super) fn fetch_trusted( + input: &str, + deadline: std::time::Instant, + cancellation: &crate::process::Cancellation, + maximum: u64, +) -> DynResult> { + if cancellation.is_cancelled() { + return Err("fetch cancelled before discovery".into()); + } + transfer::fetch_until(input, cancellation, deadline, maximum) +} + pub(super) fn validate_origin(input: &str) -> DynResult<()> { url_policy::trusted(input).map(|_| ()) } diff --git a/tools/xtask/src/model_registry/projector_download/transfer.rs b/tools/xtask/src/model_registry/projector_download/transfer.rs index a1dbdf4584..855f041a69 100644 --- a/tools/xtask/src/model_registry/projector_download/transfer.rs +++ b/tools/xtask/src/model_registry/projector_download/transfer.rs @@ -53,42 +53,43 @@ pub(super) fn download_until( _ => return Err("pinned projector output must be fresh".into()), } } - let mut url = super::url_policy::trusted(input)?; - let curl = crate::curl_https::Curl::discover_for(remaining_until(deadline)?, cancellation)?; let parent = output.parent().ok_or("projector output parent absent")?; std::fs::create_dir_all(parent)?; + with_private_state(parent, |directory| { + let body = complete_body(input, directory, cancellation, deadline, maximum)?; + publish_until(&body, output, maximum, deadline, cancellation, expected) + }) +} + +/// The body of a trusted URL, at most `maximum` bytes, from private state +/// under the current directory: for small documents such as API replies. +pub(super) fn fetch_until( + input: &str, + cancellation: &process::Cancellation, + deadline: Instant, + maximum: u64, +) -> DynResult> { + if !(1..=64 * 1024 * 1024).contains(&maximum) { + return Err("invalid fetch byte cap".into()); + } + let cwd = std::env::current_dir()?; + with_private_state(&cwd, |directory| { + let body = complete_body(input, directory, cancellation, deadline, maximum)?; + super::resolver::bounded_read(&body, maximum) + }) +} + +/// Runs `operation` with a private directory under `parent`, reporting a +/// cleanup failure alongside the operation's own result. +fn with_private_state( + parent: &Path, + operation: impl FnOnce(&Path) -> DynResult, +) -> DynResult { let directory = tempfile::tempdir_in(parent)?; - let result: DynResult = (|| { - for hop in 0..=10 { - let host = url.host_str().ok_or("projector host absent")?; - let addresses = - super::resolver::resolve(host, remaining_until(deadline)?, cancellation)?; - let pin = super::url_policy::pins(host, &addresses)?; - match exchange( - &curl, - &url, - &pin, - directory.path(), - remaining_until(deadline)?, - cancellation, - maximum, - )? { - Reply::Redirect(location) => { - if hop == 10 { - return Err("projector redirect limit exceeded".into()); - } - url = super::url_policy::trusted(url.join(&location)?.as_str())?; - } - Reply::Complete(body) => { - return publish_until(&body, output, maximum, deadline, cancellation, expected); - } - } - } - Err("projector redirect limit exceeded".into()) - })(); + let result = operation(directory.path()); let close = directory.close(); match (result, close) { - (Ok(hash), Ok(())) => Ok(hash), + (Ok(value), Ok(())) => Ok(value), (Err(error), Ok(())) => Err(error), (result, Err(error)) => Err(format!( "projector result {}; private-state cleanup failed: {error}", @@ -100,6 +101,42 @@ pub(super) fn download_until( .into()), } } + +/// Follows up to ten redirects within the trusted hosts and returns the path +/// of the completed body inside `directory`. +fn complete_body( + input: &str, + directory: &Path, + cancellation: &process::Cancellation, + deadline: Instant, + maximum: u64, +) -> DynResult { + let mut url = super::url_policy::trusted(input)?; + let curl = crate::curl_https::Curl::discover_for(remaining_until(deadline)?, cancellation)?; + for hop in 0..=10 { + let host = url.host_str().ok_or("projector host absent")?; + let addresses = super::resolver::resolve(host, remaining_until(deadline)?, cancellation)?; + let pin = super::url_policy::pins(host, &addresses)?; + match exchange( + &curl, + &url, + &pin, + directory, + remaining_until(deadline)?, + cancellation, + maximum, + )? { + Reply::Redirect(location) => { + if hop == 10 { + return Err("projector redirect limit exceeded".into()); + } + url = super::url_policy::trusted(url.join(&location)?.as_str())?; + } + Reply::Complete(body) => return Ok(body), + } + } + Err("projector redirect limit exceeded".into()) +} fn remaining_until(deadline: Instant) -> DynResult { deadline .checked_duration_since(Instant::now()) diff --git a/tools/xtask/src/model_registry/registry.rs b/tools/xtask/src/model_registry/registry.rs index f06460818b..7fbf8f8268 100644 --- a/tools/xtask/src/model_registry/registry.rs +++ b/tools/xtask/src/model_registry/registry.rs @@ -3,7 +3,8 @@ use super::certification::{artifact, certification}; use super::fields::{ - ModelResult, exact_keys, fail, get, has, is_identifier, object, string, string_list, + ModelResult, escapes_root, exact_keys, fail, get, has, is_identifier, object, string, + string_list, }; use crate::ci_plan::document::Json; @@ -14,6 +15,7 @@ const TOP_KEYS: &[&str] = &[ "family_policy", "artifacts", "unverified_consumers", + "derived_suites", ]; const ROW_KEYS: &[&str] = &[ "id", @@ -64,6 +66,7 @@ pub(super) fn validate(raw: &Json) -> ModelResult<&[(String, Json)]> { )?; } unverified_consumers(registry)?; + derived_suites(registry, &declared)?; Ok(registry) } @@ -152,6 +155,39 @@ fn validate_row<'a>( Ok(()) } +/// `derived_suites`: each names a declared suite, a pinned evals model list +/// under the checkout, the selectors to register it at and the id prefix. +fn derived_suites(registry: &[(String, Json)], declared: &Declared<'_>) -> ModelResult<()> { + let items = match get(registry, "derived_suites") { + None => return Ok(()), + Some(value) => match value.as_array() { + Some(items) => items, + None => return fail("registry.derived_suites must be an array"), + }, + }; + for (index, item) in items.iter().enumerate() { + let field = format!("registry.derived_suites[{index}]"); + let item = object(Some(item), &field)?; + exact_keys(item, &["suite", "from", "selectors", "id_prefix"], &field)?; + let suite = string(get(item, "suite"), &format!("{field}.suite"))?; + if suite == FAMILY_SUITE || !declared.suites.contains(&suite) { + return fail(format!("{field}.suite is not a declared non-family suite")); + } + let from = string(get(item, "from"), &format!("{field}.from"))?; + if escapes_root(from) || from.contains('\\') { + return fail(format!("{field}.from must stay inside the checkout")); + } + string_list(get(item, "selectors"), &format!("{field}.selectors"))?; + if !is_identifier(string( + get(item, "id_prefix"), + &format!("{field}.id_prefix"), + )?) { + return fail(format!("{field}.id_prefix has invalid characters")); + } + } + Ok(()) +} + fn unverified_consumers(registry: &[(String, Json)]) -> ModelResult<()> { let items = match get(registry, "unverified_consumers") { None => return Ok(()), diff --git a/tools/xtask/tests/migration_models/generator.rs b/tools/xtask/tests/migration_models/generator.rs index 8a8b1332c3..7b490b0017 100644 --- a/tools/xtask/tests/migration_models/generator.rs +++ b/tools/xtask/tests/migration_models/generator.rs @@ -51,6 +51,80 @@ fn standalone_cpp_api_projection_is_required_when_its_suite_is_admitted() -> Tes Ok(()) } +#[test] +fn derived_suites_refuse_generation_until_every_member_is_pinned() -> TestResult { + // Given: a registry deriving a suite from a one-model list it lacks rows for. + let stage = Stage::new("derived-suite")?; + let list = "evals/models.json"; + stage.write( + list, + br#"[{"key":"tiny-q4-k-m","family":"hybrid-dense","repo":"acme/Tiny-GGUF","revision":"0123456789abcdef0123456789abcdef01234567","files":[{"name":"Tiny-Q4_K_M.gguf","sha256":"3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597"}]}]"#, + )?; + let mut registry: Value = serde_json::from_slice(&small_registry()?)?; + registry["suites"] + .as_array_mut() + .ok_or("suites")? + .push(Value::from("performance-core")); + registry["derived_suites"] = serde_json::json!([{ + "suite": "performance-core", + "from": list, + "selectors": ["Q4_K_M", "BF16"], + "id_prefix": "perf" + }]); + stage.write(REGISTRY, &serde_json::to_vec(®istry)?)?; + let missing = xtask(stage.path(), &["models", "generate"])?; + assert_eq!(missing.status.code(), Some(2)); + let stderr = crate::support::text(&missing.stderr); + assert!(stderr.contains("run `cargo xtool models pin`"), "{stderr}"); + assert!( + stderr.contains("(perf-tiny-q4-k-m) acme/Tiny-GGUF Tiny-Q4_K_M.gguf"), + "{stderr}" + ); + assert!( + stderr.contains("(perf-tiny-bf16) acme/Tiny-GGUF Tiny-BF16.gguf"), + "{stderr}" + ); + + // When: both derived rows are registered, one of them under another file. + let row = |id: &str, file: &str, selector: &str| { + serde_json::json!({ + "id": id, "family": "hybrid-dense", "suites": ["performance-core"], + "cadences": ["manual"], "capability_tags": ["dense", "gguf", "hybrid"], + "artifact": {"repo": "acme/Tiny-GGUF", + "revision": "0123456789abcdef0123456789abcdef01234567", "selector": selector, + "files": [{"path": file, "size_bytes": 12, "sha256": "ab".repeat(32)}]} + }) + }; + let rows = registry["artifacts"].as_array_mut().ok_or("artifacts")?; + rows.push(row("perf-tiny-q4-k-m", "Tiny-Q4_K_M.gguf", "Q4_K_M")); + rows.push(row("perf-tiny-bf16", "Tiny-Q8_0.gguf", "BF16")); + stage.write(REGISTRY, &serde_json::to_vec(®istry)?)?; + let differs = xtask(stage.path(), &["models", "generate"])?; + assert_eq!(differs.status.code(), Some(2)); + assert!( + crate::support::text(&differs.stderr) + .contains("perf-tiny-bf16 is registered as something other than") + ); + + // Then: with the derivation matched, the suite projects. + let rows = registry["artifacts"].as_array_mut().ok_or("artifacts")?; + let last = rows.len() - 1; + rows[last]["artifact"]["files"][0]["path"] = Value::from("Tiny-BF16.gguf"); + stage.write(REGISTRY, &serde_json::to_vec(®istry)?)?; + assert_streams( + "derived suite", + &xtask(stage.path(), &["models", "generate"])?, + 0, + "", + "", + ); + let manifest: Value = + serde_json::from_str(&stage.read("ci/model-artifacts/manifests/performance-core.json")?)?; + assert_eq!(manifest["artifacts"].as_array().map(Vec::len), Some(2)); + assert_eq!(manifest["artifacts"][1]["file"], "Tiny-BF16.gguf"); + Ok(()) +} + /// Applies recorded `{set,value}` / `{delete}` path operations. fn apply(mut registry: Value, ops: &[Value]) -> Result> { for op in ops { @@ -240,7 +314,7 @@ fn migration_models_generator_projects_system_one_suite_in_python_order() -> Tes // Given: the real registry and its checked-in System One manifest. let stage = Stage::new("system-one")?; let root = crate::support::repository_root(); - stage.write(REGISTRY, &std::fs::read(root.join(REGISTRY))?)?; + stage.real_registry(&root)?; let stale = xtask(stage.path(), &["models", "generate", "--check"])?; let stale_names = crate::support::text(&stale.stderr); let preceding = stale_names diff --git a/tools/xtask/tests/migration_models/live.rs b/tools/xtask/tests/migration_models/live.rs index eae8936a01..f055b5e5d2 100644 --- a/tools/xtask/tests/migration_models/live.rs +++ b/tools/xtask/tests/migration_models/live.rs @@ -6,23 +6,35 @@ use crate::support::{Stage, TestResult, assert_streams, fixture_dir, repository_ use serde_json::Value; use std::fs; -const OUTPUTS: [&str; 14] = [ - "ci/llama-canary/family-certified.json", - "ci/model-artifacts/manifests/product-smoke.json", - "ci/model-artifacts/manifests/scripted-binary-smoke.json", - "ci/model-artifacts/manifests/sdk-smoke.json", - "ci/model-artifacts/manifests/hf-download-smoke.json", - "ci/model-artifacts/manifests/openai-smoke.json", - "ci/model-artifacts/manifests/skippy-correctness.json", - "ci/model-artifacts/manifests/safetensors-runtime-smoke.json", - "ci/model-artifacts/manifests/skippy-ci-smoke.json", - "ci/model-artifacts/manifests/skippy-system-one-smoke.json", - "ci/model-artifacts/manifests/skippy-parity.json", - "ci/model-artifacts/manifests/competitive-benchmark.json", - "ci/model-artifacts/manifests/radix-cache.json", - "ci/model-artifacts/manifests/skippy-cpp-api.json", +const FAMILY_ROSTER: &str = "ci/llama-canary/family-certified.json"; +const MANIFESTS: &str = "ci/model-artifacts/manifests"; +/// Suite manifests with a frozen fixture under `fixtures/models/manifests`. +const FROZEN: [&str; 11] = [ + "product-smoke", + "scripted-binary-smoke", + "sdk-smoke", + "hf-download-smoke", + "openai-smoke", + "skippy-correctness", + "safetensors-runtime-smoke", + "skippy-ci-smoke", + "skippy-parity", + "competitive-benchmark", + "radix-cache", ]; +/// The family roster and every checked-in suite manifest, so a suite the +/// registry declares is compared without listing it here. +fn checked_in_outputs() -> Result, Box> { + let mut manifests = fs::read_dir(repository_root().join(MANIFESTS))? + .map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned())) + .collect::, std::io::Error>>()?; + manifests.sort(); + Ok(std::iter::once(FAMILY_ROSTER.to_owned()) + .chain(manifests.iter().map(|name| format!("{MANIFESTS}/{name}"))) + .collect()) +} + #[test] fn migration_models_checked_in_projection_is_current() -> TestResult { // Given/When: the generator checks the real checkout. @@ -34,11 +46,10 @@ fn migration_models_checked_in_projection_is_current() -> TestResult { #[test] fn migration_models_regenerated_real_registry_is_byte_identical() -> TestResult { - // Given: a copy of the real registry and nothing else. + // Given: a copy of the real registry, its derived lists and nothing else. let root = repository_root(); let stage = Stage::new("live")?; - let registry = "ci/model-artifacts/registry.json"; - stage.write(registry, &fs::read(root.join(registry))?)?; + stage.real_registry(&root)?; // When: the generator writes a fresh projection. assert_streams( "regenerate", @@ -48,10 +59,10 @@ fn migration_models_regenerated_real_registry_is_byte_identical() -> TestResult "", ); // Then: every output equals the checked-in bytes. - for path in OUTPUTS { + for path in checked_in_outputs()? { assert_eq!( - stage.read(path)?, - fs::read_to_string(root.join(path))?, + stage.read(&path)?, + fs::read_to_string(root.join(&path))?, "{path}" ); } @@ -62,16 +73,14 @@ fn migration_models_regenerated_real_registry_is_byte_identical() -> TestResult fn migration_models_frozen_manifests_match_the_checkout() -> TestResult { // Given/When: the frozen resolver inputs and the checked-in manifests. let root = repository_root(); - for path in &OUTPUTS[1..] { - let name = path.rsplit('/').next().ok_or("manifest name")?; + for suite in FROZEN { + let name = format!("{suite}.json"); // Then: frozen artifact payloads remain unchanged apart from the // registry digest and Qwen's added System One membership. - if matches!(name, "skippy-system-one-smoke.json" | "skippy-cpp-api.json") { - continue; - } let mut frozen: Value = - serde_json::from_slice(&fs::read(fixture_dir().join("manifests").join(name))?)?; - let mut current: Value = serde_json::from_slice(&fs::read(root.join(path))?)?; + serde_json::from_slice(&fs::read(fixture_dir().join("manifests").join(&name))?)?; + let mut current: Value = + serde_json::from_slice(&fs::read(root.join(MANIFESTS).join(&name))?)?; if name == "product-smoke.json" { current["artifacts"] .as_array_mut() diff --git a/tools/xtask/tests/migration_models/support.rs b/tools/xtask/tests/migration_models/support.rs index 8caf5e5838..01639f9828 100644 --- a/tools/xtask/tests/migration_models/support.rs +++ b/tools/xtask/tests/migration_models/support.rs @@ -84,6 +84,23 @@ impl Stage { Ok(fs::read_to_string(self.0.join(relative))?) } + /// Copies the checkout's registry and every evals model list its + /// derived suites read, so the stage projects like the checkout. + pub(crate) fn real_registry(&self, root: &Path) -> TestResult { + const REGISTRY: &str = "ci/model-artifacts/registry.json"; + let bytes = fs::read(root.join(REGISTRY))?; + let registry: serde_json::Value = serde_json::from_slice(&bytes)?; + let lists = registry["derived_suites"] + .as_array() + .into_iter() + .flatten() + .filter_map(|derived| derived["from"].as_str()); + for list in lists { + self.write(list, &fs::read(root.join(list))?)?; + } + self.write(REGISTRY, &bytes) + } + /// Copies the frozen suite manifests to `manifests/`. pub(crate) fn frozen_manifests(&self) -> TestResult { for entry in fs::read_dir(fixture_dir().join("manifests"))? { diff --git a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs index 2633a41d00..80ae069722 100644 --- a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs +++ b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs @@ -49,7 +49,7 @@ const VALID_SOURCES: [(&str, &[u8], &[u8]); 2] = [ ( "abi", include_bytes!("../../../../skippy/crates/skippy-ffi/src/lib.rs"), - b"0.1.80\n", + b"0.1.83\n", ), ]; diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index cdb6f8b4b6..3d6790813a 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -225,6 +225,7 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( } for target in [ "skippy-asr-decode-boundary", + "skippy-backend-sample-capacity", "skippy-diffusion-host-fallback", "skippy-graph-build-inputs", "skippy-selected-logits", @@ -235,15 +236,18 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( "skippy-sampling-history", "skippy-concurrent-sampling", "skippy-noalloc-graph-planning", + "skippy-recurrent-retention", "skippy-renamed-multishard-planning", "skippy-stage-slice-plan", "skippy-verify-rollback", "test-skippy-kv-cells-contiguous", "test-skippy-kv-page-export", + "test-skippy-kv-rows-aligned", "test-skippy-model-loader-accounting", "test-skippy-recurrent-state-roundtrip", "test-skippy-rerank-template", "test-skippy-sampling-suppress", + "test-skippy-tracing", "test-skippy-verify-checkpoint-retirement", ] { assert!(contains(build, target), "{target}"); @@ -289,10 +293,10 @@ fn replay_metal_selects_cachegen_gate_without_qualifying_device_execution() { let replay = Replay::new(); replay.run(true, false, true, "metal"); let calls = replay.calls(); - assert!(contains( - first(&calls, "cmake", true), - "test-skippy-cachegen-metal" - )); + let build = first(&calls, "cmake", true); + for target in ["test-skippy-cachegen-metal", "test-skippy-tracing-metal"] { + assert!(contains(build, target), "{target}"); + } replay.finish(); } #[test] From 73e72687e00286b7988b75e02be2d5f978bfd0f6 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 33/81] fix(skippy): restore multi-turn checkpoints and span nesting lost in the #2866 merge --- .../skippy-serving/src/frontend/backend.rs | 33 +- .../src/frontend/backend/inference.rs | 6 + .../frontend/embedded_generation/lifecycle.rs | 1 + .../src/frontend/generation/execution.rs | 4 +- .../src/frontend/generation/parsing.rs | 4 + .../src/frontend/generation/types.rs | 7 + .../generation_flow/text_generation.rs | 42 ++- .../frontend/local_generation/decode_step.rs | 5 + .../local_generation/linear_decode.rs | 1 + .../src/frontend/local_generation/tests.rs | 4 + .../tests/cooperative_prefill.rs | 2 + .../local_generation/tests/durable_prefix.rs | 1 + .../local_generation/token_generation.rs | 7 + .../token_generation/cache_prefill.rs | 322 ++++++++++++------ .../skippy-serving/src/frontend/prompting.rs | 154 +++++++-- 15 files changed, 435 insertions(+), 158 deletions(-) diff --git a/skippy/crates/skippy-serving/src/frontend/backend.rs b/skippy/crates/skippy-serving/src/frontend/backend.rs index 982b7bf5aa..04fe4c5465 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend.rs @@ -1,6 +1,7 @@ mod completion_exchange; mod exchange_hooks; mod inference; +mod phase_spans; mod prepared_exchange; #[cfg(test)] mod prepared_exchange_tests; @@ -1033,34 +1034,6 @@ impl StageOpenAiBackend { ); } - pub(super) fn emit_openai_phase( - &self, - name: &str, - timer: PhaseTimer, - mut attrs: BTreeMap, - ) -> f64 { - let elapsed_ms = timer.elapsed_ms(); - attrs.insert("llama_stage.elapsed_ms".to_string(), json!(elapsed_ms)); - let end = now_unix_nanos() as u64; - self.telemetry - .emit_debug_span(name, attrs, timer.start_unix_nanos, end); - elapsed_ms - } - - pub(super) fn emit_openai_summary( - &self, - name: &str, - timer: PhaseTimer, - mut attrs: BTreeMap, - ) -> f64 { - let elapsed_ms = timer.elapsed_ms(); - attrs.insert("llama_stage.elapsed_ms".to_string(), json!(elapsed_ms)); - let end = now_unix_nanos() as u64; - self.telemetry - .emit_span(name, attrs, timer.start_unix_nanos, end); - elapsed_ms - } - pub(super) fn ensure_model(&self, requested: &str) -> InferenceResult<()> { ensure_requested_model(&self.model_id, requested) } @@ -1250,7 +1223,7 @@ impl StageOpenAiBackend { } else { None }; - task::spawn_blocking(move || { + task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { let _session_permit = session_permit; let _permit = permit; let result = backend.generate_text( @@ -1322,7 +1295,7 @@ impl StageOpenAiBackend { let _ = sender.send_terminal(Err(error)); } } - }); + })); Ok(Box::pin(stream::unfold(rx, |mut rx| async { rx.recv().await.map(|item| (item, rx)) }))) diff --git a/skippy/crates/skippy-serving/src/frontend/backend/inference.rs b/skippy/crates/skippy-serving/src/frontend/backend/inference.rs index 933a910b52..7fbf61cef6 100644 --- a/skippy/crates/skippy-serving/src/frontend/backend/inference.rs +++ b/skippy/crates/skippy-serving/src/frontend/backend/inference.rs @@ -46,6 +46,7 @@ impl InferenceBackend for StageOpenAiBackend { &context, ); let request_timer = PhaseTimer::start(); + let _request = self.enter_openai_summary_task(&request_timer); self.chat_completion_with_prepared_hooks_for_exchange( request, None, @@ -60,6 +61,7 @@ impl InferenceBackend for StageOpenAiBackend { let template_options = chat_template_options(&request, &request_defaults)?; let parse_chat_output = chat_output_parser_required(&request, &template_options); let template_timer = PhaseTimer::start(); + let templating = self.enter_openai_phase_task(&template_timer); let prompt = self .prepare_chat_prompt_offloaded( &request, @@ -67,6 +69,7 @@ impl InferenceBackend for StageOpenAiBackend { context.clone(), ) .await?; + drop(templating); let mut template_attrs = self.openai_attrs(&ids); template_attrs.insert( "llama_stage.openai_operation".to_string(), @@ -216,9 +219,11 @@ impl InferenceBackend for StageOpenAiBackend { let parse_chat_output = chat_output_parser_required(&request, &template_options); let emit_reasoning = template_exposes_reasoning(&template_options); let template_timer = PhaseTimer::start(); + let templating = self.enter_openai_phase_task(&template_timer); let prompt = self .prepare_chat_prompt_offloaded(&request, template_options, context.clone()) .await?; + drop(templating); let mut template_attrs = self.openai_attrs(&ids); template_attrs.insert( "llama_stage.openai_operation".to_string(), @@ -302,6 +307,7 @@ impl InferenceBackend for StageOpenAiBackend { &context, ); let request_timer = PhaseTimer::start(); + let _request = self.enter_openai_summary_task(&request_timer); self.ensure_model(&request.model)?; let (request_defaults, defaults_diagnostics) = resolve_completion_request_defaults(&request, &self.request_defaults.snapshot()); diff --git a/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs b/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs index 2d0370f84e..ffb668a50b 100644 --- a/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs +++ b/skippy/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs @@ -423,6 +423,7 @@ impl StageOpenAiBackend { LocalGeneration { prompt_token_ids: request.prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: request.max_tokens, sampling: request.sampling, chat_sampling_metadata: request.chat_sampling_metadata, diff --git a/skippy/crates/skippy-serving/src/frontend/generation/execution.rs b/skippy/crates/skippy-serving/src/frontend/generation/execution.rs index c2f89633a0..bd08c33c29 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/execution.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/execution.rs @@ -34,14 +34,14 @@ where F: FnOnce(skippy_inference_api::CancellationToken) -> T + Send + 'static, P: Send + 'static, { - task::spawn_blocking(move || { + task::spawn_blocking(crate::telemetry::trace_context::propagate(move || { let _permit = permit; let result = work(context.cancellation_token()); // The outer future may have been dropped while native execution was // unwinding. Shared-owner capacity remains held until this point. drop(context); result - }) + })) .await } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/parsing.rs b/skippy/crates/skippy-serving/src/frontend/generation/parsing.rs index 5be7231d37..a7938ccf47 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/parsing.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/parsing.rs @@ -139,6 +139,9 @@ pub(in crate::frontend) struct PreparedGenerationPrompt { /// loaded model and requires the resulting IDs to be an exact prefix of /// `text` before it can be used for recurrent-state caching. pub(in crate::frontend) recurrent_cache_prefix_text: Option, + /// Also only a candidate: generation keeps the token prefix it shares with + /// `text`, which every request with these system messages shares too. + pub(in crate::frontend) recurrent_system_prefix_text: Option, } impl PreparedGenerationPrompt { @@ -148,6 +151,7 @@ impl PreparedGenerationPrompt { media: Vec::new(), chat_parse_metadata: None, recurrent_cache_prefix_text: None, + recurrent_system_prefix_text: None, } } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/types.rs b/skippy/crates/skippy-serving/src/frontend/generation/types.rs index b6b09f547f..bb35b31c28 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/types.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/types.rs @@ -144,6 +144,10 @@ impl InferenceBackendMode { pub(in crate::frontend) struct PhaseTimer { pub(in crate::frontend) start_unix_nanos: u64, pub(in crate::frontend) start_instant: Instant, + /// The phase's span, placed under whatever was active when it started. + /// Entered only through the backend's `enter_openai_*` helpers, which + /// skip phases the telemetry level will not export. + pub(in crate::frontend) frame: crate::telemetry::trace_context::Frame, } impl PhaseTimer { @@ -151,6 +155,7 @@ impl PhaseTimer { Self { start_unix_nanos: now_unix_nanos() as u64, start_instant: Instant::now(), + frame: crate::telemetry::trace_context::Frame::child(), } } @@ -182,6 +187,8 @@ pub(in crate::frontend) struct PreparedTextPrompt { pub(in crate::frontend) struct LocalGeneration<'a> { pub(in crate::frontend) prompt_token_ids: &'a [i32], pub(in crate::frontend) recurrent_cache_prefix_token_ids: Option<&'a [i32]>, + /// Prompt tokens every request with the same system messages shares. + pub(in crate::frontend) shared_system_prefix_tokens: Option, pub(in crate::frontend) max_tokens: u32, pub(in crate::frontend) sampling: &'a SamplingConfig, pub(in crate::frontend) chat_sampling_metadata: Option<&'a str>, diff --git a/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs b/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs index 82f077aa05..b776a5e965 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation_flow/text_generation.rs @@ -7,6 +7,7 @@ use crate::frontend::util::{generation_stop_values, openai_backend_error}; use serde_json::json; use skippy_inference_api::{InferenceError, InferenceResult, generation::GenerationRequest}; use skippy_runtime::{ModelWorkload, SamplingConfig}; +use std::time::Instant; pub(super) fn resident_capacity_target_tokens(prompt_token_count: usize) -> u64 { u64::try_from(prompt_token_count).unwrap_or(u64::MAX) @@ -20,7 +21,9 @@ impl StageOpenAiBackend { ids: &InferenceGenerationIds, ) -> InferenceResult { let tokenize_timer = PhaseTimer::start(); + let tokenizing = self.enter_openai_phase(&tokenize_timer); let token_ids = self.tokenize(&prompt.text)?; + drop(tokenizing); let mut tokenize_attrs = self.openai_attrs(ids); tokenize_attrs.insert( "llama_stage.prompt_chars".to_string(), @@ -149,6 +152,20 @@ impl StageOpenAiBackend { && prefix.len() <= prompt_token_ids.len() && prompt_token_ids.starts_with(prefix) }); + // Also optional: the rendered system prefix ends in an empty user turn, + // so only the tokens it shares with this prompt are the boundary. + let shared_system_prefix_tokens = prompt + .recurrent_system_prefix_text + .as_deref() + .and_then(|prefix| self.tokenize(prefix).ok()) + .map(|prefix| { + prefix + .iter() + .zip(&prompt_token_ids) + .take_while(|(system_token, prompt_token)| system_token == prompt_token) + .count() + }) + .filter(|&tokens| tokens > 0 && tokens < prompt_token_ids.len()); if cancellation.is_some_and(skippy_inference_api::CancellationToken::is_cancelled) { return Err(InferenceError::backend("request cancelled")); } @@ -232,11 +249,20 @@ impl StageOpenAiBackend { )); } + // Work on this thread from here on belongs to the generation span, + // which `stage.openai_generation_summary` closes below. + let _generation = self.enter_openai_summary(&generation_timer); + let mut first_token_at = None; + let mut push_token = |token: i32| { + first_token_at.get_or_insert_with(Instant::now); + collector.push_token(token) + }; let cache_stats = match self.mode.clone() { InferenceBackendMode::LocalRuntime => self.generate_local_tokens( LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: recurrent_cache_prefix_token_ids.as_deref(), + shared_system_prefix_tokens, max_tokens, sampling: &sampling, chat_sampling_metadata, @@ -248,7 +274,7 @@ impl StageOpenAiBackend { cancellation, ids: &ids, }, - |token| collector.push_token(token), + &mut push_token, )?, InferenceBackendMode::EmbeddedStageZero { config, @@ -325,7 +351,7 @@ impl StageOpenAiBackend { cancellation, ids: &ids, }, - |token| collector.push_token(token), + &mut push_token, )? } }; @@ -340,6 +366,18 @@ impl StageOpenAiBackend { "llama_stage.completion_token_count".to_string(), json!(output.completion_tokens), ); + // Offset from this span's start, so a reader can place it absolutely. + if let Some(first_token_at) = first_token_at { + summary_attrs.insert( + "llama_stage.first_token_ms".to_string(), + json!( + first_token_at + .duration_since(generation_timer.start_instant) + .as_secs_f64() + * 1000.0 + ), + ); + } summary_attrs.insert("skippy.kv.status".to_string(), json!(output.cache_status)); summary_attrs.insert( "skippy.kv.cached_prompt_tokens".to_string(), diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/decode_step.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/decode_step.rs index 962e689bf2..2f14e9c6a3 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/decode_step.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/decode_step.rs @@ -32,6 +32,10 @@ impl StageOpenAiBackend { ) -> InferenceResult { let decode_step = state.decoded_tokens; let token_timer = PhaseTimer::start(); + let decoding = state + .emit_token_debug + .then(|| self.enter_openai_phase(&token_timer)) + .flatten(); let decode_call_timer = PhaseTimer::start(); let ( predicted, @@ -173,6 +177,7 @@ impl StageOpenAiBackend { if let Some(committed_token_ids) = state.linear_context_tokens.as_mut() { committed_token_ids.push(state.current); } + drop(decoding); if state.emit_token_debug { let mut token_attrs = self.openai_attrs(request.ids); token_attrs.insert("llama_stage.decode_step".to_string(), json!(decode_step)); diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs index 40548656c5..74f49abb13 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs @@ -469,6 +469,7 @@ mod tests { let request = LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 5, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs index eaf393a3a2..1b6045329b 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -301,6 +301,7 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &first_prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 2, sampling: &sampling, chat_sampling_metadata: None, @@ -362,6 +363,7 @@ fn recurrent_post_decode_checkpoint_reuses_a_growing_prompt() -> Result<()> { LocalGeneration { prompt_token_ids: &second_prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -740,6 +742,7 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, @@ -795,6 +798,7 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error LocalGeneration { prompt_token_ids: &prompt_token_ids, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs index d617ede612..0f4f69a59f 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/cooperative_prefill.rs @@ -56,6 +56,7 @@ fn prefill_only_resident_recurrent_request_retains_shared_grid_checkpoint() -> R LocalGeneration { prompt_token_ids: &tokens, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 0, sampling: &sampling, chat_sampling_metadata: None, @@ -136,6 +137,7 @@ fn resident_checkpoint_prefill_yields_to_decode_and_cancels_without_losing_check LocalGeneration { prompt_token_ids: &worker_prompt, recurrent_cache_prefix_token_ids: Some(&worker_prompt[..64]), + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index a4a62de004..4e6a73fd70 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -159,6 +159,7 @@ fn failed_long_l3_import_rolls_back_then_reuses_the_short_native_owner() -> Resu LocalGeneration { prompt_token_ids: &prompt, recurrent_cache_prefix_token_ids: None, + shared_system_prefix_tokens: None, max_tokens: 1, sampling: &sampling, chat_sampling_metadata: None, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index eee0edc7bb..64c4ee5da5 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -557,6 +557,8 @@ impl StageOpenAiBackend { emit_token: &mut impl FnMut(i32) -> InferenceResult, ) -> InferenceResult { let timer = PhaseTimer::start(); + // The scheduler links its iterations to this phase. + let generating = self.enter_openai_phase(&timer); let stats = self.iteration_scheduler.generate( ScheduledGenerationRequest { id: session_id, @@ -568,6 +570,7 @@ impl StageOpenAiBackend { }, emit_token, )?; + drop(generating); cache_stats.suffix_prefill_tokens = saturating_u32(request.prompt_token_ids.len()); cache_stats.prompt_ms = stats.prompt_ms; cache_stats.predicted_ms = stats.predicted_ms; @@ -706,6 +709,7 @@ impl StageOpenAiBackend { cache_stats: &mut GenerationCacheStats, ) -> InferenceResult> { let prefill_timer = PhaseTimer::start(); + let _prefill = self.enter_openai_phase(&prefill_timer); let runtime_sessions_before = self .iteration_scheduler .execute_runtime("feature-prefill-stats-before", |runtime| { @@ -928,6 +932,7 @@ impl StageOpenAiBackend { emit_token: &mut impl FnMut(i32) -> InferenceResult, ) -> InferenceResult { let decode_timer = PhaseTimer::start(); + let decoding = self.enter_openai_summary(&decode_timer); let mut state = self.prepare_decode_state(request, session_id, prompt_prefill_sample, emit_token)?; let recurrent_checkpoint_required = self @@ -962,6 +967,7 @@ impl StageOpenAiBackend { }, )?; cache_stats.predicted_ms = stats.predicted_ms; + drop(decoding); let model_generation_elapsed = self.emit_decode_summary(request, &mut state, cache_stats, decode_timer)?; if state.generated_token_ids.len() > 1 { @@ -1037,6 +1043,7 @@ impl StageOpenAiBackend { break; } } + drop(decoding); let model_generation_elapsed = self.emit_decode_summary(request, &mut state, cache_stats, decode_timer)?; // The first-token checkpoint names the prompt boundary. Avoid diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index d58c070b41..bee7b81b4f 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -19,22 +19,63 @@ fn deferred_suffix_split( (suffix_start, checkpoint) } -/// Pick the deferred-prefill checkpoint boundary. A valid EXPLICIT chat -/// boundary wins: it is the reusable message-history prefix a follow-up -/// request shares token-for-token, so it is the checkpoint most likely to be -/// on a future request's path. The shared-grid checkpoint is the fallback for -/// absent, invalid, or already-restored chat boundaries. -fn select_deferred_checkpoint_boundary( - shared_checkpoint: Option, - chat_checkpoint: Option, +/// The boundaries a deferred prefill checkpoints, in prompt order. +/// +/// Recurrent state resumes only at a checkpoint that is a whole prefix of the +/// request, so each kind serves requests the others cannot: the chat boundary +/// the next turn of the same conversation, the system boundary any request +/// with the same system messages, and the shared grid a request sharing an +/// earlier part without message boundaries. Every distinct one is kept. A +/// boundary the cache would not record, being shorter than `min_tokens`, is not +/// worth splitting the prefill for. Candidates earlier in the list name a +/// boundary they share. +fn deferred_checkpoint_boundaries( + candidates: [(Option, DeferredCheckpointKind); 3], restored_prefill_tokens: usize, prompt_token_count: usize, -) -> Option { - let valid = - |boundary: &usize| *boundary > restored_prefill_tokens && *boundary < prompt_token_count; - chat_checkpoint - .filter(valid) - .or_else(|| shared_checkpoint.filter(valid)) + min_tokens: u64, +) -> Vec<(usize, DeferredCheckpointKind)> { + let valid = |boundary: &usize| { + *boundary > restored_prefill_tokens + && *boundary < prompt_token_count + && u64::try_from(*boundary).unwrap_or(u64::MAX) >= min_tokens + }; + let mut boundaries: Vec<_> = candidates + .into_iter() + .filter_map(|(boundary, kind)| boundary.filter(valid).map(|boundary| (boundary, kind))) + .collect(); + boundaries.sort_by_key(|&(boundary, _)| boundary); + boundaries.dedup_by_key(|&mut (boundary, _)| boundary); + boundaries +} + +/// The boundary a deferred prefill exports its recurrent state at. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DeferredCheckpointKind { + /// The message history before the assistant turn. + ChatPrefix, + /// The system messages, up to where the first user's text begins. + SystemPrefix, + /// The stride grid's boundary before the prompt's tail. + SharedGrid, +} + +impl DeferredCheckpointKind { + fn as_str(self) -> &'static str { + match self { + Self::ChatPrefix => "chat_prefix", + Self::SystemPrefix => "system_prefix", + Self::SharedGrid => "shared_grid", + } + } + + fn decision_prefix(self) -> &'static str { + match self { + Self::ChatPrefix => "chat_prefix_checkpoint", + Self::SystemPrefix => "system_prefix_checkpoint", + Self::SharedGrid => "shared_prefill_checkpoint", + } + } } impl StageOpenAiBackend { @@ -45,6 +86,7 @@ impl StageOpenAiBackend { cache_stats: &mut GenerationCacheStats, ) -> InferenceResult> { let prefill_timer = PhaseTimer::start(); + let prefilling = self.enter_openai_phase(&prefill_timer); let prefill_tokens = Arc::<[i32]>::from(&request.prompt_token_ids[..request.prompt_token_ids.len() - 1]); let recurrent_cache_prefix_token_ids = request @@ -157,24 +199,32 @@ impl StageOpenAiBackend { .kv .as_ref() .is_some_and(|kv| kv.retains_recurrent_checkpoints()); - let checkpoint = exact_state - .then(|| { - self.deferred_exact_checkpoint_identity( - request, - session_id, - &prefill_tokens, - restored_prefill_tokens, - ) - }) - .flatten(); - let (mut suffix_start, checkpoint_boundary) = deferred_suffix_split( + let checkpoints = if exact_state { + self.deferred_exact_checkpoints( + request, + session_id, + &prefill_tokens, + restored_prefill_tokens, + ) + } else { + Vec::new() + }; + let (mut suffix_start, _) = deferred_suffix_split( restored_prefill_tokens, request.prompt_token_ids.len(), - checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()), + None, ); - if exact_state && let Some(boundary) = checkpoint_boundary { + let mut checkpoint_chunks = 0usize; + for (checkpoint, kind) in checkpoints { + let Some(boundary) = deferred_suffix_split( + suffix_start, + request.prompt_token_ids.len(), + usize::try_from(checkpoint.identity.token_count).ok(), + ) + .1 + else { + continue; + }; let checkpoint_prefill = self.prefill_suffix( session_id, &request.prompt_token_ids[suffix_start..boundary], @@ -183,9 +233,8 @@ impl StageOpenAiBackend { cache_operation_deadline, request.cancellation, )?; - prefill_chunk_count = prefill_chunk_count - .saturating_add(checkpoint_prefill.chunk_count) - .saturating_sub(1); + checkpoint_chunks = + checkpoint_chunks.saturating_add(checkpoint_prefill.chunk_count); scheduler_batch_size_max = scheduler_batch_size_max.max(checkpoint_prefill.max_batch_size); runtime_lock_wait_ms += checkpoint_prefill.runtime_lock_wait_ms; @@ -197,7 +246,7 @@ impl StageOpenAiBackend { session_id, request.ids, request.prompt_token_ids[..boundary].to_vec(), - "shared_prefill_checkpoint", + kind.decision_prefix(), true, ) { record.resident_enqueued_checkpoints = @@ -221,11 +270,7 @@ impl StageOpenAiBackend { } else { None }; - prefill_chunk_count = if prefill_chunk_count == 1 { - suffix_outcome.chunk_count - } else { - prefill_chunk_count.saturating_add(suffix_outcome.chunk_count) - }; + prefill_chunk_count = checkpoint_chunks.saturating_add(suffix_outcome.chunk_count); scheduler_batch_size_max = scheduler_batch_size_max.max(suffix_outcome.max_batch_size); runtime_lock_wait_ms += suffix_outcome.runtime_lock_wait_ms; runtime_lock_hold_ms += suffix_outcome.runtime_lock_hold_ms; @@ -363,6 +408,7 @@ impl StageOpenAiBackend { .as_ref() .expect("debug session snapshot collected"), ); + drop(prefilling); self.emit_openai_phase("stage.openai_prefill", prefill_timer, attrs); } self.telemetry.emit( @@ -388,21 +434,25 @@ impl StageOpenAiBackend { Ok(prompt_prefill_sample) } - fn deferred_exact_checkpoint_identity( + /// The recurrent checkpoints a deferred prefill exports, in prompt order. + fn deferred_exact_checkpoints( &self, request: &LocalGeneration<'_>, session_id: &str, prefill_tokens: &[i32], restored_prefill_tokens: usize, - ) -> Option { - let kv = self + ) -> Vec<(PrefillKvIdentity, DeferredCheckpointKind)> { + let Some(kv) = self .kv .as_ref() - .filter(|kv| kv.retains_recurrent_checkpoints())?; + .filter(|kv| kv.retains_recurrent_checkpoints()) + else { + return Vec::new(); + }; let base = self.local_kv_message_base(session_id, request.ids); - let shared_checkpoint = + let mut shared_checkpoint = kv.exact_shared_checkpoint_identity(&self.config, &base, 0, prefill_tokens); - let chat_checkpoint = request + let mut chat_checkpoint = request .recurrent_cache_prefix_token_ids .filter(|checkpoint_tokens| { !checkpoint_tokens.is_empty() @@ -412,23 +462,70 @@ impl StageOpenAiBackend { .map(|checkpoint_tokens| { kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens) }); - let shared_boundary = shared_checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); - let chat_boundary = chat_checkpoint - .as_ref() - .and_then(|identity| usize::try_from(identity.identity.token_count).ok()); - let selected_boundary = select_deferred_checkpoint_boundary( - shared_boundary, - chat_boundary, + let mut system_checkpoint = request + .shared_system_prefix_tokens + .and_then(|tokens| prefill_tokens.get(..tokens)) + .map(|checkpoint_tokens| { + kv.prefill_identity(&self.config, &base, 0, checkpoint_tokens) + }); + let boundary_of = |checkpoint: &Option| { + checkpoint + .as_ref() + .and_then(|identity| usize::try_from(identity.identity.token_count).ok()) + }; + let shared_boundary = boundary_of(&shared_checkpoint); + let chat_boundary = boundary_of(&chat_checkpoint); + let system_boundary = boundary_of(&system_checkpoint); + let prompt_tokens = prefill_tokens.len().saturating_add(1); + let boundaries = deferred_checkpoint_boundaries( + [ + (chat_boundary, DeferredCheckpointKind::ChatPrefix), + (system_boundary, DeferredCheckpointKind::SystemPrefix), + (shared_boundary, DeferredCheckpointKind::SharedGrid), + ], restored_prefill_tokens, - prefill_tokens.len().saturating_add(1), + prompt_tokens, + kv.checkpoint_policy.min_tokens, ); - if selected_boundary == shared_boundary { - shared_checkpoint - } else { - chat_checkpoint + if self.telemetry.is_debug_enabled() { + let mut attrs = self.openai_attrs(request.ids); + attrs.insert( + "skippy.kv.decision".to_string(), + json!("checkpoint_boundary"), + ); + attrs.insert("skippy.kv.prompt_tokens".to_string(), json!(prompt_tokens)); + attrs.insert( + "skippy.kv.restored_prefill_tokens".to_string(), + json!(restored_prefill_tokens), + ); + attrs.insert( + "skippy.kv.chat_checkpoint_tokens".to_string(), + json!(chat_boundary), + ); + attrs.insert( + "skippy.kv.shared_checkpoint_tokens".to_string(), + json!(shared_boundary), + ); + attrs.insert( + "skippy.kv.system_checkpoint_tokens".to_string(), + json!(system_boundary), + ); + let kinds: Vec<_> = boundaries.iter().map(|&(_, kind)| kind.as_str()).collect(); + attrs.insert("skippy.kv.checkpoint_kinds".to_string(), json!(kinds)); + self.telemetry + .emit_debug("stage.openai_kv_record_decision", attrs); } + boundaries + .into_iter() + .filter_map(|(_, kind)| { + match kind { + DeferredCheckpointKind::ChatPrefix => chat_checkpoint.take(), + DeferredCheckpointKind::SystemPrefix => system_checkpoint.take(), + DeferredCheckpointKind::SharedGrid => shared_checkpoint.take(), + } + .map(|identity| (identity, kind)) + }) + .collect() } #[allow(clippy::too_many_arguments)] @@ -692,47 +789,78 @@ fn deferred_suffix_split_respects_restore_and_prompt_boundaries() { #[cfg(test)] #[test] -fn deferred_checkpoint_prefers_chat_boundary_with_shared_grid_fallback() { +fn deferred_checkpoints_keep_every_distinct_boundary_in_prompt_order() { + use DeferredCheckpointKind::{ChatPrefix, SharedGrid, SystemPrefix}; let prompt = 10; - // Both valid: the explicit chat boundary wins over the shared grid. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(6), 0, prompt), - Some(6) - ); - // Chat absent or None: shared grid is the fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), None, 0, prompt), - Some(8) - ); - // Chat already restored (equal to the restored prefix): shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(4), 4, prompt), - Some(8) - ); - // Chat at the prompt end: invalid, shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(10), 0, prompt), - Some(8) - ); - // Chat beyond the prompt: invalid, shared fallback. - assert_eq!( - select_deferred_checkpoint_boundary(Some(8), Some(99), 0, prompt), - Some(8) - ); - // Shared already restored but chat valid: chat wins. - assert_eq!( - select_deferred_checkpoint_boundary(Some(4), Some(6), 4, prompt), - Some(6) - ); - // Both invalid: nothing selected. - assert_eq!( - select_deferred_checkpoint_boundary(Some(4), Some(10), 4, prompt), - None - ); - // Neither candidate exists: nothing selected. + for (chat, system, shared, restored, expected) in [ + // The next turn needs the chat boundary, a new conversation with the + // same system messages the system boundary, and others the grid. + ( + Some(8), + Some(3), + Some(4), + 0, + vec![(3, SystemPrefix), (4, SharedGrid), (8, ChatPrefix)], + ), + ( + Some(6), + None, + Some(8), + 0, + vec![(6, ChatPrefix), (8, SharedGrid)], + ), + // A shared boundary is exported once, named by the earlier candidate. + (Some(6), None, Some(6), 0, vec![(6, ChatPrefix)]), + ( + Some(8), + Some(4), + Some(4), + 0, + vec![(4, SystemPrefix), (8, ChatPrefix)], + ), + (None, None, Some(8), 0, vec![(8, SharedGrid)]), + (Some(6), None, None, 0, vec![(6, ChatPrefix)]), + // Restored, at the prompt end, or beyond it: not exported. + (Some(4), Some(3), Some(8), 4, vec![(8, SharedGrid)]), + (Some(6), None, Some(4), 4, vec![(6, ChatPrefix)]), + (Some(10), None, Some(8), 0, vec![(8, SharedGrid)]), + (Some(99), None, Some(8), 0, vec![(8, SharedGrid)]), + (Some(10), None, Some(4), 4, vec![]), + (None, None, None, 0, vec![]), + ] { + assert_eq!( + deferred_checkpoint_boundaries( + [ + (chat, ChatPrefix), + (system, SystemPrefix), + (shared, SharedGrid) + ], + restored, + prompt, + 0, + ), + expected, + "chat {chat:?} system {system:?} shared {shared:?} restored {restored}" + ); + } +} + +#[cfg(test)] +#[test] +fn deferred_checkpoints_skip_boundaries_the_cache_would_not_record() { + use DeferredCheckpointKind::{ChatPrefix, SharedGrid, SystemPrefix}; assert_eq!( - select_deferred_checkpoint_boundary(None, None, 0, prompt), - None + deferred_checkpoint_boundaries( + [ + (Some(300), ChatPrefix), + (Some(40), SystemPrefix), + (Some(256), SharedGrid) + ], + 0, + 400, + 256, + ), + vec![(256, SharedGrid), (300, ChatPrefix)] ); } diff --git a/skippy/crates/skippy-serving/src/frontend/prompting.rs b/skippy/crates/skippy-serving/src/frontend/prompting.rs index 936101eaf8..9514904097 100644 --- a/skippy/crates/skippy-serving/src/frontend/prompting.rs +++ b/skippy/crates/skippy-serving/src/frontend/prompting.rs @@ -13,10 +13,12 @@ use crate::frontend::tool_emulation; use crate::frontend::util::openai_backend_error; use crate::runtime_state::panic_recovery::lock_runtime; use serde_json::Value; +use skippy_inference_api::ChatMessage; use skippy_inference_api::GenerationHookSignals; use skippy_inference_api::InferenceError; use skippy_inference_api::InferenceRequestContext; use skippy_inference_api::InferenceResult; +use skippy_inference_api::MessageContent; use skippy_inference_api::PrefillHookSignals; use skippy_inference_api::apply_chat_hook_outcome; use skippy_inference_api::chat_skippy_hooks_enabled; @@ -26,6 +28,7 @@ use skippy_runtime::ChatTemplateOptions; use skippy_runtime::GenerationSignalWindow; use skippy_runtime::MediaInput; use skippy_runtime::TokenSignal; +use std::collections::BTreeMap; /// Output of a single chat-template application, before it is folded into a /// [`PreparedGenerationPrompt`]. @@ -86,52 +89,88 @@ impl StageOpenAiBackend { tool_emulation::rewrite_history_for_emulation(&request.messages, &instruction); let emulated = self.render_chat_prompt(request, &options, &marker, Some(&rewritten), false)?; - let recurrent_cache_prefix_text = if self - .kv - .as_ref() - .is_some_and(|kv| kv.retains_recurrent_checkpoints()) - && emulated.media.is_empty() - && options.add_assistant + let (recurrent_cache_prefix_text, recurrent_system_prefix_text) = if self + .renders_recurrent_checkpoints(&options, &emulated) { - let mut prefix_options = options.clone(); - prefix_options.add_assistant = false; - self.render_chat_prompt(request, &prefix_options, &marker, Some(&rewritten), false) - .ok() - .map(|rendered| rendered.prompt) + ( + self.render_chat_prefix(request, &options, &marker, Some(&rewritten), false), + self.render_system_prefix(request, &options, &marker, &rewritten, false), + ) } else { - None + (None, None) }; return Ok(PreparedGenerationPrompt { text: emulated.prompt, media: emulated.media, chat_parse_metadata: Some(emulated.metadata_json), recurrent_cache_prefix_text, + recurrent_system_prefix_text, }); } - let recurrent_cache_prefix_text = if self - .kv - .as_ref() - .is_some_and(|kv| kv.retains_recurrent_checkpoints()) - && native.media.is_empty() - && options.add_assistant - { - let mut prefix_options = options.clone(); - prefix_options.add_assistant = false; - self.render_chat_prompt(request, &prefix_options, &marker, None, true) - .ok() - .map(|rendered| rendered.prompt) - } else { - None - }; + let (recurrent_cache_prefix_text, recurrent_system_prefix_text) = + if self.renders_recurrent_checkpoints(&options, &native) { + ( + self.render_chat_prefix(request, &options, &marker, None, true), + self.render_system_prefix(request, &options, &marker, &request.messages, true), + ) + } else { + (None, None) + }; Ok(PreparedGenerationPrompt { text: native.prompt, media: native.media, chat_parse_metadata: Some(native.metadata_json), recurrent_cache_prefix_text, + recurrent_system_prefix_text, }) } + /// Recurrent checkpoints resume at rendered message boundaries, so a + /// text-only prompt that asks for an assistant turn renders its candidates. + fn renders_recurrent_checkpoints( + &self, + options: &ChatTemplateOptions, + rendered: &RenderedChatPrompt, + ) -> bool { + rendered.media.is_empty() + && options.add_assistant + && self + .kv + .as_ref() + .is_some_and(|kv| kv.retains_recurrent_checkpoints()) + } + + /// The messages without the assistant-generation suffix. + fn render_chat_prefix( + &self, + request: &GenerationRequest, + options: &ChatTemplateOptions, + marker: &str, + messages: Option<&[ChatMessage]>, + include_tools: bool, + ) -> Option { + let mut prefix_options = options.clone(); + prefix_options.add_assistant = false; + self.render_chat_prompt(request, &prefix_options, marker, messages, include_tools) + .ok() + .map(|rendered| rendered.prompt) + } + + /// The leading system messages and an empty user turn, without the + /// assistant-generation suffix. + fn render_system_prefix( + &self, + request: &GenerationRequest, + options: &ChatTemplateOptions, + marker: &str, + messages: &[ChatMessage], + include_tools: bool, + ) -> Option { + let prefix = system_prefix_messages(messages)?; + self.render_chat_prefix(request, options, marker, Some(&prefix), include_tools) + } + /// Applies the chat template for the given messages. When `messages` is /// `None`, the request's own messages are used. When `include_tools` is /// false, `tools`/`tool_choice` are omitted (used by the emulation path). @@ -416,3 +455,64 @@ pub(super) fn parse_emulated_chat_output( tool_calls, }) } + +/// The leading system and developer messages and an empty user turn, when the +/// conversation has both. Every request with those system messages renders the +/// same tokens up to where the user's text begins. +fn system_prefix_messages(messages: &[ChatMessage]) -> Option> { + let system = messages + .iter() + .take_while(|message| matches!(message.role.as_str(), "system" | "developer")) + .count(); + (system > 0 && system < messages.len()).then(|| { + let user = ChatMessage { + role: "user".to_string(), + content: Some(MessageContent::Text(String::new())), + extra: BTreeMap::new(), + }; + messages[..system] + .iter() + .cloned() + .chain(std::iter::once(user)) + .collect() + }) +} + +#[cfg(test)] +mod system_prefix_tests { + use super::*; + + fn message(role: &str, text: &str) -> ChatMessage { + ChatMessage { + role: role.to_string(), + content: Some(MessageContent::Text(text.to_string())), + extra: BTreeMap::new(), + } + } + + #[test] + fn system_messages_are_followed_by_an_empty_user_turn() { + let conversation = [ + message("system", "rules"), + message("developer", "tools"), + message("user", "first question"), + message("assistant", "answer"), + message("user", "second question"), + ]; + assert_eq!( + system_prefix_messages(&conversation), + Some(vec![ + message("system", "rules"), + message("developer", "tools"), + message("user", ""), + ]) + ); + } + + #[test] + fn conversations_without_both_parts_have_no_system_prefix() { + assert_eq!(system_prefix_messages(&[message("user", "question")]), None); + assert_eq!(system_prefix_messages(&[message("system", "rules")]), None); + assert_eq!(system_prefix_messages(&[]), None); + } +} From 2ab38ae7b20acd4f936700fea4b005a66b300ae0 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 34/81] perf(skippy): place each request's share of a batch together in the KV pool --- .../skippy-api/src/split-certified.json | 2 +- ...-request-s-share-of-a-batch-together.patch | 488 ++++++++++++++++++ skippy/scripts/build-llama.sh | 1 + .../full_replay.rs | 1 + 4 files changed, 491 insertions(+), 1 deletion(-) create mode 100644 skippy/llama_cpp/patches/0033-llama-place-each-request-s-share-of-a-batch-together.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index ef4648db09..bbccf34220 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "372dc5ca157276beb6c67b2e92477e8d662e964a", "skippy_abi": "0.1.83", - "patch_queue_sha256": "5655d47e336cc179fcf10f20ee3e37caf07d0ffa23505fa43cda85846e291a75" + "patch_queue_sha256": "956a11c1cede8acef2ce46b4ed6d5de0034b5c45fe2bc511cb40969b11edc6f3" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0033-llama-place-each-request-s-share-of-a-batch-together.patch b/skippy/llama_cpp/patches/0033-llama-place-each-request-s-share-of-a-batch-together.patch new file mode 100644 index 0000000000..e58525eb91 --- /dev/null +++ b/skippy/llama_cpp/patches/0033-llama-place-each-request-s-share-of-a-batch-together.patch @@ -0,0 +1,488 @@ +From cb4788c49b0880370b68cba50abeb477b72b3367 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Thu, 12 Nov 2026 08:42:32 +1100 +Subject: [PATCH 33/33] llama: place each request's share of a batch together + in the KV pool + +The unified pool placed one token at a time: a sequence continued after its +highest cell while that stayed inside a 64-cell chunk, and otherwise opened +the next all-empty chunk. + +A request that resumes a cached prompt takes over cells that can sit above the +ones it writes next. Its highest cell then never moves, the cell after it is +taken, and every generated token opens a chunk of its own: 128 tokens became +about 128 one-cell runs spread over 128 chunks, each padded to a 32-row block +in the row lists the attention kernels read. + +Placement now works per sequence over the whole ubatch +(llama_kv_cells::place_together): the share continues after the sequence's +latest token, wherever that cell is, and the rest goes to the smallest free +stretch that holds it, sized in whole chunks so the sequence can keep growing +there. When no stretch is large enough the longest ones are filled first. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + src/llama-kv-cache.cpp | 81 ++-------- + src/llama-kv-cells.h | 115 ++++++++++++-- + tests/CMakeLists.txt | 1 + + tests/test-skippy-kv-place-together.cpp | 200 ++++++++++++++++++++++++ + 4 files changed, 317 insertions(+), 80 deletions(-) + create mode 100644 tests/test-skippy-kv-place-together.cpp + +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index 7d099082c..9d9be0f94 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -1261,79 +1261,18 @@ bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_co + return updated; + } + +-// Unified pool placement that keeps each sequence's cells together: a token +-// goes to the cell after its sequence's highest one while that stays inside the +-// same chunk and free, else to the first cell of a fresh all-empty chunk. Row +-// lists then hold long runs instead of one cell per decode step, which is what +-// the row-attention kernels read at dense speed. A pool too fragmented for a +-// fresh chunk falls back to any empty cell. ++// Unified pool placement: each sequence's tokens of the ubatch land together (see ++// llama_kv_cells::place_together), so row lists hold long runs, which the ++// row-attention kernels read at dense speed. + std::vector llama_kv_cache::find_chunked_cells( + const llama_ubatch & ubatch, const llama_kv_cells & cells, uint32_t head_cur) const { +- const uint32_t n_tokens = ubatch.n_tokens; +- const uint32_t n_cells = cells.size(); +- const uint32_t n_chunks = n_cells / kv_chunk_cells; +- +- std::vector idxs; +- idxs.reserve(n_tokens); +- +- std::vector taken(n_cells, 0); +- const auto free_cell = [&](uint32_t idx) { return cells.is_empty(idx) && !taken[idx]; }; +- const auto take = [&](uint32_t idx) { taken[idx] = 1; idxs.push_back(idx); }; +- +- // next cell of each sequence's open chunk, resolved on first use +- std::array next; +- next.fill(-2); +- +- uint32_t chunk_cur = n_chunks ? (head_cur / kv_chunk_cells) % n_chunks : 0; +- +- for (uint32_t i = 0; i < n_tokens; ++i) { +- const llama_seq_id seq_id = ubatch.n_seq_id[i] > 0 ? ubatch.seq_id[i][0] : 0; +- +- if (next[seq_id] == -2) { +- const int64_t last = cells.seq_cell_max(seq_id); +- next[seq_id] = last >= 0 && (last + 1) % kv_chunk_cells != 0 ? last + 1 : -1; +- } +- +- const int64_t cand = next[seq_id]; +- if (cand >= 0 && cand < (int64_t) n_cells && free_cell((uint32_t) cand)) { +- take((uint32_t) cand); +- next[seq_id] = (cand + 1) % kv_chunk_cells != 0 ? cand + 1 : -1; +- continue; +- } +- +- // a fresh chunk: every cell empty and unclaimed, searched from the head onward +- bool placed = false; +- for (uint32_t tested = 0; tested < n_chunks && !placed; ++tested) { +- const uint32_t start = chunk_cur * kv_chunk_cells; +- chunk_cur = (chunk_cur + 1) % n_chunks; +- bool empty = true; +- for (uint32_t c = start; c < start + kv_chunk_cells && empty; ++c) { +- empty = free_cell(c); +- } +- if (empty) { +- take(start); +- next[seq_id] = kv_chunk_cells > 1 ? start + 1 : -1; +- placed = true; +- } +- } +- if (placed) { +- continue; +- } +- +- // the pool is fragmented: any empty cell keeps the batch going +- for (uint32_t tested = 0; tested < n_cells && !placed; ++tested) { +- const uint32_t idx = (head_cur + tested) % n_cells; +- if (free_cell(idx)) { +- take(idx); +- placed = true; +- } +- } +- if (!placed) { +- return { }; +- } +- } +- +- return idxs; ++ std::vector token_seqs(ubatch.n_tokens); ++ std::vector tokens(ubatch.n_tokens); ++ std::iota(tokens.begin(), tokens.end(), 0u); ++ std::transform(tokens.begin(), tokens.end(), token_seqs.begin(), [&](uint32_t i) { ++ return ubatch.n_seq_id[i] > 0 ? ubatch.seq_id[i][0] : 0; ++ }); ++ return cells.place_together(token_seqs, head_cur, kv_chunk_cells); + } + + llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, bool cont) const { +diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h +index 1743c8fae..ac6ae063e 100644 +--- a/src/llama-kv-cells.h ++++ b/src/llama-kv-cells.h +@@ -4,12 +4,14 @@ + #include "llama-cparams.h" + + #include ++#include + #include + #include + #include + #include + #include + #include ++#include + #include + #include + +@@ -627,17 +629,112 @@ public: + positions.size() == static_cast(pos_max) + 1; + } + +- // The highest cell the sequence occupies, or -1. +- int64_t seq_cell_max(llama_seq_id seq_id) const { +- assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); +- const auto & bits = seq_bits[seq_id]; +- const uint32_t n_words = std::min((used_max_p1() + 63) / 64, bits.size()); +- for (uint32_t w = n_words; w-- > 0;) { +- if (bits[w] != 0) { +- return 64 * w + fls64(bits[w]); ++ // Cells for the tokens of a batch, in token order, with each sequence's share kept ++ // together: first the free cells right after its latest token, then the smallest free ++ // stretch that holds the rest. A stretch starts on a `chunk` boundary, so the runs of a ++ // row list stay block aligned, and is sized in whole chunks, which leaves the sequence ++ // room to grow where it lands. When nothing holds the rest, the longest stretch is ++ // filled and what remains is placed the same way. Empty when the cells run out. ++ std::vector place_together(const std::vector & token_seqs, uint32_t head, uint32_t chunk) const { ++ const uint32_t n_cells = size(); ++ ++ std::vector busy(n_cells); ++ std::transform(pos.begin(), pos.end(), busy.begin(), [](llama_pos p) { return p != -1; }); ++ ++ struct share { ++ llama_seq_id seq; ++ uint32_t want; ++ std::vector cells; ++ }; ++ std::vector shares; ++ std::array share_of; ++ share_of.fill(-1); ++ std::for_each(token_seqs.begin(), token_seqs.end(), [&](llama_seq_id seq) { ++ if (share_of[seq] < 0) { ++ share_of[seq] = (int32_t) shares.size(); ++ shares.push_back({ seq, 0, { } }); ++ } ++ shares[share_of[seq]].want++; ++ }); ++ ++ const auto claim = [&](share & sh, uint32_t first, uint32_t n) { ++ std::fill_n(busy.begin() + first, n, 1); ++ sh.cells.resize(sh.cells.size() + n); ++ std::iota(sh.cells.end() - n, sh.cells.end(), first); ++ }; ++ ++ struct stretch { ++ uint32_t first; ++ uint32_t len; ++ }; ++ const auto stretches = [&](bool aligned) { ++ std::vector out; ++ auto it = std::find(busy.begin(), busy.end(), 0); ++ while (it != busy.end()) { ++ const auto end = std::find(it, busy.end(), 1); ++ const uint32_t last = (uint32_t) (end - busy.begin()); ++ const uint32_t first = (uint32_t) (it - busy.begin()); ++ const uint32_t start = aligned ? (first + chunk - 1)/chunk*chunk : first; ++ if (start < last) { ++ out.push_back({ start, last - start }); ++ } ++ it = std::find(end, busy.end(), 0); ++ } ++ return out; ++ }; ++ ++ for (share & sh : shares) { ++ const int64_t last = seq_cell_tail(sh.seq); ++ if (last >= 0 && last + 1 < (int64_t) n_cells) { ++ const auto begin = busy.begin() + last + 1; ++ const auto end = busy.begin() + std::min(n_cells, last + 1 + sh.want); ++ claim(sh, (uint32_t) (last + 1), (uint32_t) (std::find(begin, end, 1) - begin)); ++ } ++ while (sh.cells.size() < sh.want) { ++ const uint32_t rest = sh.want - (uint32_t) sh.cells.size(); ++ const uint32_t need = (rest + chunk - 1)/chunk*chunk; ++ ++ std::vector free = stretches(true); ++ if (free.empty()) { ++ free = stretches(false); ++ } ++ if (free.empty()) { ++ return { }; ++ } ++ ++ const auto ahead = [&](const stretch & s) { return (s.first + n_cells - head % n_cells) % n_cells; }; ++ const auto best = std::min_element(free.begin(), free.end(), [&](const stretch & a, const stretch & b) { ++ const bool fits_a = a.len >= need; ++ const bool fits_b = b.len >= need; ++ if (fits_a != fits_b) { ++ return fits_a; ++ } ++ if (!fits_a && a.len != b.len) { ++ return a.len > b.len; ++ } ++ if (fits_a && a.len != b.len) { ++ return a.len < b.len; ++ } ++ return ahead(a) < ahead(b); ++ }); ++ claim(sh, best->first, std::min(rest, best->len)); + } + } +- return -1; ++ ++ std::vector idxs(token_seqs.size()); ++ std::vector used_of(shares.size(), 0); ++ std::transform(token_seqs.begin(), token_seqs.end(), idxs.begin(), [&](llama_seq_id seq) { ++ const int32_t s = share_of[seq]; ++ return shares[s].cells[used_of[s]++]; ++ }); ++ return idxs; ++ } ++ ++ // The cell holding the sequence's highest position, or -1. A sequence that took over ++ // another's cells keeps writing after its own latest token, wherever those cells sit. ++ int64_t seq_cell_tail(llama_seq_id seq_id) const { ++ assert(seq_id >= 0 && seq_id < LLAMA_MAX_SEQ); ++ return seq_pos[seq_id].empty() ? -1 : (int64_t) seq_pos[seq_id].rbegin()->second; + } + + // note: call only if the cell is not empty +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index cc27837c5..595a84a26 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -194,6 +194,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) + llama_build_and_test(test-skippy-verify-checkpoint-retirement.cpp) + llama_build_and_test(test-skippy-kv-cells-contiguous.cpp) + llama_build_and_test(test-skippy-kv-rows-aligned.cpp) ++ llama_build_and_test(test-skippy-kv-place-together.cpp) + llama_build_and_test(test-skippy-recurrent-state-roundtrip.cpp) + # these tests are disabled on Windows because they use internal functions not exported with LLAMA_API (when building with shared libraries) + llama_build_and_test(test-unicode.cpp LABEL behavior LINK llama) +diff --git a/tests/test-skippy-kv-place-together.cpp b/tests/test-skippy-kv-place-together.cpp +new file mode 100644 +index 000000000..b7c50f142 +--- /dev/null ++++ b/tests/test-skippy-kv-place-together.cpp +@@ -0,0 +1,200 @@ ++// Batch placement (llama_kv_cells::place_together): every token gets its own free cell, and ++// a sequence's share of a batch lands in as few runs as the free space allows. ++#include "../src/llama-kv-cells.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++static int failures = 0; ++#define CHECK(cond) do { if (!(cond)) { ++failures; std::printf("FAIL line %d: %s\n", __LINE__, #cond); } } while (0) ++ ++static const uint32_t chunk = 64; ++ ++static void commit(llama_kv_cells & cells, const std::vector & seqs, const std::vector & idxs, ++ std::vector & next_pos) { ++ std::vector tokens(seqs.size()); ++ std::iota(tokens.begin(), tokens.end(), size_t(0)); ++ std::for_each(tokens.begin(), tokens.end(), [&](size_t i) { ++ cells.pos_set(idxs[i], next_pos[seqs[i]]++); ++ cells.seq_add(idxs[i], seqs[i]); ++ }); ++} ++ ++static size_t runs_of(const llama_kv_cells & cells, llama_seq_id seq) { ++ std::vector own; ++ std::vector all(cells.size()); ++ std::iota(all.begin(), all.end(), 0u); ++ std::copy_if(all.begin(), all.end(), std::back_inserter(own), [&](uint32_t i) { ++ return !cells.is_empty(i) && cells.seq_has(i, seq); ++ }); ++ if (own.empty()) { ++ return 0; ++ } ++ std::vector gaps(own.size()); ++ std::adjacent_difference(own.begin(), own.end(), gaps.begin()); ++ return 1 + (size_t) std::count_if(gaps.begin() + 1, gaps.end(), [](uint32_t gap) { return gap != 1; }); ++} ++ ++static std::vector batch_of(int n_seq, uint32_t per_seq) { ++ std::vector seqs((size_t) n_seq*per_seq); ++ std::vector tokens(seqs.size()); ++ std::iota(tokens.begin(), tokens.end(), size_t(0)); ++ std::transform(tokens.begin(), tokens.end(), seqs.begin(), [&](size_t i) { return (llama_seq_id) (i / per_seq); }); ++ return seqs; ++} ++ ++// four prompts in one batch, then their generation, then a follow-up prompt each ++static void concurrent_prompts() { ++ llama_kv_cells cells; ++ cells.resize(16384); ++ std::vector next_pos(4, 0); ++ ++ const auto prompt = batch_of(4, 512); ++ auto idxs = cells.place_together(prompt, 0, chunk); ++ CHECK(idxs.size() == prompt.size()); ++ commit(cells, prompt, idxs, next_pos); ++ std::vector each = { 0, 1, 2, 3 }; ++ CHECK(std::all_of(each.begin(), each.end(), [&](llama_seq_id s) { return runs_of(cells, s) == 1; })); ++ ++ std::vector steps(128); ++ std::for_each(steps.begin(), steps.end(), [&](int) { ++ const auto placed = cells.place_together(each, 0, chunk); ++ CHECK(placed.size() == each.size()); ++ commit(cells, each, placed, next_pos); ++ }); ++ // a prompt run, then generation in chunks ++ CHECK(std::all_of(each.begin(), each.end(), [&](llama_seq_id s) { return runs_of(cells, s) <= 1 + 128/chunk + 1; })); ++ ++ std::vector before(each.size()); ++ std::transform(each.begin(), each.end(), before.begin(), [&](llama_seq_id s) { return runs_of(cells, s); }); ++ idxs = cells.place_together(prompt, 0, chunk); ++ CHECK(idxs.size() == prompt.size()); ++ commit(cells, prompt, idxs, next_pos); ++ // a follow-up adds the rest of the open chunk and one stretch ++ CHECK(std::all_of(each.begin(), each.end(), [&](llama_seq_id s) { return runs_of(cells, s) <= before[s] + 1; })); ++} ++ ++// a request that resumes from cells placed above its own keeps one run per chunk of ++// generation, not one per token ++static void resumed_from_higher_cells() { ++ llama_kv_cells cells; ++ cells.resize(16384); ++ std::vector prefix(4096); ++ std::iota(prefix.begin(), prefix.end(), 8192u); ++ std::for_each(prefix.begin(), prefix.end(), [&](uint32_t i) { ++ cells.pos_set(i, (llama_pos) (i - 8192)); ++ cells.seq_add(i, 0); ++ cells.seq_add(i, 1); ++ }); ++ // the cell after the prefix belongs to someone else ++ cells.pos_set(8192 + 4096, 0); ++ cells.seq_add(8192 + 4096, 5); ++ ++ std::vector next_pos(8, 4096); ++ const std::vector prompt(512, 1); ++ commit(cells, prompt, cells.place_together(prompt, 0, chunk), next_pos); ++ CHECK(runs_of(cells, 1) == 2); ++ ++ std::vector steps(128); ++ std::for_each(steps.begin(), steps.end(), [&](int) { ++ const std::vector one = { 1 }; ++ commit(cells, one, cells.place_together(one, 0, chunk), next_pos); ++ }); ++ CHECK(runs_of(cells, 1) == 2); ++} ++ ++// the smallest stretch that holds the share wins over a larger one ++static void best_fit() { ++ llama_kv_cells cells; ++ cells.resize(4096); ++ std::vector all(cells.size()); ++ std::iota(all.begin(), all.end(), 0u); ++ llama_pos pos = 0; ++ // free: [512, 1024) and [2048, 2560 + 1024) ++ std::for_each(all.begin(), all.end(), [&](uint32_t i) { ++ const bool hole = (i >= 512 && i < 1024) || (i >= 2048 && i < 3584); ++ if (!hole) { ++ cells.pos_set(i, pos++); ++ cells.seq_add(i, 7); ++ } ++ }); ++ const std::vector share(512, 1); ++ const auto idxs = cells.place_together(share, 2048, chunk); ++ CHECK(idxs.size() == 512); ++ CHECK(idxs.front() == 512 && idxs.back() == 1023); ++} ++ ++// no stretch holds the share: the longest ones are filled first ++static void fragmented_pool() { ++ llama_kv_cells cells; ++ cells.resize(4096); ++ std::vector all(cells.size()); ++ std::iota(all.begin(), all.end(), 0u); ++ llama_pos pos = 0; ++ // every chunk keeps its first 16 cells busy, two chunks are fully free ++ std::for_each(all.begin(), all.end(), [&](uint32_t i) { ++ const bool free_chunk = i / chunk == 10 || i / chunk == 11; ++ if (!free_chunk && i % chunk < 16) { ++ cells.pos_set(i, pos++); ++ cells.seq_add(i, 7); ++ } ++ }); ++ std::vector next_pos(8, 0); ++ const std::vector share(512, 1); ++ const auto idxs = cells.place_together(share, 0, chunk); ++ CHECK(idxs.size() == 512); ++ CHECK(idxs.front() == 10*chunk); ++ commit(cells, share, idxs, next_pos); ++ // 128 free cells together, then 48 at a time ++ CHECK(runs_of(cells, 1) == 1 + (512 - 128 + 47)/48); ++} ++ ++static void random_pools() { ++ std::mt19937 rng(11); ++ for (int round = 0; round < 300; ++round) { ++ const uint32_t n_cells = chunk * (4 + rng() % 60); ++ llama_kv_cells cells; ++ cells.resize(n_cells); ++ const int n_seq = 1 + rng() % 4; ++ std::vector next_pos(n_seq, 0); ++ const uint32_t fill = rng() % n_cells; ++ std::vector tries(fill); ++ std::for_each(tries.begin(), tries.end(), [&](uint32_t) { ++ const uint32_t cell = rng() % n_cells; ++ if (cells.is_empty(cell)) { ++ const llama_seq_id seq = (llama_seq_id) (rng() % n_seq); ++ cells.pos_set(cell, next_pos[seq]++); ++ cells.seq_add(cell, seq); ++ } ++ }); ++ const uint32_t n_free = n_cells - cells.get_used(); ++ ++ std::vector seqs(1 + rng() % 600); ++ std::generate(seqs.begin(), seqs.end(), [&] { return (llama_seq_id) (rng() % n_seq); }); ++ const auto idxs = cells.place_together(seqs, rng() % n_cells, chunk); ++ ++ if (seqs.size() > n_free) { ++ CHECK(idxs.empty()); ++ continue; ++ } ++ CHECK(idxs.size() == seqs.size()); ++ CHECK(std::set(idxs.begin(), idxs.end()).size() == idxs.size()); ++ CHECK(std::all_of(idxs.begin(), idxs.end(), [&](uint32_t i) { return i < n_cells && cells.is_empty(i); })); ++ } ++} ++ ++int main() { ++ concurrent_prompts(); ++ resumed_from_higher_cells(); ++ best_fit(); ++ fragmented_pool(); ++ random_pools(); ++ if (failures == 0) { ++ std::printf("ok\n"); ++ } ++ return failures == 0 ? 0 : 1; ++} +-- +2.43.0 + diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index b4a15d05ab..0c5434ac0a 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -554,6 +554,7 @@ if [[ "$LLAMA_STAGE_FULL_REPLAY" == "ON" ]]; then test-skippy-kv-cells-contiguous test-skippy-kv-page-export test-skippy-kv-rows-aligned + test-skippy-kv-place-together test-skippy-model-loader-accounting test-skippy-recurrent-state-roundtrip test-skippy-rerank-template diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index 3d6790813a..fc71dd58e9 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -243,6 +243,7 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( "test-skippy-kv-cells-contiguous", "test-skippy-kv-page-export", "test-skippy-kv-rows-aligned", + "test-skippy-kv-place-together", "test-skippy-model-loader-accounting", "test-skippy-recurrent-state-roundtrip", "test-skippy-rerank-template", From 42005f4ae0d5d3dad31b42d61f10b2b091c8c55a Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 35/81] feat(skippy): batch policy API, configurable sampling executor, review fixes --- .gitignore | 1 - .../src/inference/skippy/deployment.rs | 2 + .../src/config/tests.rs | 4 +- skippy/crates/llama-spec-bench/src/main.rs | 1 + .../skippy-api/src/split-certified.json | 4 +- skippy/crates/skippy-api/src/stage.rs | 2 + skippy/crates/skippy-api/src/stage_load.rs | 2 + skippy/crates/skippy-cache/src/identity.rs | 4 + .../skippy-cli/src/serve_settings/catalog.rs | 28 + .../skippy-cli/src/serve_settings/tests.rs | 33 + .../crates/skippy-config/src/local_serving.rs | 18 +- .../src/runner/kv_page_growth.rs | 1 + .../src/runner/remote_handoff.rs | 1 + .../src/runner/single_step.rs | 2 + .../src/runner/split_chain.rs | 1 + .../src/runner/stage_execution.rs | 1 + .../src/runner/stage_fa_parity.rs | 1 + .../src/runner/state_handoff.rs | 2 + .../tests/parity_models/mod.rs | 1 + skippy/crates/skippy-ffi/README.md | 2 +- .../crates/skippy-ffi/src/bindings/skippy.rs | 4 +- skippy/crates/skippy-ffi/src/lib.rs | 2 +- skippy/crates/skippy-protocol/src/config.rs | 51 ++ skippy/crates/skippy-protocol/src/lib.rs | 10 +- .../crates/skippy-quantize/src/mtp_attach.rs | 1 + skippy/crates/skippy-runtime/src/config.rs | 10 + skippy/crates/skippy-runtime/src/tests.rs | 1 + .../src/frontend/generation/draft_runner.rs | 1 + .../src/frontend/generation/server.rs | 2 +- .../src/frontend/iteration_scheduler.rs | 44 +- .../iteration_scheduler/batch_policy.rs | 396 ++++++++++++ .../iteration_scheduler/batch_policy/tests.rs | 181 ++++++ .../iteration_scheduler/cache_wave.rs | 2 +- .../iteration_scheduler/command_waits.rs | 26 +- .../iteration_scheduler/direct_batch.rs | 97 ++- .../direct_batch/coalescing_tests.rs | 2 +- .../iteration_scheduler/direct_execution.rs | 19 +- .../iteration_scheduler/step_telemetry.rs | 2 +- .../src/frontend/iteration_scheduler/tests.rs | 24 +- .../local_generation/linear_decode.rs | 2 +- .../skippy-serving/src/runtime_state.rs | 1 + .../src/telemetry/resource_attrs.rs | 20 +- skippy/docs/SERVING_SETTINGS.md | 4 + ...wave-through-a-configurable-executor.patch | 590 ++++++++++++++++++ ...-add-diffusiongemma-system-one-reads.patch | 4 +- ...dels-add-laya-decision-model-support.patch | 4 +- ...kippy-add-whisper-speech-recognition.patch | 4 +- ...rd-per-token-logprobs-while-sampling.patch | 4 +- ...skippy-add-clef-joint-decision-reads.patch | 4 +- skippy/scripts/build-llama.sh | 1 + .../encoding_approval.rs | 2 +- .../full_replay.rs | 1 + 52 files changed, 1487 insertions(+), 140 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs create mode 100644 skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs create mode 100644 skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch diff --git a/.gitignore b/.gitignore index 13a3b008d5..d7b2a9d4e0 100644 --- a/.gitignore +++ b/.gitignore @@ -79,4 +79,3 @@ microkit-work/ /.lsmcp/ compile_commands.json skippy/skippy_api/.cache/ ->>>>>>> moby/2746-merged diff --git a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs index 3e0f77dd09..ceaf9e1c1b 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/inference/skippy/deployment.rs @@ -173,7 +173,9 @@ pub(crate) fn stage0_config( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, prefill_coalesce_max_ms: None, + batch: Default::default(), cache_idle_slots: context.runtime_settings.cache_idle_slots, resident_tensor_names: Vec::new(), execution_contract: context.admission.execution_contract.clone(), diff --git a/mesh/crates/mesh-llm-skippy-adapter/src/config/tests.rs b/mesh/crates/mesh-llm-skippy-adapter/src/config/tests.rs index c95b80201e..10ba97730a 100644 --- a/mesh/crates/mesh-llm-skippy-adapter/src/config/tests.rs +++ b/mesh/crates/mesh-llm-skippy-adapter/src/config/tests.rs @@ -467,7 +467,7 @@ tuning_profile = "throughput" assert_eq!(resolved.model_fit.cache_type_v, "f16"); assert_eq!(resolved.model_fit.kv_offload, "auto"); assert_eq!(resolved.throughput.tuning_profile, "throughput"); - assert_eq!(resolved.model_fit.batch, 1024); + assert_eq!(resolved.model_fit.batch, 2048); assert_eq!(resolved.model_fit.ubatch, 1024); assert_eq!(resolved.throughput.parallel, 2); assert_eq!(resolved.throughput.continuous_batching, "true"); @@ -1092,7 +1092,7 @@ parallel = 11 .unwrap(); assert_eq!(resolved.throughput.tuning_profile, "throughput"); - assert_eq!(resolved.model_fit.batch, 1024); + assert_eq!(resolved.model_fit.batch, 2048); assert_eq!(resolved.model_fit.ubatch, 999); assert_eq!(resolved.throughput.parallel, 11); assert_eq!(resolved.throughput.continuous_batching, "true"); diff --git a/skippy/crates/llama-spec-bench/src/main.rs b/skippy/crates/llama-spec-bench/src/main.rs index 58f92e3279..d30719e95b 100644 --- a/skippy/crates/llama-spec-bench/src/main.rs +++ b/skippy/crates/llama-spec-bench/src/main.rs @@ -357,6 +357,7 @@ fn full_model_config(path: &Path, ctx_size: u32, n_gpu_layers: i32) -> Result ThroughputProfileDefaults { match policy { + // A doubled micro-batch, and never a smaller batch than `balanced`: + // the batch is what lets prompts that arrive together prefill together. "throughput" => ThroughputProfileDefaults { - batch: Some(UBATCH * 2), + batch: Some(BATCH.max(UBATCH * 2)), ubatch: Some(UBATCH * 2), parallel: Some(2), continuous_batching: Some("true".to_string()), @@ -74,7 +76,7 @@ mod tests { fn throughput_profiles_preserve_mesh_tuning_behavior() { for (name, batch, ubatch, parallel, continuous) in [ ("balanced", 2048, 512, 4, "auto"), - ("throughput", 1024, 1024, 2, "true"), + ("throughput", 2048, 1024, 2, "true"), ("saver", 256, 256, 1, "false"), ] { let profile = throughput_profile_defaults(name); @@ -84,4 +86,16 @@ mod tests { assert_eq!(profile.continuous_batching.as_deref(), Some(continuous)); } } + + /// A profile named for throughput must not prefill fewer tokens per + /// iteration than the default one, and a batch holds at least one micro-batch. + #[test] + fn the_throughput_batch_is_never_below_the_balanced_one() { + let batch = |name| throughput_profile_defaults(name).batch.unwrap(); + let ubatch = |name| throughput_profile_defaults(name).ubatch.unwrap(); + assert!(batch("throughput") >= batch("balanced")); + for name in ["balanced", "throughput", "saver"] { + assert!(batch(name) >= ubatch(name), "{name}"); + } + } } diff --git a/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs b/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs index a58f893fe6..da90a096d0 100644 --- a/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs +++ b/skippy/crates/skippy-correctness/src/runner/kv_page_growth.rs @@ -166,6 +166,7 @@ pub fn kv_page_growth(args: KvPageGrowthArgs) -> Result<()> { kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }; plan.apply_to(&mut config); let model = StageModel::open(&args.runtime.model, &config) diff --git a/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs b/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs index 3977baa612..d6d916cfd4 100644 --- a/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs +++ b/skippy/crates/skippy-correctness/src/runner/remote_handoff.rs @@ -335,6 +335,7 @@ fn open_full_model(args: &RemoteHandoffArgs, lane_count: u32) -> Result Result Result Result { kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }; let stage0 = StageModel::open(&stage0_resolution.path, &stage0_config) .context("failed to open stage 0")?; diff --git a/skippy/crates/skippy-correctness/src/runner/stage_execution.rs b/skippy/crates/skippy-correctness/src/runner/stage_execution.rs index 089e99a70b..ae8f4ae950 100644 --- a/skippy/crates/skippy-correctness/src/runner/stage_execution.rs +++ b/skippy/crates/skippy-correctness/src/runner/stage_execution.rs @@ -514,6 +514,7 @@ pub(in crate::runner) fn tokenizer_model_for_state_handoff( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }, )) } diff --git a/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs b/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs index 8eb55e8e6b..aeceef9292 100644 --- a/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs +++ b/skippy/crates/skippy-correctness/src/runner/stage_fa_parity.rs @@ -131,6 +131,7 @@ fn decode_boundary( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }; plan.apply_to(&mut config); let selection = select_layer_package_parts(&PackageStageRequest { diff --git a/skippy/crates/skippy-correctness/src/runner/state_handoff.rs b/skippy/crates/skippy-correctness/src/runner/state_handoff.rs index 767f3d838e..8fc1b678b2 100644 --- a/skippy/crates/skippy-correctness/src/runner/state_handoff.rs +++ b/skippy/crates/skippy-correctness/src/runner/state_handoff.rs @@ -1037,6 +1037,7 @@ fn open_local_state_model( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }; StageModel::open(&stage_resolution.path, &runtime_config) .context("failed to open local state handoff stage") @@ -1619,6 +1620,7 @@ fn build_state_handoff_inputs( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }; let input_model = StageModel::open(&input_resolution.path, &input_config) .context("failed to open state handoff input producer")?; diff --git a/skippy/crates/skippy-correctness/tests/parity_models/mod.rs b/skippy/crates/skippy-correctness/tests/parity_models/mod.rs index f1bdca8136..9ce8effe58 100644 --- a/skippy/crates/skippy-correctness/tests/parity_models/mod.rs +++ b/skippy/crates/skippy-correctness/tests/parity_models/mod.rs @@ -1644,6 +1644,7 @@ fn open_stage_model(path: &StagePath, shape: StageShape, n_gpu_layers: i32) -> R kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, }, ) .with_context(|| { diff --git a/skippy/crates/skippy-ffi/README.md b/skippy/crates/skippy-ffi/README.md index 7fb77a8a22..217ea46edf 100644 --- a/skippy/crates/skippy-ffi/README.md +++ b/skippy/crates/skippy-ffi/README.md @@ -105,7 +105,7 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.83`. The patch header in +The staged ABI is versioned as `0.1.84`. The patch header in `skippy/llama_cpp/patches/` and the Rust constants in `skippy/crates/skippy-ffi/src/lib.rs` are the source of truth, so keep this README aligned with those files instead of treating it as canonical prose. diff --git a/skippy/crates/skippy-ffi/src/bindings/skippy.rs b/skippy/crates/skippy-ffi/src/bindings/skippy.rs index e0cb34ab6f..8c8354fbf7 100644 --- a/skippy/crates/skippy-ffi/src/bindings/skippy.rs +++ b/skippy/crates/skippy-ffi/src/bindings/skippy.rs @@ -6,7 +6,7 @@ pub const SKIPPY_ABI_VERSION_MAJOR: u32 = 0; pub const SKIPPY_ABI_VERSION_MINOR: u32 = 1; -pub const SKIPPY_ABI_VERSION_PATCH: u32 = 83; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 84; pub const SKIPPY_ACTIVATION_FRAME_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_IDENTITY_BYTES: u32 = 32; @@ -629,6 +629,8 @@ pub struct skippy_runtime_config { pub kv_release_pages: i32, #[doc = " @brief Whether attention reads a unified pool through per-owner row lists. AUTO and TRUE use row lists wherever the backend supports them; FALSE keeps ordinary attention over the whole pool, to measure one against the other."] pub kv_row_attention: i32, + #[doc = " @brief Threads that sample the requests of one decode wave. 0 uses the calling thread and as many pooled helpers as the wave and the hardware allow; 1 samples every request on the calling thread; any other value caps the calling thread plus helpers."] + pub sample_threads: u32, #[doc = " @brief Whether the backend offloads host tensor operations to device (mirrors upstream `op_offload`). SKIPPY_TRISTATE_AUTO preserves llama.cpp's derived default (enabled); FALSE/TRUE force the value."] pub op_offload: i32, #[doc = " @brief Whether model loading bypasses the host buffer, allowing extra buffers to be used (mirrors upstream `no_host`)."] diff --git a/skippy/crates/skippy-ffi/src/lib.rs b/skippy/crates/skippy-ffi/src/lib.rs index ef1a05752d..b75b5ab996 100644 --- a/skippy/crates/skippy-ffi/src/lib.rs +++ b/skippy/crates/skippy-ffi/src/lib.rs @@ -5,7 +5,7 @@ mod dynamic_library; // without compiling the crate to determine native-runtime compatibility. pub const ABI_VERSION_MAJOR: u32 = 0; pub const ABI_VERSION_MINOR: u32 = 1; -pub const ABI_VERSION_PATCH: u32 = 83; +pub const ABI_VERSION_PATCH: u32 = 84; // The facade constants are parsed without compiling; tie them to the generated // bindings' view of the native ABI version at compile time so a common.h bump diff --git a/skippy/crates/skippy-protocol/src/config.rs b/skippy/crates/skippy-protocol/src/config.rs index 2ac70f3c71..b7dff697dc 100644 --- a/skippy/crates/skippy-protocol/src/config.rs +++ b/skippy/crates/skippy-protocol/src/config.rs @@ -325,6 +325,48 @@ impl StageActivationCodecPolicy { } } +/// The algorithm that forms the scheduler's batches: how long a batch waits +/// for more requests, and which queued requests it takes. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum BatchPolicyKind { + /// Requests join a batch in the order they arrived, up to the lane count + /// and the token budget. + #[default] + ArrivalOrder, +} + +impl BatchPolicyKind { + pub const fn as_str(self) -> &'static str { + match self { + Self::ArrivalOrder => "arrival_order", + } + } +} + +/// Batch-forming settings. A value left unset is the one the policy chooses +/// for the backend the stage runs on. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct BatchConfig { + #[serde(default)] + pub policy: Option, + /// How long a batch of generated tokens waits for the other active + /// requests to join it, in microseconds. + #[serde(default)] + pub decode_window_us: Option, + /// How long a prompt waits for others to join its prefill wave, per + /// prompt token, in microseconds. `prefill_coalesce_max_ms` caps the total. + #[serde(default)] + pub prefill_window_per_token_us: Option, +} + +impl BatchConfig { + pub fn is_default(&self) -> bool { + *self == Self::default() + } +} + #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct StageConfig { @@ -451,12 +493,21 @@ pub struct StageConfig { /// over the whole pool. #[serde(default)] pub kv_row_attention: Option, + /// Threads that sample the requests of one decode wave. None and zero + /// use the scheduler thread plus as many pooled helpers as the wave and + /// the hardware allow; one samples every request on the scheduler + /// thread; any other value caps the scheduler thread plus helpers. + #[serde(default)] + pub sample_threads: Option, #[serde(default)] pub cache_idle_slots: Option, /// The longest a prompt waits for others to join its prefill wave, in /// milliseconds. None is the scheduler's own ceiling; zero never waits. #[serde(default)] pub prefill_coalesce_max_ms: Option, + /// How the scheduler forms its batches. + #[serde(default, skip_serializing_if = "BatchConfig::is_default")] + pub batch: BatchConfig, /// Exact native tensor names resolved locally from admitted package-v2 /// tensor IDs. Empty is valid only for an unsplit full-model load. #[serde( diff --git a/skippy/crates/skippy-protocol/src/lib.rs b/skippy/crates/skippy-protocol/src/lib.rs index e830c3a7e3..dc6db840ac 100644 --- a/skippy/crates/skippy-protocol/src/lib.rs +++ b/skippy/crates/skippy-protocol/src/lib.rs @@ -24,11 +24,11 @@ pub use admission::{ StageAdmissionSidecar, StageAdmissionSidecarKind, }; pub use config::{ - ActivationDType, ActivationDescriptor, ActivationLayout, FlashAttentionType, GlmDsaPolicy, - HostExpertLayers, HostExpertPolicy, LoadMode, PeerConfig, SplitMode, StageActivationCodec, - StageActivationCodecPolicy, StageConfig, StageDevice, StageIdentity, StageKvCacheCodec, - StageKvCacheConfig, StageKvCacheMode, StageKvRetention, StagePrefillAdmission, StageTopology, - StageTopologyEntry, + ActivationDType, ActivationDescriptor, ActivationLayout, BatchConfig, BatchPolicyKind, + FlashAttentionType, GlmDsaPolicy, HostExpertLayers, HostExpertPolicy, LoadMode, PeerConfig, + SplitMode, StageActivationCodec, StageActivationCodecPolicy, StageConfig, StageDevice, + StageIdentity, StageKvCacheCodec, StageKvCacheConfig, StageKvCacheMode, StageKvRetention, + StagePrefillAdmission, StageTopology, StageTopologyEntry, }; pub use messages::{ AckMessage, DecodeTokenMessage, ErrorMessage, FinalPrefillChunkMessage, MessageBase, diff --git a/skippy/crates/skippy-quantize/src/mtp_attach.rs b/skippy/crates/skippy-quantize/src/mtp_attach.rs index 067e10365e..1fca21bdff 100644 --- a/skippy/crates/skippy-quantize/src/mtp_attach.rs +++ b/skippy/crates/skippy-quantize/src/mtp_attach.rs @@ -212,6 +212,7 @@ fn runtime_config( kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, checkpoint_quantization: skippy_runtime::CheckpointQuantization::Preserve, checkpoint_imatrix: None, checkpoint_imatrix_sha256: None, diff --git a/skippy/crates/skippy-runtime/src/config.rs b/skippy/crates/skippy-runtime/src/config.rs index dd22c47a81..bb4c43a524 100644 --- a/skippy/crates/skippy-runtime/src/config.rs +++ b/skippy/crates/skippy-runtime/src/config.rs @@ -149,6 +149,11 @@ pub struct RuntimeConfig { /// `Some(true)` use them wherever the backend supports it; `Some(false)` /// keeps ordinary attention over the whole pool. pub kv_row_attention: Option, + /// Threads that sample the requests of one decode wave. `None` and + /// `Some(0)` use the calling thread plus as many pooled helpers as the + /// wave and the hardware allow; `Some(1)` samples on the calling thread + /// alone; any other value caps the calling thread plus helpers. + pub sample_threads: Option, /// Whether the backend offloads host tensor operations to device. `None` /// preserves llama.cpp's derived default (enabled). pub op_offload: Option, @@ -415,6 +420,7 @@ impl RuntimeConfig { kv_lazy_clear: tristate(self.kv_lazy_clear), kv_release_pages: tristate(self.kv_release_pages), kv_row_attention: tristate(self.kv_row_attention), + sample_threads: self.sample_threads.unwrap_or(0), op_offload: tristate(self.op_offload), no_host_buffer: self.no_host_buffer, check_tensors: self.check_tensors, @@ -560,6 +566,7 @@ impl Default for RuntimeConfig { kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, op_offload: None, no_host_buffer: false, check_tensors: false, @@ -1109,6 +1116,7 @@ mod tests { assert_eq!(raw.kv_lazy_clear, skippy_ffi::TRISTATE_AUTO); assert_eq!(raw.kv_release_pages, skippy_ffi::TRISTATE_AUTO); assert_eq!(raw.kv_row_attention, skippy_ffi::TRISTATE_AUTO); + assert_eq!(raw.sample_threads, 0); Ok(()) } @@ -1121,6 +1129,7 @@ mod tests { kv_lazy_clear: Some(false), kv_release_pages: Some(false), kv_row_attention: Some(true), + sample_threads: Some(6), ..RuntimeConfig::default() } .as_raw()? @@ -1130,6 +1139,7 @@ mod tests { assert_eq!(raw.kv_lazy_clear, skippy_ffi::TRISTATE_FALSE); assert_eq!(raw.kv_release_pages, skippy_ffi::TRISTATE_FALSE); assert_eq!(raw.kv_row_attention, skippy_ffi::TRISTATE_TRUE); + assert_eq!(raw.sample_threads, 6); Ok(()) } diff --git a/skippy/crates/skippy-runtime/src/tests.rs b/skippy/crates/skippy-runtime/src/tests.rs index d8bf413d39..fdec66225c 100644 --- a/skippy/crates/skippy-runtime/src/tests.rs +++ b/skippy/crates/skippy-runtime/src/tests.rs @@ -128,6 +128,7 @@ mod tests { kv_lazy_clear: None, kv_release_pages: None, kv_row_attention: None, + sample_threads: None, op_offload: None, no_host_buffer: false, check_tensors: false, diff --git a/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs b/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs index 439287ed8a..b9fd7bc837 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/draft_runner.rs @@ -392,6 +392,7 @@ pub(in crate::frontend) fn draft_runtime_config( kv_lazy_clear: config.kv_lazy_clear, kv_release_pages: config.kv_release_pages, kv_row_attention: config.kv_row_attention, + sample_threads: config.sample_threads, }) } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/server.rs b/skippy/crates/skippy-serving/src/frontend/generation/server.rs index 0142aa374c..2bb54df17d 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/server.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/server.rs @@ -11,8 +11,8 @@ use crate::frontend::admission::GenerationTokenBudget; use crate::frontend::generation::GenerationConcurrencyController; use crate::frontend::generation::GenerationServiceEstimator; use crate::frontend::generation::InferenceBackendMode; -use crate::frontend::generation::PersistentStageLanePool; use crate::frontend::generation::LoadedModel; +use crate::frontend::generation::PersistentStageLanePool; use crate::frontend::generation::StageOpenAiBackend; use crate::frontend::generation::attach_dflash_draft; use crate::frontend::generation::attach_native_mtp_draft_model; diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 7528afda0e..09ed7e2ed7 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -1,3 +1,4 @@ +mod batch_policy; pub(super) mod cache_runtime; mod cache_wave; mod command_waits; @@ -8,18 +9,21 @@ mod direct_reply; pub(crate) mod readout; mod step_telemetry; +use self::batch_policy::{ + BatchPlatform, BatchPolicy, BatchTuning, BatchView, Gather, batch_policy, take_batch, +}; use self::cache_runtime::{ CacheAffinityRefresh, CacheRuntimeQueue, CacheRuntimeTelemetry, should_coalesce_direct_iterations, should_fill_cache_runtime_wave, should_serve_cache_runtime, should_suppress_cache_runtime, }; use self::direct_batch::{ - PIPELINE_DECODE_GROUPS_ENV, direct_coalesce_target, effective_scheduler_lane_count, - pipeline_group_batch_size, prefill_coalesce_max, prefill_coalesce_window, - resolve_pipeline_decode_groups, - scheduler_safe_mode_from_value, should_serve_direct, take_direct_iteration_batch, + PIPELINE_DECODE_GROUPS_ENV, effective_scheduler_lane_count, pipeline_group_batch_size, + resolve_pipeline_decode_groups, scheduler_safe_mode_from_value, should_serve_direct, validate_direct_iteration, }; +#[cfg(test)] +use self::direct_batch::{direct_coalesce_target, take_direct_iteration_batch}; use self::direct_reply::DirectReply; use self::step_telemetry::{StepTiming, sample_kv_used_cells}; use crate::frontend::admission::DECODE_BATCH_HEADROOM_TOKENS; @@ -398,7 +402,7 @@ struct SchedulerWorker { /// unless `SKIPPY_PIPELINE_DECODE_GROUPS` splits waves into groups. direct_group_batch_size: usize, /// The ceiling on how long a prefill waits for others to join its wave. - prefill_coalesce_max: Duration, + batch_policy: Box, max_direct_iteration_tokens: usize, max_commands_per_turn: usize, iteration_interval: Duration, @@ -434,7 +438,13 @@ impl IterationScheduler { ) }; let safe_mode = scheduler_safe_mode_from_value(env::var(SAFE_MODE_ENV).ok().as_deref()); - let prefill_coalesce_max = prefill_coalesce_max(config.prefill_coalesce_max_ms); + let batch_platform = BatchPlatform::detect(); + let batch_tuning = BatchTuning::resolve( + batch_platform, + &config.batch, + config.prefill_coalesce_max_ms, + ); + let batch_policy = batch_policy(config.batch.policy.unwrap_or_default(), batch_tuning); let pipeline_decode_groups = resolve_pipeline_decode_groups( env::var(PIPELINE_DECODE_GROUPS_ENV).ok().as_deref(), planned_pipeline_decode_groups, @@ -492,6 +502,26 @@ impl IterationScheduler { "skippy.scheduler.mixed_prefill_decode".to_string(), json!(mixed_prefill_decode), ), + ( + "skippy.scheduler.batch_policy".to_string(), + json!(batch_policy.kind().as_str()), + ), + ( + "skippy.scheduler.batch_platform".to_string(), + json!(batch_platform.as_str()), + ), + ( + "skippy.scheduler.batch_decode_window_us".to_string(), + json!(batch_tuning.decode_window.as_micros()), + ), + ( + "skippy.scheduler.batch_prefill_window_per_token_us".to_string(), + json!(batch_tuning.prefill_window_per_token.as_micros()), + ), + ( + "skippy.scheduler.batch_prefill_window_max_ms".to_string(), + json!(batch_tuning.prefill_window_max.as_millis()), + ), ( "skippy.scheduler.cache_policy".to_string(), json!("weighted_lpm_aging_dfs_waiting_prefix"), @@ -525,7 +555,7 @@ impl IterationScheduler { scheduler_lane_count.max(1), pipeline_decode_groups, ), - prefill_coalesce_max, + batch_policy, max_direct_iteration_tokens, max_commands_per_turn: command_queue_capacity.min(MAX_COMMANDS_PER_TURN), iteration_interval, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs new file mode 100644 index 0000000000..b95aee5a28 --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs @@ -0,0 +1,396 @@ +//! Where the scheduler's batching decisions are made. +//! +//! A [`BatchPolicy`] answers two questions for the direct queue: how long a +//! batch waits for more requests ([`BatchPolicy::gather`]), and which queued +//! requests it takes ([`BatchPolicy::select`]). The scheduler checks every +//! selection before it runs ([`take_batch`]), so a policy can reorder and +//! hold back work but cannot break a session's ordering, starve the head of +//! the queue, or overfill an iteration. +//! +//! A new algorithm is a new [`BatchPolicyKind`] and an implementation here; +//! [`BatchTuning::resolve`] is the one place a backend gets different values. + +use super::direct_batch::{ + PREFILL_COALESCE_PER_TOKEN, PREFILL_COALESCE_WINDOW_MAX, direct_coalesce_target, +}; +use super::{DIRECT_ITERATION_COALESCE_WINDOW, DirectIteration}; +use skippy_protocol::{BatchConfig, BatchPolicyKind}; +use skippy_runtime::{BackendDeviceType, IterationBatchPhase}; +use std::collections::{BTreeSet, VecDeque}; +use std::time::Duration; + +/// The compute backend the stage's batches run on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BatchPlatform { + Metal, + Cuda, + Vulkan, + Cpu, + Other, +} + +impl BatchPlatform { + /// From a backend device name as the runtime reports it (`MTL0`, `CUDA1`). + pub(super) fn from_device_name(name: &str) -> Self { + let family = name.trim_end_matches(|c: char| c.is_ascii_digit()); + match family.to_ascii_uppercase().as_str() { + "MTL" | "METAL" => Self::Metal, + "CUDA" => Self::Cuda, + "VULKAN" => Self::Vulkan, + "CPU" => Self::Cpu, + _ => Self::Other, + } + } + + /// The first GPU the runtime reports, else its first device. + pub(super) fn detect() -> Self { + let Ok(devices) = skippy_runtime::backend_devices_untraced() else { + return Self::Other; + }; + devices + .iter() + .find(|device| { + matches!( + device.device_type, + BackendDeviceType::Gpu | BackendDeviceType::IntegratedGpu + ) + }) + .or_else(|| devices.first()) + .map_or(Self::Cpu, |device| Self::from_device_name(&device.name)) + } + + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Metal => "metal", + Self::Cuda => "cuda", + Self::Vulkan => "vulkan", + Self::Cpu => "cpu", + Self::Other => "other", + } + } +} + +/// The values a policy waits by. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct BatchTuning { + /// How long generated tokens wait for the other active requests. + pub(super) decode_window: Duration, + /// How long a prompt waits for company, per prompt token. A prefill costs + /// on the order of a millisecond a token, so a few microseconds a token + /// buys the chance that requests arriving together prefill as one wave. + pub(super) prefill_window_per_token: Duration, + /// The longest a prompt waits. May be shorter than `decode_window`, or zero. + pub(super) prefill_window_max: Duration, +} + +impl BatchTuning { + /// The policy's values for `platform`, with whatever the stage configures + /// laid over them. + pub(super) fn resolve( + platform: BatchPlatform, + config: &BatchConfig, + prefill_coalesce_max_ms: Option, + ) -> Self { + let base = match platform { + BatchPlatform::Metal + | BatchPlatform::Cuda + | BatchPlatform::Vulkan + | BatchPlatform::Cpu + | BatchPlatform::Other => Self { + decode_window: DIRECT_ITERATION_COALESCE_WINDOW, + prefill_window_per_token: PREFILL_COALESCE_PER_TOKEN, + prefill_window_max: PREFILL_COALESCE_WINDOW_MAX, + }, + }; + Self { + decode_window: config.decode_window_us.map_or(base.decode_window, |us| { + Duration::from_micros(u64::from(us)) + }), + prefill_window_per_token: config + .prefill_window_per_token_us + .map_or(base.prefill_window_per_token, |us| { + Duration::from_micros(u64::from(us)) + }), + prefill_window_max: prefill_coalesce_max_ms.map_or(base.prefill_window_max, |ms| { + Duration::from_millis(u64::from(ms)) + }), + } + } + + /// The wait for a batch that holds a prefill of `tokens`: a small fraction + /// of the prefill itself, at least the decode window, never past the cap. + pub(super) fn prefill_window(&self, tokens: usize) -> Duration { + (self.prefill_window_per_token * u32::try_from(tokens).unwrap_or(u32::MAX)) + .max(self.decode_window) + .min(self.prefill_window_max) + } +} + +/// One queued request, as a policy sees it. +#[derive(Clone, Copy, Debug)] +pub(super) struct QueuedRequest<'a> { + pub(super) session: &'a str, + pub(super) tokens: usize, + pub(super) phase: IterationBatchPhase, +} + +/// What the scheduler knows when it is about to form a batch. `queued` is in +/// arrival order. +#[derive(Clone, Debug)] +pub(super) struct BatchView<'a> { + pub(super) queued: Vec>, + /// Sessions the runtime is serving, queued or not. + pub(super) active_sessions: usize, + /// The most requests one batch may hold. + pub(super) lanes: usize, + /// The most tokens one batch may hold. + pub(super) token_budget: usize, +} + +impl<'a> BatchView<'a> { + pub(super) fn of( + queue: &'a VecDeque, + active_sessions: usize, + lanes: usize, + token_budget: usize, + ) -> Self { + Self { + queued: queue + .iter() + .map(|request| QueuedRequest { + session: &request.session_id, + tokens: request.token_ids.len(), + phase: request.phase, + }) + .collect(), + active_sessions, + lanes, + token_budget, + } + } +} + +/// Wait until `target` requests are queued or `window` has passed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Gather { + pub(super) target: usize, + pub(super) window: Duration, +} + +/// Positions in [`BatchView::queued`] of the requests to run now. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct Selection(pub(super) Vec); + +pub(super) trait BatchPolicy: Send { + fn kind(&self) -> BatchPolicyKind; + fn tuning(&self) -> BatchTuning; + fn gather(&self, view: &BatchView<'_>) -> Gather; + fn select(&self, view: &BatchView<'_>) -> Selection; +} + +/// The policy a stage gets when it configures nothing, on an unnamed backend. +#[cfg(test)] +pub(in crate::frontend::iteration_scheduler) fn default_policy() -> Box { + batch_policy( + BatchPolicyKind::default(), + BatchTuning::resolve(BatchPlatform::Other, &BatchConfig::default(), None), + ) +} + +pub(super) fn batch_policy(kind: BatchPolicyKind, tuning: BatchTuning) -> Box { + match kind { + BatchPolicyKind::ArrivalOrder => Box::new(ArrivalOrder { tuning }), + } +} + +/// Requests join in the order they arrived. A batch that holds a prompt +/// waits for a full wave, for a window sized to the prompt; a batch of +/// generated tokens waits the decode window for the sessions already active. +pub(super) struct ArrivalOrder { + pub(super) tuning: BatchTuning, +} + +impl BatchPolicy for ArrivalOrder { + fn kind(&self) -> BatchPolicyKind { + BatchPolicyKind::ArrivalOrder + } + + fn tuning(&self) -> BatchTuning { + self.tuning + } + + fn gather(&self, view: &BatchView<'_>) -> Gather { + let prefill_tokens = view + .queued + .iter() + .filter(|request| request.phase == IterationBatchPhase::Prefill) + .map(|request| request.tokens) + .max(); + match prefill_tokens { + Some(tokens) => Gather { + target: view.lanes, + window: self.tuning.prefill_window(tokens), + }, + None => Gather { + target: direct_coalesce_target(view.active_sessions, view.queued.len(), view.lanes), + window: self.tuning.decode_window, + }, + } + } + + fn select(&self, view: &BatchView<'_>) -> Selection { + let mut budget = view.token_budget; + // Sessions with a request taken or passed over: a later request from + // one must wait, so it cannot overtake the earlier one. + let mut claimed = BTreeSet::new(); + let mut selected = Vec::new(); + for (position, request) in view.queued.iter().enumerate() { + if selected.len() >= view.lanes || budget == 0 { + break; + } + if !claimed.insert(request.session) { + continue; + } + // Keep scanning past a chunk that does not fit, so smaller decode + // rows queued behind a large prefill chunk still join this wave. + if request.tokens > budget { + continue; + } + budget -= request.tokens; + selected.push(position); + } + Selection(selected) + } +} + +/// Why a policy's selection was not run as given. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BatchRejection { + Empty, + NotInQueueOrder, + OutOfRange, + TooManyRequests, + OverTokenBudget, + SessionTwice, + OvertakesSession, + SkipsQueueHead, +} + +impl BatchRejection { + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Empty => "empty", + Self::NotInQueueOrder => "not_in_queue_order", + Self::OutOfRange => "out_of_range", + Self::TooManyRequests => "too_many_requests", + Self::OverTokenBudget => "over_token_budget", + Self::SessionTwice => "session_twice", + Self::OvertakesSession => "overtakes_session", + Self::SkipsQueueHead => "skips_queue_head", + } + } +} + +/// The rules every batch keeps, whichever policy chose it. +/// +/// The head of the queue always fits a fresh budget (iterations are validated +/// against it when queued), so requiring it keeps every request moving. +pub(super) fn check_selection( + view: &BatchView<'_>, + selection: &Selection, +) -> Result<(), BatchRejection> { + let positions = &selection.0; + if positions.is_empty() { + return Err(BatchRejection::Empty); + } + if positions.windows(2).any(|pair| pair[0] >= pair[1]) { + return Err(BatchRejection::NotInQueueOrder); + } + if positions + .iter() + .any(|&position| position >= view.queued.len()) + { + return Err(BatchRejection::OutOfRange); + } + if positions[0] != 0 { + return Err(BatchRejection::SkipsQueueHead); + } + if positions.len() > view.lanes { + return Err(BatchRejection::TooManyRequests); + } + let tokens: usize = positions + .iter() + .map(|&position| view.queued[position].tokens) + .sum(); + if tokens > view.token_budget { + return Err(BatchRejection::OverTokenBudget); + } + let mut sessions = BTreeSet::new(); + if !positions + .iter() + .all(|&position| sessions.insert(view.queued[position].session)) + { + return Err(BatchRejection::SessionTwice); + } + let overtakes = positions.iter().any(|&position| { + view.queued[..position] + .iter() + .enumerate() + .any(|(earlier, request)| { + request.session == view.queued[position].session + && positions.binary_search(&earlier).is_err() + }) + }); + if overtakes { + return Err(BatchRejection::OvertakesSession); + } + Ok(()) +} + +/// A batch off the queue: the policy's selection when it keeps the rules, +/// otherwise arrival order, with the reason the policy's was set aside. +/// +/// Requests left behind keep their order. The batch is ordered by session so +/// arrival timing cannot permute graph rows between otherwise identical waves. +pub(super) fn take_batch( + queue: &mut VecDeque, + policy: &dyn BatchPolicy, + active_sessions: usize, + lanes: usize, + token_budget: usize, +) -> (Vec, Option) { + if queue.is_empty() { + return (Vec::new(), None); + } + let (positions, rejection) = { + let view = BatchView::of(queue, active_sessions, lanes, token_budget); + let selection = policy.select(&view); + match check_selection(&view, &selection) { + Ok(()) => (selection.0, None), + Err(rejection) => { + let fallback = ArrivalOrder { + tuning: policy.tuning(), + } + .select(&view); + (fallback.0, Some(rejection)) + } + } + }; + let mut batch = Vec::with_capacity(positions.len()); + let mut left = VecDeque::with_capacity(queue.len()); + let mut wanted = positions.iter().copied().peekable(); + for (position, request) in std::mem::take(queue).into_iter().enumerate() { + if wanted.peek() == Some(&position) { + wanted.next(); + batch.push(request); + } else { + left.push_back(request); + } + } + *queue = left; + batch.sort_unstable_by(|left, right| left.session_id.cmp(&right.session_id)); + (batch, rejection) +} + +#[cfg(test)] +mod tests; diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs new file mode 100644 index 0000000000..a4b6ad57ca --- /dev/null +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs @@ -0,0 +1,181 @@ +use super::*; + +fn queued( + session: &'static str, + tokens: usize, + phase: IterationBatchPhase, +) -> QueuedRequest<'static> { + QueuedRequest { + session, + tokens, + phase, + } +} + +fn view( + queued: Vec>, + lanes: usize, + token_budget: usize, +) -> BatchView<'static> { + BatchView { + queued, + active_sessions: 0, + lanes, + token_budget, + } +} + +fn default_tuning() -> BatchTuning { + BatchTuning::resolve(BatchPlatform::Other, &BatchConfig::default(), None) +} + +const DECODE: IterationBatchPhase = IterationBatchPhase::Decode; +const PREFILL: IterationBatchPhase = IterationBatchPhase::Prefill; + +#[test] +fn device_names_map_to_platforms() { + assert_eq!( + BatchPlatform::from_device_name("MTL0"), + BatchPlatform::Metal + ); + assert_eq!( + BatchPlatform::from_device_name("CUDA1"), + BatchPlatform::Cuda + ); + assert_eq!( + BatchPlatform::from_device_name("Vulkan0"), + BatchPlatform::Vulkan + ); + assert_eq!(BatchPlatform::from_device_name("CPU"), BatchPlatform::Cpu); + assert_eq!( + BatchPlatform::from_device_name("SYCL0"), + BatchPlatform::Other + ); +} + +/// Every backend starts from the values the scheduler has always used. +#[test] +fn unset_tuning_is_the_scheduler_default_on_every_platform() { + for platform in [ + BatchPlatform::Metal, + BatchPlatform::Cuda, + BatchPlatform::Vulkan, + BatchPlatform::Cpu, + BatchPlatform::Other, + ] { + let tuning = BatchTuning::resolve(platform, &BatchConfig::default(), None); + assert_eq!(tuning.decode_window, Duration::from_millis(2)); + assert_eq!(tuning.prefill_window_per_token, Duration::from_micros(15)); + assert_eq!(tuning.prefill_window_max, Duration::from_millis(8)); + } +} + +#[test] +fn configured_tuning_replaces_the_platform_values() { + let config = BatchConfig { + policy: None, + decode_window_us: Some(500), + prefill_window_per_token_us: Some(40), + }; + let tuning = BatchTuning::resolve(BatchPlatform::Metal, &config, Some(20)); + assert_eq!(tuning.decode_window, Duration::from_micros(500)); + assert_eq!(tuning.prefill_window_per_token, Duration::from_micros(40)); + assert_eq!(tuning.prefill_window_max, Duration::from_millis(20)); + assert_eq!(tuning.prefill_window(100), Duration::from_millis(4)); + assert_eq!(tuning.prefill_window(4096), Duration::from_millis(20)); + assert_eq!(tuning.prefill_window(1), Duration::from_micros(500)); +} + +#[test] +fn a_prompt_gathers_a_full_wave_and_generation_the_active_sessions() { + let policy = ArrivalOrder { + tuning: default_tuning(), + }; + let mut with_prompt = view( + vec![queued("a", 1, DECODE), queued("b", 512, PREFILL)], + 4, + 2048, + ); + with_prompt.active_sessions = 2; + assert_eq!( + policy.gather(&with_prompt), + Gather { + target: 4, + window: Duration::from_micros(7_680), + } + ); + let mut generating = view(vec![queued("a", 1, DECODE)], 4, 2048); + generating.active_sessions = 3; + assert_eq!( + policy.gather(&generating), + Gather { + target: 3, + window: Duration::from_millis(2), + } + ); + assert_eq!(policy.gather(&view(Vec::new(), 4, 2048)).target, 0); +} + +#[test] +fn arrival_order_keeps_every_rule() { + let policy = ArrivalOrder { + tuning: default_tuning(), + }; + let view = view( + vec![ + queued("a", 4, PREFILL), + queued("b", 9, PREFILL), + queued("a", 1, DECODE), + queued("b", 1, DECODE), + queued("c", 1, DECODE), + ], + 3, + 8, + ); + let selection = policy.select(&view); + // b's prefill does not fit; its later decode must not overtake it + assert_eq!(selection, Selection(vec![0, 4])); + assert_eq!(check_selection(&view, &selection), Ok(())); +} + +#[test] +fn a_selection_that_breaks_a_rule_is_named() { + let view = view( + vec![ + queued("a", 4, PREFILL), + queued("b", 4, PREFILL), + queued("a", 1, DECODE), + queued("c", 6, PREFILL), + ], + 2, + 8, + ); + let rejected = |positions: &[usize]| check_selection(&view, &Selection(positions.to_vec())); + assert_eq!(rejected(&[]), Err(BatchRejection::Empty)); + assert_eq!(rejected(&[1, 0]), Err(BatchRejection::NotInQueueOrder)); + assert_eq!(rejected(&[0, 0]), Err(BatchRejection::NotInQueueOrder)); + assert_eq!(rejected(&[0, 9]), Err(BatchRejection::OutOfRange)); + assert_eq!(rejected(&[1]), Err(BatchRejection::SkipsQueueHead)); + assert_eq!(rejected(&[0, 1, 3]), Err(BatchRejection::TooManyRequests)); + assert_eq!(rejected(&[0, 3]), Err(BatchRejection::OverTokenBudget)); + assert_eq!(rejected(&[0, 2]), Err(BatchRejection::SessionTwice)); + assert_eq!(rejected(&[0, 1]), Ok(())); +} + +#[test] +fn a_later_request_may_not_overtake_its_own_session() { + let view = view( + vec![ + queued("a", 1, DECODE), + queued("b", 4, PREFILL), + queued("b", 1, DECODE), + ], + 4, + 8, + ); + assert_eq!( + check_selection(&view, &Selection(vec![0, 2])), + Err(BatchRejection::OvertakesSession) + ); + assert_eq!(check_selection(&view, &Selection(vec![0, 1])), Ok(())); +} diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs index d4d2ee0a92..79fdc49ab6 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs @@ -91,7 +91,7 @@ mod tests { kv_capacity_tokens: 8192, max_direct_batch_size: 4, direct_group_batch_size: 4, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: 32, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs index ba1a9e711b..af5116ebec 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs @@ -59,26 +59,12 @@ impl SchedulerWorker { /// wave run at once instead of taking a turn of their own, so a request /// that is a few milliseconds behind can still submit its prefill in time. pub(super) fn coalesce_direct_iterations(&mut self) -> bool { - let prefill_tokens = self - .direct_iterations - .iter() - .filter(|request| request.phase == IterationBatchPhase::Prefill) - .map(|request| request.token_ids.len()) - .max(); - let (target, window) = match prefill_tokens { - Some(tokens) => ( - self.direct_group_batch_size, - prefill_coalesce_window(tokens, self.prefill_coalesce_max), - ), - None => ( - direct_coalesce_target( - self.active_runtime_sessions, - self.direct_iterations.len(), - self.direct_group_batch_size, - ), - DIRECT_ITERATION_COALESCE_WINDOW, - ), - }; + let Gather { target, window } = self.batch_policy.gather(&BatchView::of( + &self.direct_iterations, + self.active_runtime_sessions, + self.direct_group_batch_size, + self.max_direct_iteration_tokens, + )); let queued_before = self.direct_iterations.len(); if target <= queued_before { return true; diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs index 7e9f7e314a..b840e4debb 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch.rs @@ -1,6 +1,15 @@ -use super::{DIRECT_ITERATION_COALESCE_WINDOW, DirectIteration, MAX_NATIVE_ITERATION_TOKENS}; +#[cfg(test)] +use super::DIRECT_ITERATION_COALESCE_WINDOW; +#[cfg(test)] +use super::DirectIteration; +use super::MAX_NATIVE_ITERATION_TOKENS; +#[cfg(test)] +use super::batch_policy::{BatchPlatform, BatchTuning, default_policy, take_batch}; use skippy_inference_api::{InferenceError, InferenceResult}; -use std::collections::{BTreeSet, VecDeque}; +#[cfg(test)] +use skippy_protocol::BatchConfig; +#[cfg(test)] +use std::collections::VecDeque; use std::time::Duration; pub(super) fn should_serve_direct( @@ -31,30 +40,29 @@ pub(super) fn direct_coalesce_target( .min(max_direct_batch_size) } -/// How long a prefill may wait for company, per prompt token. A prefill -/// costs on the order of a millisecond per token on the runtime, so a few -/// microseconds a token buys the chance that requests arriving together -/// prefill as one wave and start decoding together, instead of one taking -/// the runtime for hundreds of milliseconds while the rest queue behind it. -const PREFILL_COALESCE_PER_TOKEN: Duration = Duration::from_micros(15); +/// How long a prefill may wait for company, per prompt token, unless the +/// stage's batch settings say otherwise. +pub(super) const PREFILL_COALESCE_PER_TOKEN: Duration = Duration::from_micros(15); /// The longest a prefill waits unless the stage configures another ceiling. -const PREFILL_COALESCE_WINDOW_MAX: Duration = Duration::from_millis(8); +pub(super) const PREFILL_COALESCE_WINDOW_MAX: Duration = Duration::from_millis(8); /// The ceiling on the prefill coalesce window: the stage's /// `prefill_coalesce_max_ms`, else the scheduler's own. +#[cfg(test)] pub(super) fn prefill_coalesce_max(configured_ms: Option) -> Duration { - configured_ms.map_or(PREFILL_COALESCE_WINDOW_MAX, |ms| { - Duration::from_millis(u64::from(ms)) - }) + BatchTuning::resolve(BatchPlatform::Other, &BatchConfig::default(), configured_ms) + .prefill_window_max } -/// The coalesce window for a batch that holds a prefill of `tokens`: a small -/// fraction of the prefill itself, at least the decode window, and never -/// past `max`, which may be shorter than the decode window or zero. +/// The default tuning's coalesce window for a batch that holds a prefill of +/// `tokens`, under the ceiling `max`. +#[cfg(test)] pub(super) fn prefill_coalesce_window(tokens: usize, max: Duration) -> Duration { - (PREFILL_COALESCE_PER_TOKEN * u32::try_from(tokens).unwrap_or(u32::MAX)) - .max(DIRECT_ITERATION_COALESCE_WINDOW) - .min(max) + BatchTuning { + prefill_window_max: max, + ..BatchTuning::resolve(BatchPlatform::Other, &BatchConfig::default(), None) + } + .prefill_window(tokens) } #[cfg(test)] @@ -120,52 +128,21 @@ pub(super) const fn effective_scheduler_lane_count( } } +/// A batch chosen by the default policy. +#[cfg(test)] pub(super) fn take_direct_iteration_batch( queue: &mut VecDeque, max_batch_size: usize, - mut token_budget: usize, + token_budget: usize, ) -> Vec { - let mut batch = Vec::new(); - // Sessions that already have a request in this wave or deferred from it. - // A later request from such a session must wait so it cannot overtake - // the earlier one. - let mut claimed_sessions = BTreeSet::new(); - let mut deferred = VecDeque::new(); - let queued = queue.len(); - for _ in 0..queued { - if batch.len() >= max_batch_size { - break; - } - let Some(request) = queue.pop_front() else { - break; - }; - if claimed_sessions.contains(&request.session_id) { - deferred.push_back(request); - continue; - } - // Keep scanning past a chunk that does not fit so smaller decode rows - // queued behind a large prefill chunk still join this wave. The - // deferred chunk keeps its place ahead of later arrivals, and the - // queue head always fits a fresh budget, so it cannot starve. - if request.token_ids.len() > token_budget { - claimed_sessions.insert(request.session_id.clone()); - deferred.push_back(request); - continue; - } - token_budget = token_budget.saturating_sub(request.token_ids.len()); - claimed_sessions.insert(request.session_id.clone()); - batch.push(request); - if token_budget == 0 { - break; - } - } - deferred.append(queue); - *queue = deferred; - // Selection stays FIFO and budget-driven. Only order the selected, distinct - // sessions for native execution so arrival timing cannot permute graph rows - // between otherwise identical waves. Each request keeps its own reply. - batch.sort_unstable_by(|left, right| left.session_id.cmp(&right.session_id)); - batch + take_batch( + queue, + default_policy().as_ref(), + 0, + max_batch_size, + token_budget, + ) + .0 } pub(super) fn validate_direct_iteration( diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs index 0770b96a57..1669eee625 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs @@ -14,7 +14,7 @@ fn worker(commands: std_mpsc::Receiver) -> SchedulerWorker { kv_capacity_tokens: 64, max_direct_batch_size: 4, direct_group_batch_size: 4, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, // Leave the sentinel command for coalescing or the next idle turn. max_commands_per_turn: 0, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs index 437ba7809b..9c9e403227 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/direct_execution.rs @@ -19,11 +19,28 @@ struct BatchTiming { impl SchedulerWorker { /// Align and execute a direct batch, then deliver each request's own result. pub(super) fn run_direct_iteration_batch(&mut self) { - let batch = take_direct_iteration_batch( + let (batch, rejection) = take_batch( &mut self.direct_iterations, + self.batch_policy.as_ref(), + self.active_runtime_sessions, self.direct_group_batch_size, self.max_direct_iteration_tokens, ); + if let (Some(rejection), Some(telemetry)) = (rejection, self.telemetry.as_ref()) { + telemetry.emit( + "stage.scheduler_batch_selection_rejected", + BTreeMap::from([ + ( + "skippy.scheduler.batch_policy".to_string(), + json!(self.batch_policy.kind().as_str()), + ), + ( + "skippy.scheduler.batch_rejection".to_string(), + json!(rejection.as_str()), + ), + ]), + ); + } debug_assert!(!batch.is_empty(), "validated direct queue must yield work"); let active = retain_active(batch); if active.is_empty() { diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs index 130e649da3..20eee41bfb 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs @@ -198,7 +198,7 @@ mod tests { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index 63e57ee312..231b97884e 100644 --- a/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/skippy/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -94,7 +94,7 @@ fn expired_direct_iteration_behind_blocked_worker_never_reaches_native_runtime() kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -268,7 +268,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { kv_capacity_tokens: 64, max_direct_batch_size: 2, direct_group_batch_size: 2, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -378,7 +378,7 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -439,7 +439,7 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -498,7 +498,7 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { kv_capacity_tokens: 64, max_direct_batch_size: 3, direct_group_batch_size: 3, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -546,7 +546,7 @@ fn detached_runtime_operation_returns_before_work_completes() { kv_capacity_tokens: 64, max_direct_batch_size: 3, direct_group_batch_size: 3, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -691,7 +691,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -741,7 +741,7 @@ fn resident_kv_does_not_engage_direct_wave_gate() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -838,7 +838,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -960,7 +960,7 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -1056,7 +1056,7 @@ fn scheduler_worker_keeps_serving_after_an_operation_panics() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, @@ -1120,7 +1120,7 @@ fn direct_iterations_in_a_panicking_batch_get_an_error() { kv_capacity_tokens: 64, max_direct_batch_size: 1, direct_group_batch_size: 1, - prefill_coalesce_max: std::time::Duration::from_millis(8), + batch_policy: crate::frontend::iteration_scheduler::batch_policy::default_policy(), max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, max_commands_per_turn: 8, iteration_interval: Duration::ZERO, diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs index 74f49abb13..e477946a35 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/linear_decode.rs @@ -295,8 +295,8 @@ mod tests { use std::sync::{Arc, Mutex, atomic::AtomicUsize}; use super::*; - use crate::frontend::generation::LoadedModel; use crate::frontend::admission::GenerationTokenBudget; + use crate::frontend::generation::LoadedModel; use crate::frontend::generation::{ GenerationConcurrencyController, InferenceBackendMode, InferenceCacheHints, InferenceGenerationIds, diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index 465bde75c5..cdcc000486 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -619,6 +619,7 @@ pub(crate) fn runtime_config_from_stage_config( kv_lazy_clear: config.kv_lazy_clear, kv_release_pages: config.kv_release_pages, kv_row_attention: config.kv_row_attention, + sample_threads: config.sample_threads, projector_path: config.projector_path.clone(), projector_use_gpu: config.projector_use_gpu, media_marker: config.media_marker.clone(), diff --git a/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs index 9274134e17..5f421beb9f 100644 --- a/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs +++ b/skippy/crates/skippy-serving/src/telemetry/resource_attrs.rs @@ -152,9 +152,14 @@ fn serving_config_attrs(config: &StageConfig) -> BTreeMap { ("skippy.kv.swa_full", config.swa_full.map(Value::from)), ( "skippy.kv.pool_tokens", - config.kv_pool_tokens.map(|tokens| Value::from(tokens.get())), + config + .kv_pool_tokens + .map(|tokens| Value::from(tokens.get())), + ), + ( + "skippy.kv.lazy_clear", + config.kv_lazy_clear.map(Value::from), ), - ("skippy.kv.lazy_clear", config.kv_lazy_clear.map(Value::from)), ( "skippy.kv.release_pages", config.kv_release_pages.map(Value::from), @@ -165,13 +170,10 @@ fn serving_config_attrs(config: &StageConfig) -> BTreeMap { ), ( "skippy.kv.retention_tokens", - config - .kv_cache - .as_ref() - .map(|cache| match cache.retention { - StageKvRetention::Tokens(tokens) => Value::from(tokens), - StageKvRetention::Unbounded => Value::from("unbounded"), - }), + config.kv_cache.as_ref().map(|cache| match cache.retention { + StageKvRetention::Tokens(tokens) => Value::from(tokens), + StageKvRetention::Unbounded => Value::from("unbounded"), + }), ), ( "skippy.scheduler.prefill_coalesce_max_ms", diff --git a/skippy/docs/SERVING_SETTINGS.md b/skippy/docs/SERVING_SETTINGS.md index 7b54703e33..7578d4962c 100644 --- a/skippy/docs/SERVING_SETTINGS.md +++ b/skippy/docs/SERVING_SETTINGS.md @@ -246,6 +246,10 @@ with their runtime purpose; existing controls follow in the same sections. | `--continuous-batching` | `continuous_batching` | Allow the iteration scheduler to serve concurrent lanes | | `--pipeline-decode-groups` | `pipeline_decode_groups` | Number of decode dispatch groups | | `--prefill-coalesce-max-ms` | `prefill_coalesce_max_ms` | Longest a prompt waits for others to join its prefill wave, in milliseconds; zero never waits | +| `--sample-threads` | `sample_threads` | Threads that sample one decode wave: 0 as many as the wave and the hardware allow, 1 the scheduler thread alone, N at most N | +| `--batch-policy` | `batch_policy` | Algorithm that forms the scheduler's batches: arrival_order | +| `--batch-decode-window-us` | `batch_decode_window_us` | How long generated tokens wait for the other active requests to join their batch, in microseconds | +| `--batch-prefill-window-per-token-us` | `batch_prefill_window_per_token_us` | How long a prompt waits for others to join its prefill wave, per prompt token, in microseconds | | `--generation-signal-window` | `generation_signal_window` | Generation signal observation window in tokens | | `--generation-concurrency` | `generation_concurrency` | See `skippy serve --help` for values and defaults. | | `--adaptive-generation-concurrency` | `adaptive_generation_concurrency` | See `skippy serve --help` for values and defaults. | diff --git a/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch b/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch new file mode 100644 index 0000000000..78ec96818d --- /dev/null +++ b/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch @@ -0,0 +1,590 @@ +From 24b6a305317dc5baaffd3885685e6d2cddb27f2a Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Thu, 12 Nov 2026 12:25:11 +1100 +Subject: [PATCH 34/34] skippy: sample a wave through a configurable executor + +Concurrent sampling started one thread per request for every decode step and +joined them before returning: a thread create and join per token per request, +with no bound on how many ran at once. + +How a wave is sampled is now a skippy_sample_executor, chosen by the new +`sample_threads` runtime setting: + + 0 the calling thread plus helpers from a shared pool, as many as the wave + and the hardware allow (the default) + 1 the calling thread alone + N the pool, N threads at most + +The pool (skippy_task_pool) starts a helper the first time a run can use one, +up to one per spare hardware thread, and reuses them for every step, so a wide +machine serving many lanes gets as many samplers as it has requests and a small +one starts none it cannot use. A task's exception reaches the caller. The +wave's trace span names the executor. + +ABI 0.1.73: skippy_runtime_config gains sample_threads. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + include/skippy/common.h | 2 +- + include/skippy/runtime.h | 3 + + src/CMakeLists.txt | 2 + + src/skippy/batch_sampling.cpp | 30 +++--- + src/skippy/sample_executor.cpp | 17 ++++ + src/skippy/sample_executor.h | 50 ++++++++++ + src/skippy/task_pool.cpp | 97 ++++++++++++++++++ + src/skippy/task_pool.h | 59 +++++++++++ + tests/CMakeLists.txt | 1 + + tests/test-skippy-task-pool.cpp | 171 ++++++++++++++++++++++++++++++++ + 10 files changed, 415 insertions(+), 17 deletions(-) + create mode 100644 src/skippy/sample_executor.cpp + create mode 100644 src/skippy/sample_executor.h + create mode 100644 src/skippy/task_pool.cpp + create mode 100644 src/skippy/task_pool.h + create mode 100644 tests/test-skippy-task-pool.cpp + +diff --git a/include/skippy/common.h b/include/skippy/common.h +index b16229b1b..557ba5169 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -46,7 +46,7 @@ extern "C" { + + #define SKIPPY_ABI_VERSION_MAJOR 0 + #define SKIPPY_ABI_VERSION_MINOR 1 +-#define SKIPPY_ABI_VERSION_PATCH 72 ++#define SKIPPY_ABI_VERSION_PATCH 73 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) +diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h +index 31ce347ea..58b157319 100644 +--- a/include/skippy/runtime.h ++++ b/include/skippy/runtime.h +@@ -111,6 +111,9 @@ struct skippy_runtime_config { + /** @brief Whether attention reads a unified pool through per-owner row lists. AUTO and TRUE use row lists wherever the backend supports them; FALSE keeps ordinary attention over the whole pool, to measure one against the other. */ + int32_t kv_row_attention; + ++ /** @brief Threads that sample the requests of one decode wave. 0 uses the calling thread and as many pooled helpers as the wave and the hardware allow; 1 samples every request on the calling thread; any other value caps the calling thread plus helpers. */ ++ uint32_t sample_threads; ++ + // Model-load and context-creation controls resolved from `hardware` + // config. + /** @brief Whether the backend offloads host tensor operations to device (mirrors upstream `op_offload`). SKIPPY_TRISTATE_AUTO preserves llama.cpp's derived default (enabled); FALSE/TRUE force the value. */ +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 7dad15759..3aa224023 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -84,6 +84,8 @@ add_library(llama + ../common/llguidance.cpp + skippy/sampling.cpp + skippy/batch_sampling.cpp ++ skippy/task_pool.cpp ++ skippy/sample_executor.cpp + skippy/sampling_config.cpp + skippy/chat_sampling.cpp + skippy/sampling_vocab.cpp +diff --git a/src/skippy/batch_sampling.cpp b/src/skippy/batch_sampling.cpp +index e59c89857..0b01db542 100644 +--- a/src/skippy/batch_sampling.cpp ++++ b/src/skippy/batch_sampling.cpp +@@ -3,13 +3,12 @@ + #include "llama-context.h" + #include "skippy/runtime_types.h" + #include "skippy/sampling_internal.h" ++#include "skippy/sample_executor.h" + #include "skippy/trace_scope.h" + + #include + #include + #include +-#include +-#include + + namespace { + +@@ -25,8 +24,8 @@ llama_token sample(const skippy_sample_request & request) { + return skippy_sample_token_ith(request.session, request.sampling, request.logits_index); + } + +-// One helper thread per index after the first, which this thread samples. +-// Each thread writes only its own slot of `tokens`. ++// Samples through the executor the stage's `sample_threads` selects. Each ++// task writes only its own slot of `tokens`. + void sample_concurrently( + const std::vector & requests, + std::vector::const_iterator first, +@@ -35,24 +34,23 @@ void sample_concurrently( + std::vector & tokens) { + skippy_trace::scope trace("skippy.sample_concurrent", "requests", std::distance(first, last)); + const uint64_t parent = skippy_trace::current_parent(); +- const auto sample_reading = [&requests, &tokens, &outputs](size_t index) { ++ const auto sample_reading = [&](size_t index) { + const llama_output_reader reader(outputs); + tokens[index] = sample(requests[index]); + }; +- std::vector helpers; +- helpers.reserve(static_cast(std::distance(first, last))); +- std::for_each(std::next(first), last, [&](size_t index) { +- try { +- helpers.emplace_back([&sample_reading, index, parent] { +- const skippy_trace::adopt joined(parent); ++ const uint32_t sample_threads = requests[*first].session->stage_model->config.sample_threads; ++ skippy_with_sample_executor(sample_threads, [&](const skippy_sample_executor & executor) { ++ trace.set_detail(executor.name()); ++ executor.run(static_cast(std::distance(first, last)), [&](size_t slot, bool on_helper) { ++ const size_t index = *std::next(first, static_cast(slot)); ++ if (!on_helper) { + sample_reading(index); +- }); +- } catch (const std::system_error &) { ++ return; ++ } ++ const skippy_trace::adopt joined(parent); + sample_reading(index); +- } ++ }); + }); +- sample_reading(*first); +- std::for_each(helpers.begin(), helpers.end(), [](std::thread & helper) { helper.join(); }); + } + + bool share_context( +diff --git a/src/skippy/sample_executor.cpp b/src/skippy/sample_executor.cpp +new file mode 100644 +index 000000000..614074d52 +--- /dev/null ++++ b/src/skippy/sample_executor.cpp +@@ -0,0 +1,17 @@ ++#include "skippy/sample_executor.h" ++ ++#include ++#include ++#include ++#include ++ ++void skippy_inline_sampling::run(size_t count, const skippy_task_pool::task_fn & task) const { ++ std::vector indices(count); ++ std::iota(indices.begin(), indices.end(), size_t { 0 }); ++ std::for_each(indices.begin(), indices.end(), [&](size_t index) { task(index, false); }); ++} ++ ++void skippy_pooled_sampling::run(size_t count, const skippy_task_pool::task_fn & task) const { ++ const size_t max_helpers = threads == 0 ? std::numeric_limits::max() : threads - 1; ++ skippy_task_pool::shared().run(count, task, max_helpers); ++} +diff --git a/src/skippy/sample_executor.h b/src/skippy/sample_executor.h +new file mode 100644 +index 000000000..7eeb5937c +--- /dev/null ++++ b/src/skippy/sample_executor.h +@@ -0,0 +1,50 @@ ++#pragma once ++ ++// How the requests of a wave are sampled. `sample_threads` in ++// skippy_runtime_config picks the executor; a new strategy is a new ++// implementation and a new case in skippy_with_sample_executor. ++ ++#include "skippy/task_pool.h" ++ ++#include ++#include ++ ++class skippy_sample_executor { ++ public: ++ virtual ~skippy_sample_executor() = default; ++ ++ // names the executor on the wave's trace span ++ virtual const char * name() const = 0; ++ // Runs task for every index below count and returns once all have run. ++ virtual void run(size_t count, const skippy_task_pool::task_fn & task) const = 0; ++}; ++ ++// The calling thread samples every request in turn. ++class skippy_inline_sampling final : public skippy_sample_executor { ++ public: ++ const char * name() const override { return "inline"; } ++ void run(size_t count, const skippy_task_pool::task_fn & task) const override; ++}; ++ ++// The calling thread and helpers from the shared pool, `threads` at most; 0 ++// is as many as the wave and the hardware allow. ++class skippy_pooled_sampling final : public skippy_sample_executor { ++ public: ++ explicit skippy_pooled_sampling(uint32_t threads) : threads(threads) { ++ } ++ const char * name() const override { return "pool"; } ++ void run(size_t count, const skippy_task_pool::task_fn & task) const override; ++ ++ private: ++ uint32_t threads; ++}; ++ ++// Calls use(executor) with the executor `sample_threads` selects: 0 the pool ++// at its widest, 1 the calling thread alone, N the pool with N threads at most. ++template ++auto skippy_with_sample_executor(uint32_t sample_threads, Use && use) { ++ if (sample_threads == 1) { ++ return use(skippy_inline_sampling()); ++ } ++ return use(skippy_pooled_sampling(sample_threads)); ++} +diff --git a/src/skippy/task_pool.cpp b/src/skippy/task_pool.cpp +new file mode 100644 +index 000000000..88f8d3b59 +--- /dev/null ++++ b/src/skippy/task_pool.cpp +@@ -0,0 +1,97 @@ ++#include "skippy/task_pool.h" ++ ++#include ++#include ++#include ++#include ++ ++skippy_task_pool::skippy_task_pool(size_t ceiling) : limit(ceiling) { ++} ++ ++skippy_task_pool::~skippy_task_pool() { ++ { ++ const std::lock_guard lock(mutex); ++ stopping = true; ++ } ++ wake.notify_all(); ++ std::for_each(threads.begin(), threads.end(), [](std::thread & thread) { thread.join(); }); ++} ++ ++skippy_task_pool & skippy_task_pool::shared() { ++ static skippy_task_pool pool(std::max(2u, std::thread::hardware_concurrency()) - 1); ++ return pool; ++} ++ ++size_t skippy_task_pool::helpers() const { ++ const std::lock_guard lock(mutex); ++ return threads.size(); ++} ++ ++void skippy_task_pool::run(size_t n, const task_fn & fn, size_t max_helpers) { ++ if (n == 0) { ++ return; ++ } ++ const std::lock_guard one_run(turn); ++ const size_t wanted = std::min({ max_helpers, limit, n - 1 }); ++ { ++ const std::lock_guard lock(mutex); ++ try { ++ std::generate_n(std::back_inserter(threads), wanted - std::min(wanted, threads.size()), [this] { ++ return std::thread([this, ordinal = threads.size()] { serve(ordinal); }); ++ }); ++ } catch (const std::system_error &) { ++ // the helpers that did start, and the caller, still run every task ++ } ++ task = &fn; ++ count = n; ++ next = 0; ++ pending = n; ++ allowed = wanted; ++ failure = nullptr; ++ } ++ wake.notify_all(); ++ work(false); ++ ++ std::unique_lock lock(mutex); ++ idle.wait(lock, [this] { return pending == 0; }); ++ task = nullptr; ++ if (failure) { ++ std::rethrow_exception(std::exchange(failure, nullptr)); ++ } ++} ++ ++// Takes indices until none are left. ++void skippy_task_pool::work(bool on_helper) { ++ std::unique_lock lock(mutex); ++ while (task != nullptr && next < count) { ++ const size_t index = next++; ++ const task_fn * fn = task; ++ lock.unlock(); ++ std::exception_ptr thrown; ++ try { ++ (*fn)(index, on_helper); ++ } catch (...) { ++ thrown = std::current_exception(); ++ } ++ lock.lock(); ++ if (thrown && !failure) { ++ failure = thrown; ++ } ++ if (--pending == 0) { ++ idle.notify_all(); ++ } ++ } ++} ++ ++void skippy_task_pool::serve(size_t ordinal) { ++ std::unique_lock lock(mutex); ++ while (true) { ++ wake.wait(lock, [&] { return stopping || (task != nullptr && next < count && ordinal < allowed); }); ++ if (stopping) { ++ return; ++ } ++ lock.unlock(); ++ work(true); ++ lock.lock(); ++ } ++} +diff --git a/src/skippy/task_pool.h b/src/skippy/task_pool.h +new file mode 100644 +index 000000000..e33523ea7 +--- /dev/null ++++ b/src/skippy/task_pool.h +@@ -0,0 +1,59 @@ ++#pragma once ++ ++// Helper threads that outlive a call. A decode step samples one token for ++// every request of a wave; starting and joining a thread per request per step ++// costs more than the sampling it spreads, and has no bound. ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++class skippy_task_pool { ++ public: ++ // on_helper: the task runs on a pool thread, not the thread that called run() ++ using task_fn = std::function; ++ ++ // ceiling: the most helper threads the pool ever starts ++ explicit skippy_task_pool(size_t ceiling); ++ ~skippy_task_pool(); ++ ++ skippy_task_pool(const skippy_task_pool &) = delete; ++ skippy_task_pool & operator=(const skippy_task_pool &) = delete; ++ ++ // The pool every caller shares. Its ceiling is one helper per spare ++ // hardware thread, so it is as wide as the machine and no wider. ++ static skippy_task_pool & shared(); ++ ++ size_t ceiling() const { return limit; } ++ // helper threads started so far ++ size_t helpers() const; ++ ++ // Runs task for every index below count and returns once all have run, ++ // on the calling thread and at most max_helpers helpers. Helpers start ++ // the first time a run can use them: a run of n tasks uses n - 1 at most. ++ // Rethrows the first exception a task threw. Calls from different threads ++ // take turns. ++ void run(size_t count, const task_fn & task, size_t max_helpers); ++ ++ private: ++ void work(bool on_helper); ++ void serve(size_t ordinal); ++ ++ const size_t limit; ++ std::mutex turn; ++ mutable std::mutex mutex; ++ std::condition_variable wake; ++ std::condition_variable idle; ++ const task_fn * task = nullptr; // owned by the run() in progress ++ size_t count = 0; ++ size_t next = 0; ++ size_t pending = 0; ++ size_t allowed = 0; // helpers the run in progress may use ++ std::exception_ptr failure; ++ bool stopping = false; ++ std::vector threads; // grown by run() under `turn` ++}; +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index 595a84a26..452c0dd8f 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -195,6 +195,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) + llama_build_and_test(test-skippy-kv-cells-contiguous.cpp) + llama_build_and_test(test-skippy-kv-rows-aligned.cpp) + llama_build_and_test(test-skippy-kv-place-together.cpp) ++ llama_build_and_test(test-skippy-task-pool.cpp) + llama_build_and_test(test-skippy-recurrent-state-roundtrip.cpp) + # these tests are disabled on Windows because they use internal functions not exported with LLAMA_API (when building with shared libraries) + llama_build_and_test(test-unicode.cpp LABEL behavior LINK llama) +diff --git a/tests/test-skippy-task-pool.cpp b/tests/test-skippy-task-pool.cpp +new file mode 100644 +index 000000000..6bb6b040f +--- /dev/null ++++ b/tests/test-skippy-task-pool.cpp +@@ -0,0 +1,171 @@ ++// skippy_task_pool and the sampling executors over it: every index runs once, on a bounded ++// set of threads that later runs reuse, and a task's exception reaches the caller. ++#include "../src/skippy/sample_executor.h" ++#include "../src/skippy/task_pool.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++static int failures = 0; ++#define CHECK(cond) do { if (!(cond)) { ++failures; std::printf("FAIL line %d: %s\n", __LINE__, #cond); } } while (0) ++ ++static void every_index_runs_once() { ++ skippy_task_pool pool(3); ++ std::vector rounds(200); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { ++ std::vector> hits(17); ++ pool.run(hits.size(), [&](size_t index, bool) { hits[index]++; }, 3); ++ CHECK(std::all_of(hits.begin(), hits.end(), [](const std::atomic & hit) { return hit == 1; })); ++ }); ++} ++ ++static void threads_are_bounded_and_reused() { ++ skippy_task_pool pool(3); ++ std::mutex mutex; ++ std::set seen; ++ std::atomic running { 0 }; ++ std::atomic most { 0 }; ++ std::atomic on_helpers { 0 }; ++ std::vector rounds(300); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { ++ pool.run(16, [&](size_t, bool on_helper) { ++ const int now = ++running; ++ int before = most.load(); ++ while (now > before && !most.compare_exchange_weak(before, now)) { ++ } ++ on_helpers += on_helper ? 1 : 0; ++ { ++ const std::lock_guard lock(mutex); ++ seen.insert(std::this_thread::get_id()); ++ } ++ std::this_thread::yield(); ++ --running; ++ }, 3); ++ }); ++ CHECK(pool.helpers() == 3); ++ CHECK(seen.size() <= pool.helpers() + 1); ++ CHECK(most <= (int) pool.helpers() + 1); ++ CHECK(on_helpers > 0); ++ CHECK(seen.count(std::this_thread::get_id()) == 1); ++} ++ ++static void a_pool_without_helpers_runs_on_the_caller() { ++ skippy_task_pool pool(0); ++ int sum = 0; ++ pool.run(10, [&](size_t index, bool on_helper) { ++ CHECK(!on_helper); ++ sum += (int) index; ++ }, 8); ++ CHECK(sum == 45); ++ CHECK(pool.helpers() == 0); ++ pool.run(0, [&](size_t, bool) { CHECK(false); }, 8); ++} ++ ++static void an_exception_reaches_the_caller_and_the_pool_keeps_working() { ++ skippy_task_pool pool(2); ++ std::atomic ran { 0 }; ++ bool caught = false; ++ try { ++ pool.run(8, [&](size_t index, bool) { ++ ++ran; ++ if (index == 3) { ++ throw std::runtime_error("task 3"); ++ } ++ }, 2); ++ } catch (const std::runtime_error &) { ++ caught = true; ++ } ++ CHECK(caught); ++ CHECK(ran == 8); ++ std::atomic again { 0 }; ++ pool.run(8, [&](size_t, bool) { ++again; }, 2); ++ CHECK(again == 8); ++} ++ ++static void callers_on_different_threads_take_turns() { ++ skippy_task_pool pool(2); ++ std::atomic total { 0 }; ++ std::vector callers; ++ std::generate_n(std::back_inserter(callers), 4, [&] { ++ return std::thread([&] { ++ std::vector rounds(100); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { pool.run(5, [&](size_t, bool) { ++total; }, 2); }); ++ }); ++ }); ++ std::for_each(callers.begin(), callers.end(), [](std::thread & caller) { caller.join(); }); ++ CHECK(total == 4 * 100 * 5); ++} ++ ++// Helpers start when a run can use them, and a run never uses more than it asked for. ++static void the_pool_grows_to_demand_and_honours_each_runs_limit() { ++ skippy_task_pool pool(6); ++ CHECK(pool.helpers() == 0); ++ pool.run(1, [](size_t, bool) {}, 6); ++ CHECK(pool.helpers() == 0); ++ pool.run(3, [](size_t, bool) {}, 6); ++ CHECK(pool.helpers() == 2); ++ pool.run(64, [](size_t, bool) {}, 100); ++ CHECK(pool.helpers() == 6); ++ ++ std::atomic running { 0 }; ++ std::atomic most { 0 }; ++ std::atomic on_helpers { 0 }; ++ std::vector rounds(200); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { ++ pool.run(32, [&](size_t, bool on_helper) { ++ const int now = ++running; ++ int before = most.load(); ++ while (now > before && !most.compare_exchange_weak(before, now)) { ++ } ++ on_helpers += on_helper ? 1 : 0; ++ std::this_thread::yield(); ++ --running; ++ }, 1); ++ }); ++ CHECK(most <= 2); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { ++ pool.run(32, [&](size_t, bool on_helper) { CHECK(!on_helper); }, 0); ++ }); ++} ++ ++static void sample_threads_select_the_executor() { ++ const auto name_of = [](uint32_t sample_threads) { ++ return std::string(skippy_with_sample_executor(sample_threads, ++ [](const skippy_sample_executor & executor) { return executor.name(); })); ++ }; ++ CHECK(name_of(0) == "pool"); ++ CHECK(name_of(1) == "inline"); ++ CHECK(name_of(4) == "pool"); ++ ++ std::vector> hits(9); ++ skippy_inline_sampling().run(hits.size(), [&](size_t index, bool on_helper) { ++ CHECK(!on_helper); ++ hits[index]++; ++ }); ++ skippy_pooled_sampling(3).run(hits.size(), [&](size_t index, bool) { hits[index]++; }); ++ skippy_pooled_sampling(0).run(hits.size(), [&](size_t index, bool) { hits[index]++; }); ++ CHECK(std::all_of(hits.begin(), hits.end(), [](const std::atomic & hit) { return hit == 3; })); ++} ++ ++int main() { ++ every_index_runs_once(); ++ threads_are_bounded_and_reused(); ++ a_pool_without_helpers_runs_on_the_caller(); ++ an_exception_reaches_the_caller_and_the_pool_keeps_working(); ++ callers_on_different_threads_take_turns(); ++ the_pool_grows_to_demand_and_honours_each_runs_limit(); ++ sample_threads_select_the_executor(); ++ CHECK(skippy_task_pool::shared().helpers() <= skippy_task_pool::shared().ceiling()); ++ if (failures == 0) { ++ std::printf("ok\n"); ++ } ++ return failures == 0 ? 0 : 1; ++} +-- +2.43.0 + diff --git a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch index 617760cc44..b2344d0d7c 100644 --- a/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0004-skippy-add-diffusiongemma-system-one-reads.patch @@ -38,8 +38,8 @@ index 3448095a1..d04825da4 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 72 -+#define SKIPPY_ABI_VERSION_PATCH 73 +-#define SKIPPY_ABI_VERSION_PATCH 73 ++#define SKIPPY_ABI_VERSION_PATCH 74 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch index 6619fb10a1..33400752cd 100644 --- a/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch +++ b/skippy/llama_cpp/patches/model_support/0006-models-add-laya-decision-model-support.patch @@ -76,8 +76,8 @@ index d04825da4..54c87b6f2 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 73 -+#define SKIPPY_ABI_VERSION_PATCH 75 +-#define SKIPPY_ABI_VERSION_PATCH 74 ++#define SKIPPY_ABI_VERSION_PATCH 76 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch index b28ac444f5..52d5d1919d 100644 --- a/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch +++ b/skippy/llama_cpp/patches/model_support/0009-skippy-add-whisper-speech-recognition.patch @@ -223,8 +223,8 @@ index 54c87b6f2..80710eb3b 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 75 -+#define SKIPPY_ABI_VERSION_PATCH 77 +-#define SKIPPY_ABI_VERSION_PATCH 76 ++#define SKIPPY_ABI_VERSION_PATCH 78 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch index c7017a5589..d3b605d0cc 100644 --- a/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch +++ b/skippy/llama_cpp/patches/model_support/0010-skippy-record-per-token-logprobs-while-sampling.patch @@ -50,8 +50,8 @@ index 80710eb3b..93232a2b8 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 77 -+#define SKIPPY_ABI_VERSION_PATCH 80 +-#define SKIPPY_ABI_VERSION_PATCH 78 ++#define SKIPPY_ABI_VERSION_PATCH 81 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch index bfc409f8db..da1b74e6e1 100644 --- a/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch +++ b/skippy/llama_cpp/patches/model_support/0012-skippy-add-clef-joint-decision-reads.patch @@ -187,8 +187,8 @@ index 93232a2b8..d2ab5d538 100644 #define SKIPPY_ABI_VERSION_MAJOR 0 #define SKIPPY_ABI_VERSION_MINOR 1 --#define SKIPPY_ABI_VERSION_PATCH 80 -+#define SKIPPY_ABI_VERSION_PATCH 83 +-#define SKIPPY_ABI_VERSION_PATCH 81 ++#define SKIPPY_ABI_VERSION_PATCH 84 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 0c5434ac0a..08fd4945a2 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -555,6 +555,7 @@ if [[ "$LLAMA_STAGE_FULL_REPLAY" == "ON" ]]; then test-skippy-kv-page-export test-skippy-kv-rows-aligned test-skippy-kv-place-together + test-skippy-task-pool test-skippy-model-loader-accounting test-skippy-recurrent-state-roundtrip test-skippy-rerank-template diff --git a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs index 80ae069722..6697e682e3 100644 --- a/tools/xtask/tests/migration_package_source_version/encoding_approval.rs +++ b/tools/xtask/tests/migration_package_source_version/encoding_approval.rs @@ -49,7 +49,7 @@ const VALID_SOURCES: [(&str, &[u8], &[u8]); 2] = [ ( "abi", include_bytes!("../../../../skippy/crates/skippy-ffi/src/lib.rs"), - b"0.1.83\n", + b"0.1.84\n", ), ]; diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index fc71dd58e9..9133bb0aa5 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -244,6 +244,7 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( "test-skippy-kv-page-export", "test-skippy-kv-rows-aligned", "test-skippy-kv-place-together", + "test-skippy-task-pool", "test-skippy-model-loader-accounting", "test-skippy-recurrent-state-roundtrip", "test-skippy-rerank-template", From 22304681be03e4e8150717fdc85c87c95705946d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 36/81] test(skippy): add a concurrent wave to the cache reuse smoke --- skippy/crates/skippy-correctness/src/cli.rs | 7 + .../src/openai_cache_reuse.rs | 91 ++++++++++++- .../src/openai_cache_reuse/tests.rs | 128 +++++++++++++++++- skippy/scripts/skippy-ci-smoke.sh | 3 + 4 files changed, 223 insertions(+), 6 deletions(-) diff --git a/skippy/crates/skippy-correctness/src/cli.rs b/skippy/crates/skippy-correctness/src/cli.rs index dd30c36a2b..566e4f4df5 100644 --- a/skippy/crates/skippy-correctness/src/cli.rs +++ b/skippy/crates/skippy-correctness/src/cli.rs @@ -40,6 +40,13 @@ pub struct OpenAiCacheReuseArgs { pub max_tokens: u32, #[arg(long, default_value_t = 120)] pub request_timeout_secs: u64, + /// Requests sent at once after the sequential checks. Above one, the + /// grown chat is repeated as a wave of this many copies, then branched + /// into this many different follow-ups that are answered together and + /// again one at a time: every copy must match the sequential answer, and + /// every branch must give the same answer in a batch as alone. + #[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u16).range(1..=64))] + pub wave: u16, } #[derive(Args)] diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs index e318e4f066..560585cb6c 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse.rs @@ -1,6 +1,6 @@ -use std::{fs, time::Duration}; +use std::{fs, thread, time::Duration}; -use anyhow::{Context, Result, bail, ensure}; +use anyhow::{Context, Result, anyhow, bail, ensure}; use reqwest::blocking::Client; use serde_json::{Value, json}; @@ -45,11 +45,27 @@ pub fn run(args: OpenAiCacheReuseArgs) -> Result<()> { let grown_repeat = complete(&client, &url, &args.model, &growing_turn, args.max_tokens)?; require_hit("growing chat repeat", &grown_repeat)?; require_content("growing chat repeat", &grown_seed, &grown_repeat)?; + let wave_branches = if args.wave > 1 { + Some(check_wave( + &client, + &url, + &args, + &growing_turn, + &grown_seed, + )?) + } else { + None + }; println!( "{}", serde_json::to_string(&json!({ "status": "pass", "content_parity": "exact", + "wave": wave_branches.map(|branches| json!({ + "requests": args.wave, + "copies": "exact", + "branches": branches + })), "cold_content": seed.content, "repeat": { "cached_tokens": repeat.cached_tokens, @@ -71,6 +87,77 @@ pub fn run(args: OpenAiCacheReuseArgs) -> Result<()> { Ok(()) } +/// The concurrent half of the check: the requests of a wave share one batch, +/// one KV pool and one sampling pass, and each must come out as it does alone. +/// +/// Returns each branch's content. +fn check_wave( + client: &Client, + url: &str, + args: &OpenAiCacheReuseArgs, + growing_turn: &[Value], + grown_seed: &Completion, +) -> Result> { + let wave = usize::from(args.wave); + let copies = vec![growing_turn.to_vec(); wave]; + let together = complete_wave(client, url, &args.model, &copies, args.max_tokens)?; + for (index, copy) in together.iter().enumerate() { + let label = format!("wave copy {index}"); + require_hit(&label, copy)?; + require_content(&label, grown_seed, copy)?; + } + + let branches: Vec> = (0..wave) + .map(|index| { + let mut turn = growing_turn.to_vec(); + turn.push(json!({"role": "assistant", "content": grown_seed.content.clone()})); + turn.push(json!({ + "role": "user", + "content": format!("Reply with the number {index} and nothing else.") + })); + turn + }) + .collect(); + let batched = complete_wave(client, url, &args.model, &branches, args.max_tokens)?; + for (index, (turn, batched)) in branches.iter().zip(&batched).enumerate() { + let label = format!("wave branch {index}"); + require_hit(&label, batched)?; + ensure!( + !batched.content.is_empty(), + "{label} returned empty content" + ); + let alone = complete(client, url, &args.model, turn, args.max_tokens)?; + let label = format!("wave branch {index} alone"); + require_hit(&label, &alone)?; + require_content(&label, batched, &alone)?; + } + Ok(batched.into_iter().map(|branch| branch.content).collect()) +} + +/// Sends every turn at once and returns the completions in turn order. +fn complete_wave( + client: &Client, + url: &str, + model: &str, + turns: &[Vec], + max_tokens: u32, +) -> Result> { + thread::scope(|scope| { + let requests: Vec<_> = turns + .iter() + .map(|messages| scope.spawn(move || complete(client, url, model, messages, max_tokens))) + .collect(); + requests + .into_iter() + .map(|request| { + request + .join() + .map_err(|_| anyhow!("a wave request panicked"))? + }) + .collect() + }) +} + fn complete( client: &Client, url: &str, diff --git a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs index 0a4f751d38..5a9096139f 100644 --- a/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs +++ b/skippy/crates/skippy-correctness/src/openai_cache_reuse/tests.rs @@ -53,6 +53,19 @@ impl Peer { fn with_telemetry(cached: [Option; 4], content: [&str; 4]) -> Self { let content = content.map(str::to_owned); + Self::answering(move |index, _| { + ( + content.get(index).cloned().unwrap_or_default(), + cached.get(index).cloned().flatten(), + ) + }) + } + + /// A peer that answers request `index` with `respond(index, request)`: + /// the content and the cached-token count it reports, if any. + fn answering( + respond: impl Fn(usize, &Value) -> (String, Option) + Send + 'static, + ) -> Self { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); let base_url = format!("http://{}/v1", listener.local_addr().unwrap()); @@ -74,15 +87,15 @@ impl Peer { .unwrap(); let request = request_body(&mut stream); let index = requests.len(); + let (content, cached) = respond(index, &request); requests.push(request); let mut response = json!({ - "choices": [{"message": {"content": content.get(index).cloned().unwrap_or_default()}}], + "choices": [{"message": {"content": content}}], "usage": {"prompt_tokens": 100, "prompt_tokens_details": {}} }); - if let Some(Some(value)) = cached.get(index) { - response["usage"]["prompt_tokens_details"]["cached_tokens"] = - value.clone(); + if let Some(value) = cached { + response["usage"]["prompt_tokens_details"]["cached_tokens"] = value; } let response = response.to_string(); write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()).unwrap(); @@ -158,7 +171,114 @@ fn args(peer: &Peer, prompt: &Prompt) -> OpenAiCacheReuseArgs { prompt_file: prompt.0.clone(), max_tokens: 8, request_timeout_secs: 1, + wave: 1, + } +} + +/// A peer that answers every request from its last message alone, as a +/// deterministic server does whichever way a request reaches it. Only the +/// first request is cold. +fn consistent_peer() -> Peer { + Peer::answering(|index, request| { + let last = request["messages"] + .as_array() + .and_then(|messages| messages.last()) + .and_then(|message| message["content"].as_str()) + .unwrap_or_default(); + ( + format!("re: {last}"), + Some(json!(if index == 0 { 0 } else { 60 })), + ) + }) +} + +fn last_user_message(request: &Value) -> &str { + request["messages"] + .as_array() + .and_then(|messages| messages.last()) + .and_then(|message| message["content"].as_str()) + .unwrap() +} + +#[test] +fn a_wave_repeats_the_grown_chat_then_answers_each_branch_together_and_alone() { + let prompt = Prompt::new(); + let peer = consistent_peer(); + run(OpenAiCacheReuseArgs { + wave: 3, + ..args(&peer, &prompt) + }) + .unwrap(); + let requests = peer.finish(); + // four sequential, three copies, three branches together, three alone + assert_eq!(requests.len(), 4 + 3 + 3 + 3); + assert_eq!(requests[0], requests[1]); + assert_eq!(requests[2], requests[3]); + for copy in &requests[4..7] { + assert_eq!(copy, &requests[2], "a wave copy is the grown chat again"); + } + let mut together: Vec<&str> = requests[7..10].iter().map(last_user_message).collect(); + together.sort_unstable(); + assert_eq!( + together, + [ + "Reply with the number 0 and nothing else.", + "Reply with the number 1 and nothing else.", + "Reply with the number 2 and nothing else." + ] + ); + for request in &requests[7..] { + assert_eq!(request["messages"].as_array().unwrap().len(), 5); } + let alone: Vec<&str> = requests[10..].iter().map(last_user_message).collect(); + assert_eq!(alone, { + let mut sorted = alone.clone(); + sorted.sort_unstable(); + sorted + }); +} + +#[test] +fn a_branch_that_answers_differently_alone_fails_by_name() { + let prompt = Prompt::new(); + // the last request is branch 1 on its own + let peer = Peer::answering(|index, request| { + let last = last_user_message(request).to_owned(); + let content = if index == 4 + 2 + 2 + 1 { + "something else".to_owned() + } else { + format!("re: {last}") + }; + (content, Some(json!(if index == 0 { 0 } else { 60 }))) + }); + let error = run(OpenAiCacheReuseArgs { + wave: 2, + ..args(&peer, &prompt) + }) + .unwrap_err() + .to_string(); + assert!( + error.contains("wave branch 1 alone generated-content mismatch"), + "{error}" + ); +} + +#[test] +fn a_wave_copy_that_misses_the_cache_fails() { + let prompt = Prompt::new(); + let peer = Peer::answering(|index, request| { + let last = last_user_message(request).to_owned(); + let cached = if index == 0 || index >= 4 { 0 } else { 60 }; + (format!("re: {last}"), Some(json!(cached))) + }); + let error = run(OpenAiCacheReuseArgs { + wave: 2, + ..args(&peer, &prompt) + }) + .unwrap_err() + .to_string(); + assert!(error.contains("wave copy"), "{error}"); + assert!(error.contains("did not reuse a prompt prefix"), "{error}"); } fn assert_sequence(requests: &[Value]) { diff --git a/skippy/scripts/skippy-ci-smoke.sh b/skippy/scripts/skippy-ci-smoke.sh index 0e064af47f..4d421bf8c7 100755 --- a/skippy/scripts/skippy-ci-smoke.sh +++ b/skippy/scripts/skippy-ci-smoke.sh @@ -65,6 +65,8 @@ PROMPT_CTX_SIZE="${PROMPT_CTX_SIZE:-$CTX_SIZE}" STATE_PREFIX_TOKENS="${STATE_PREFIX_TOKENS:-128}" PROMPT_PREFILL_CHUNK_SIZE="${PROMPT_PREFILL_CHUNK_SIZE:-128}" PROMPT_MAX_NEW_TOKENS="${PROMPT_MAX_NEW_TOKENS:-8}" +# Requests the cache reuse smoke sends at once; the stage serves four lanes. +PROMPT_WAVE="${PROMPT_WAVE:-4}" SMOKE_COMMAND_TIMEOUT_SECS="${SMOKE_COMMAND_TIMEOUT_SECS:-900}" DENSE_CHAIN_STARTUP_TIMEOUT_SECS="${DENSE_CHAIN_STARTUP_TIMEOUT_SECS:-180}" SMOKE_FLASH_ATTN="${SMOKE_FLASH_ATTN:-disabled}" @@ -701,6 +703,7 @@ if ! LLAMA_STAGE_BUILD_DIR="$LLAMA_BUILD_DIR" \ --model "$DENSE_MODEL_ID" \ --prompt-file "$PROMPT_IN" \ --max-tokens "$PROMPT_MAX_NEW_TOKENS" \ + --wave "$PROMPT_WAVE" \ >"$PROMPT_OUT" 2>&1; then echo "staged cache reuse smoke failed; output follows" >&2 sed -n '1,260p' "$PROMPT_OUT" >&2 || true From c537fec65023539276bcd833f60f6904b90b2135 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:15 +1100 Subject: [PATCH 37/81] test(skippy): check row-list attention on the GPU for pooled list layouts --- .../skippy-api/src/split-certified.json | 2 +- ...list-attention-over-the-lists-a-unif.patch | 196 ++++++++++++++++++ skippy/scripts/build-llama.sh | 3 +- 3 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index e14b6ef603..a0ed8f4afa 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "372dc5ca157276beb6c67b2e92477e8d662e964a", "skippy_abi": "0.1.84", - "patch_queue_sha256": "659c3fbfe37ed379fabc0591588220fc5e0c54a8b3237ed687c477e96070b447" + "patch_queue_sha256": "4f4cbca470aa7b317c02876c86c0c7c5639eee6669fa0d69adb19cef915932ca" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch b/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch new file mode 100644 index 0000000000..4e30ede26d --- /dev/null +++ b/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch @@ -0,0 +1,196 @@ +From c146911d8fb5b122da53d74ec46b295ae70c7e79 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Thu, 12 Nov 2026 15:55:33 +1100 +Subject: [PATCH 35/35] tests: check row-list attention over the lists a + unified KV pool produces + +test-backend-ops compared row-list attention on a GPU backend with the CPU +only for lists of scattered cells with padding at the tail. A pool that keeps +a sequence's cells together produces a different shape: runs of consecutive +cells laid out in blocks of 32 entries, each run's last block ending in +padding. Metal reads such a block straight from the cache, and compiles the +gather out of the kernel when every block of every list qualifies, so the +paths most decode steps take had no backend-level check. + +test_flash_attn_ext_kv_rows_runs adds four layouts over the same op: + + consecutive one range filling whole blocks (the gather-free kernel) + runs_padded several runs, padding inside the list (gather-free) + run_at_cache_end a padded run in the cache's last cells, which a blind + whole-block read would overrun (the general kernel) + mixed consecutive and scattered blocks in one list + +On Metal builds the row-list cases run as the ctest +skippy_backend_ops_kv_rows, so the project's native test run includes them. + +Co-Authored-By: Claude Fable 5.2 +Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y +--- + tests/CMakeLists.txt | 5 ++ + tests/test-backend-ops.cpp | 113 +++++++++++++++++++++++++++++++++++-- + 2 files changed, 113 insertions(+), 5 deletions(-) + +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index 452c0dd8f..b1a34f1d2 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -393,6 +393,11 @@ if (GGML_METAL AND NOT GGML_BACKEND_DL) + endif() + + llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) ++if (GGML_METAL) ++ # row-list attention on the GPU against the CPU, for every list layout the unified KV ++ # pool produces; selected by the row-list cases' own parameter ++ llama_test(test-backend-ops NAME skippy_backend_ops_kv_rows LABEL "main" ARGS test -o FLASH_ATTN_EXT -p n_cells=) ++endif() + + llama_build_and_test(test-backend-tensor.cpp LINK ggml) + # per-call cost of ordinary vs row-list decode attention; a tool, not a test +diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp +index cd9d2b894..5a052fbca 100644 +--- a/tests/test-backend-ops.cpp ++++ b/tests/test-backend-ops.cpp +@@ -9013,11 +9013,8 @@ struct test_flash_attn_ext_kv_rows : public test_case { + return out; + } + +- void initialize_tensors(ggml_context * ctx) override { +- std::mt19937 gen(0x6B76); +- +- // per slice: distinct random cells, the tail of the list is padding +- rows.assign(kv*n_slices, -1); ++ // per slice: distinct random cells, the tail of the list is padding ++ virtual void fill_rows(std::mt19937 & gen) { + std::vector order(n_cells); + for (int64_t s = 0; s < n_slices; ++s) { + for (int64_t i = 0; i < n_cells; ++i) { +@@ -9029,6 +9026,13 @@ struct test_flash_attn_ext_kv_rows : public test_case { + rows[s*kv + i] = order[i]; + } + } ++ } ++ ++ void initialize_tensors(ggml_context * ctx) override { ++ std::mt19937 gen(0x6B76); ++ ++ rows.assign(kv*n_slices, -1); ++ fill_rows(gen); + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->view_src) { +@@ -9058,6 +9062,91 @@ struct test_flash_attn_ext_kv_rows : public test_case { + } + }; + ++// GGML_OP_FLASH_ATTN_EXT over the row lists a unified KV pool produces once a sequence's ++// cells sit together: runs of consecutive cells laid out in blocks of 32 list entries. ++// A backend may read such a block straight from the cache instead of gathering it, and ++// may drop the gather altogether when every block of every list qualifies. ++struct test_flash_attn_ext_kv_rows_runs : public test_flash_attn_ext_kv_rows { ++ enum layout_t { ++ // every list is one consecutive range filling whole blocks ++ LAYOUT_CONSECUTIVE, ++ // several runs per list; a run starts on a block and its last block ends in padding, ++ // so padding sits inside the list, not only at its tail ++ LAYOUT_RUNS_PADDED, ++ // as LAYOUT_RUNS_PADDED, with one run in the cache's last cells: its padded block ++ // would read past the end of the cache if a backend read whole blocks blindly ++ LAYOUT_RUN_AT_CACHE_END, ++ // consecutive blocks and scattered blocks in the same list ++ LAYOUT_MIXED, ++ }; ++ ++ const layout_t layout; ++ ++ static const int64_t block = 32; ++ ++ std::string vars() override { ++ static const char * const names[] = { "consecutive", "runs_padded", "run_at_cache_end", "mixed" }; ++ return test_flash_attn_ext_kv_rows::vars() + ",layout=" + names[layout]; ++ } ++ ++ test_flash_attn_ext_kv_rows_runs(layout_t layout, int64_t hs, int64_t nh, int64_t gqa, int64_t n_cells, int64_t kv, ++ int64_t nb, int64_t n_slices, ggml_type type_KV = GGML_TYPE_F16) ++ : test_flash_attn_ext_kv_rows(hs, nh, gqa, n_cells, kv, nb, n_slices, type_KV), layout(layout) { ++ GGML_ASSERT(kv % block == 0 && n_cells >= 2*kv); ++ } ++ ++ // one run of `len` cells from `first`, at list entry `at`; returns the entry after its last block ++ int64_t put_run(int64_t s, int64_t at, int64_t first, int64_t len) { ++ for (int64_t i = 0; i < len; ++i) { ++ rows[s*kv + at + i] = (int32_t) (first + i); ++ } ++ return at + (len + block - 1)/block*block; ++ } ++ ++ void fill_rows(std::mt19937 & gen) override { ++ for (int64_t s = 0; s < n_slices; ++s) { ++ switch (layout) { ++ case LAYOUT_CONSECUTIVE: { ++ put_run(s, 0, block*(1 + 3*s), kv); ++ } break; ++ case LAYOUT_RUNS_PADDED: ++ case LAYOUT_RUN_AT_CACHE_END: { ++ // runs of uneven length from disjoint parts of the cache, then all-padding blocks ++ const int64_t lens[] = { 3*block + 7, block - 1, 2*block, 5 + s }; ++ int64_t at = 0; ++ int64_t first = 64*(s + 1) + 3; ++ for (int64_t len : lens) { ++ if (at + (len + block - 1)/block*block > kv - block) { ++ break; ++ } ++ at = put_run(s, at, first, len); ++ first += len + 100; ++ } ++ if (layout == LAYOUT_RUN_AT_CACHE_END) { ++ put_run(s, at, n_cells - 5 - s, 5 + s); ++ } ++ } break; ++ case LAYOUT_MIXED: { ++ std::vector scattered(n_cells/2); ++ for (int64_t i = 0; i < (int64_t) scattered.size(); ++i) { ++ scattered[i] = (int32_t) (n_cells/2 + i); ++ } ++ std::shuffle(scattered.begin(), scattered.end(), gen); ++ for (int64_t b = 0; b < kv/block; ++b) { ++ if ((b + s) % 3 == 0) { ++ for (int64_t i = 0; i < block; ++i) { ++ rows[s*kv + b*block + i] = scattered[b*block + i]; ++ } ++ } else { ++ put_run(s, b*block, b*block + s, (b + s) % 3 == 1 ? block : block - 9); ++ } ++ } ++ } break; ++ } ++ } ++ } ++}; ++ + // GGML_OP_CROSS_ENTROPY_LOSS + struct test_cross_entropy_loss : public test_case { + const ggml_type type; +@@ -12671,6 +12760,20 @@ static std::vector> make_test_cases_eval() { + } + } + ++ // the same op over lists of consecutive runs in blocks of 32 entries ++ for (auto layout : { test_flash_attn_ext_kv_rows_runs::LAYOUT_CONSECUTIVE, ++ test_flash_attn_ext_kv_rows_runs::LAYOUT_RUNS_PADDED, ++ test_flash_attn_ext_kv_rows_runs::LAYOUT_RUN_AT_CACHE_END, ++ test_flash_attn_ext_kv_rows_runs::LAYOUT_MIXED }) { ++ for (int64_t nb : {1, 4, 64}) { ++ for (int64_t n_slices : {1, 4}) { ++ test_cases.emplace_back(new test_flash_attn_ext_kv_rows_runs(layout, 128, 8, 4, 4096, 512, nb, n_slices)); ++ test_cases.emplace_back(new test_flash_attn_ext_kv_rows_runs(layout, 256, 2, 8, 4096, 1024, nb, n_slices)); ++ test_cases.emplace_back(new test_flash_attn_ext_kv_rows_runs(layout, 64, 4, 2, 3000, 768, nb, n_slices, GGML_TYPE_Q8_0)); ++ } ++ } ++ } ++ + // sparse mask with large batch size + test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512)); + test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); +-- +2.43.0 + diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 08fd4945a2..588d44ba2d 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -564,7 +564,8 @@ if [[ "$LLAMA_STAGE_FULL_REPLAY" == "ON" ]]; then test-skippy-verify-checkpoint-retirement ) if [[ "$LLAMA_BACKEND" == "metal" ]]; then - BUILD_TARGETS+=(test-skippy-cachegen-metal test-skippy-tracing-metal) + # test-backend-ops runs as the ctest skippy_backend_ops_kv_rows + BUILD_TARGETS+=(test-skippy-cachegen-metal test-skippy-tracing-metal test-backend-ops) fi fi From ee8d792d239920e4d23996709c16d1668e169107 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 16:47:16 +1100 Subject: [PATCH 38/81] fix(skippy): give the task pool test the source include path --- .../skippy-api/src/split-certified.json | 2 +- ...wave-through-a-configurable-executor.patch | 19 ++++++++++--------- ...list-attention-over-the-lists-a-unif.patch | 6 +++--- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index a0ed8f4afa..c6f20e1075 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "372dc5ca157276beb6c67b2e92477e8d662e964a", "skippy_abi": "0.1.84", - "patch_queue_sha256": "4f4cbca470aa7b317c02876c86c0c7c5639eee6669fa0d69adb19cef915932ca" + "patch_queue_sha256": "9eacb23a0df358961f62f7e16c3b6eb405ef7717d2853aba3d6dfbaeaeab65b3" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch b/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch index 78ec96818d..e27ab257cf 100644 --- a/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch +++ b/skippy/llama_cpp/patches/0034-skippy-sample-a-wave-through-a-configurable-executor.patch @@ -1,7 +1,7 @@ -From 24b6a305317dc5baaffd3885685e6d2cddb27f2a Mon Sep 17 00:00:00 2001 +From 15f509711adba0dc9db0af0d098fd05cf5ce3914 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 12:25:11 +1100 -Subject: [PATCH 34/34] skippy: sample a wave through a configurable executor +Subject: [PATCH 34/35] skippy: sample a wave through a configurable executor Concurrent sampling started one thread per request for every decode step and joined them before returning: a thread create and join per token per request, @@ -34,9 +34,9 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y src/skippy/sample_executor.h | 50 ++++++++++ src/skippy/task_pool.cpp | 97 ++++++++++++++++++ src/skippy/task_pool.h | 59 +++++++++++ - tests/CMakeLists.txt | 1 + + tests/CMakeLists.txt | 2 + tests/test-skippy-task-pool.cpp | 171 ++++++++++++++++++++++++++++++++ - 10 files changed, 415 insertions(+), 17 deletions(-) + 10 files changed, 416 insertions(+), 17 deletions(-) create mode 100644 src/skippy/sample_executor.cpp create mode 100644 src/skippy/sample_executor.h create mode 100644 src/skippy/task_pool.cpp @@ -397,27 +397,28 @@ index 000000000..e33523ea7 + std::vector threads; // grown by run() under `turn` +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 595a84a26..452c0dd8f 100644 +index 595a84a26..97e08f3ec 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt -@@ -195,6 +195,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) +@@ -195,6 +195,8 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) llama_build_and_test(test-skippy-kv-cells-contiguous.cpp) llama_build_and_test(test-skippy-kv-rows-aligned.cpp) llama_build_and_test(test-skippy-kv-place-together.cpp) + llama_build_and_test(test-skippy-task-pool.cpp) ++ target_include_directories(test-skippy-task-pool PRIVATE ${PROJECT_SOURCE_DIR}/src) llama_build_and_test(test-skippy-recurrent-state-roundtrip.cpp) # these tests are disabled on Windows because they use internal functions not exported with LLAMA_API (when building with shared libraries) llama_build_and_test(test-unicode.cpp LABEL behavior LINK llama) diff --git a/tests/test-skippy-task-pool.cpp b/tests/test-skippy-task-pool.cpp new file mode 100644 -index 000000000..6bb6b040f +index 000000000..e9b9284e0 --- /dev/null +++ b/tests/test-skippy-task-pool.cpp @@ -0,0 +1,171 @@ +// skippy_task_pool and the sampling executors over it: every index runs once, on a bounded +// set of threads that later runs reuse, and a task's exception reaches the caller. -+#include "../src/skippy/sample_executor.h" -+#include "../src/skippy/task_pool.h" ++#include "skippy/sample_executor.h" ++#include "skippy/task_pool.h" + +#include +#include diff --git a/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch b/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch index 4e30ede26d..fb7e28b2ec 100644 --- a/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch +++ b/skippy/llama_cpp/patches/0035-tests-check-row-list-attention-over-the-lists-a-unif.patch @@ -1,4 +1,4 @@ -From c146911d8fb5b122da53d74ec46b295ae70c7e79 Mon Sep 17 00:00:00 2001 +From d21f04c41831e417d9d2e805ae225500882892d7 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 15:55:33 +1100 Subject: [PATCH 35/35] tests: check row-list attention over the lists a @@ -31,10 +31,10 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 2 files changed, 113 insertions(+), 5 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 452c0dd8f..b1a34f1d2 100644 +index 97e08f3ec..133ba2bf3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt -@@ -393,6 +393,11 @@ if (GGML_METAL AND NOT GGML_BACKEND_DL) +@@ -394,6 +394,11 @@ if (GGML_METAL AND NOT GGML_BACKEND_DL) endif() llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) From ea6de46d1479fc2cc84afe1cbe2e25702225b780 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 15 Nov 2026 16:12:15 +1100 Subject: [PATCH 39/81] fix(skippy): keep every concurrent session's exact-state entry past the hard cap The exact-state byte limits are estimated from attention KV metadata that cannot see hybrid recurrent state, so hybrid snapshots routinely exceed the soft cap several times over. The hard pass evicted down to a single entry, which turned the catalog into a single-entry cache where concurrent sessions evicted each other on every request: an AgentX comparison campaign measured prefix reuse collapsing from 46K cached tokens at concurrency 1 to zero at concurrency 4 on hybrid models, with TTFT following it from 1.5s to 29s. Both eviction passes now retain the same working-set floor, so the ceiling bounds growth above the floor instead of collapsing it. A diagnostic warns when the floor binds past the hard cap so operators can set an explicit exact-state budget. The AgentX harness gains AGENTX_SKIPPY_PREFIX_CACHE_BUDGET and AGENTX_SKIPPY_PREFIX_CACHE_RAM overrides, and the prefix-reuse probe that reproduced the regression is checked in under skippy/evals/agentx with the budget-knob distinction documented. --- .../src/kv_integration/config.rs | 120 ++++++++++++++---- skippy/evals/agentx/README.md | 28 ++++ skippy/evals/agentx/prefix-reuse-probe.py | 84 ++++++++++++ .../xtask/src/automation/agentx/lifecycle.rs | 65 ++++++++++ 4 files changed, 273 insertions(+), 24 deletions(-) create mode 100644 skippy/evals/agentx/prefix-reuse-probe.py diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index c73c63d2a9..2e0ae38c48 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -810,20 +810,37 @@ fn store_exact_radix_record_with_codec( } // Exact snapshots are indivisible, and the soft cap is estimated from // attention KV metadata that cannot include architecture-specific - // recurrent state, so one snapshot can legitimately exceed it. Hold a small + // recurrent state, so one snapshot can legitimately exceed it. Hold a // working set past the soft cap (never more than the configured entry // limit) so concurrent sessions on a stage stop evicting each other, then - // apply the hard limit so that allowance stays bounded apart from one - // indivisible snapshot. Neither pass evicts the last entry: a snapshot that - // self-evicts disables exact prefix caching for the stage entirely, which - // is the regression this retention policy exists to prevent. - evict_exact_entries_over( - radix, - blobs, - limits.soft_bytes, - EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries), - )?; - evict_exact_entries_over(radix, blobs, limits.hard_bytes, 1)?; + // apply the hard limit so that allowance stays bounded. + // + // Both passes retain the same floor. A hard pass that fell to a single + // entry defeated the working-set guarantee whenever hybrid snapshots + // (whose recurrent state the attention-derived estimate cannot see) + // pushed the retained set past the hard cap: the catalog collapsed to a + // single entry and concurrent sessions evicted each other on every + // request, which is the regression this policy exists to prevent. The + // retention floor may exceed either byte limit by design; operators who + // need a tighter bound set an explicit exact-state budget. + let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); + evict_exact_entries_over(radix, blobs, limits.soft_bytes, retention_floor)?; + if evict_exact_entries_over(radix, blobs, limits.hard_bytes, retention_floor)? > 0 { + // Observable signal that the attention-derived estimate undercounts + // this stage's snapshots: the exact-state catalog held more than the + // hard limit even with the retention floor binding. Set an explicit + // exact-state budget when this repeats and memory must stay bounded. + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "exact-state catalog exceeded its hard byte limit at the retention floor" + .to_string(), + context: Some(format!( + "soft_bytes={} hard_bytes={} floor_entries={retention_floor}", + limits.soft_bytes, limits.hard_bytes + )), + }, + ); + } #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); @@ -907,11 +924,12 @@ fn evict_exact_entries_over( blobs: &Mutex, limit_bytes: u64, min_retained_entries: usize, -) -> Result<()> { +) -> Result { if limit_bytes == 0 { - return Ok(()); + return Ok(0); } let floor = min_retained_entries.max(1); + let mut evicted_total = 0usize; loop { let over_bytes = blobs .lock() @@ -934,13 +952,14 @@ fn evict_exact_entries_over( let Some(evicted) = evicted else { break; }; + evicted_total += 1; evicted.value.payload.release_from( &mut blobs .lock() .unwrap_or_else(std::sync::PoisonError::into_inner), )?; } - Ok(()) + Ok(evicted_total) } /// Either kill-switch variable resolving to `off` disables the cache, so an @@ -1269,6 +1288,46 @@ mod tests { ); } + #[test] + fn exact_state_retention_floor_survives_a_hard_cap_blind_to_recurrent_state() { + // Regression: the byte limits are derived from attention KV metadata, + // so hybrid snapshots (recurrent state the estimate cannot see) can + // push the retained working set past the hard cap. The retention floor + // must keep every concurrent session's entry; collapsing to a single + // entry made sessions evict each other on every request. + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + // Each snapshot is 32 bytes; four of them (128) exceed the hard cap + // of 80 even though each individually fits the 8x headroom. + let oversized_for_attention_estimate = limits(10, 80); + for index in 0..4 { + store_exact_radix_record( + &radix, + &blobs, + 512, + oversized_for_attention_estimate, + None, + None, + pending( + &format!("session-{index}"), + &[1, index + 2], + &[index as u8 + 1; 32], + &budget, + ), + ) + .unwrap(); + } + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 4); + for index in 0..4 { + assert!( + radix.lookup_recurrent("model", &[1, index + 2]).is_some(), + "session {index} must retain its exact-state entry" + ); + } + } + #[test] fn selected_l3_fill_promotes_to_l2_on_the_record_worker_path() { let radix = Mutex::new(UnifiedRadixCache::new()); @@ -1546,15 +1605,21 @@ mod tests { } #[test] - fn exact_working_set_is_bounded_by_the_hard_ceiling() { + fn exact_working_set_is_bounded_by_the_retention_floor_not_the_ceiling() { let radix = Mutex::new(UnifiedRadixCache::new()); let blobs = Mutex::new(CacheBlobStore::new(4)); let budget = StorageBudget::new(); + // Six sessions' snapshots against byte limits smaller than one + // snapshot, as happens when the attention-derived estimate cannot see + // hybrid recurrent state. for (page_id, tokens, bytes) in [ - ("first", [1, 2], b"aaaabbbb"), - ("second", [1, 3], b"ccccdddd"), - ("third", [1, 4], b"eeeeffff"), + ("s1", [1, 2], b"aaaabbbb"), + ("s2", [1, 3], b"ccccdddd"), + ("s3", [1, 4], b"eeeeffff"), + ("s4", [1, 5], b"gggghhhh"), + ("s5", [1, 6], b"iiiijjjj"), + ("s6", [1, 7], b"kkkkllll"), ] { store_exact_radix_record( &radix, @@ -1568,14 +1633,21 @@ mod tests { .unwrap(); } - // The retention floor yields to the ceiling, leaving the most recent - // snapshot rather than an unbounded working set. + // The ceiling still bounds the working set above the retention floor: + // the two least-recently-used snapshots go. At the floor the ceiling + // yields, because collapsing to a single entry made concurrent + // sessions evict each other on every request. let mut radix = radix.lock().unwrap(); - assert_eq!(radix.stats().recurrent_entries, 1); + assert_eq!(radix.stats().recurrent_entries, 4); assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); assert!(radix.lookup_recurrent("model", &[1, 3]).is_none()); - assert!(radix.lookup_recurrent("model", &[1, 4]).is_some()); - assert_eq!(blobs.lock().unwrap().physical_bytes(), 8); + for tokens in [[1, 4], [1, 5], [1, 6], [1, 7]] { + assert!( + radix.lookup_recurrent("model", &tokens).is_some(), + "the retention floor must keep the newest four sessions" + ); + } + assert_eq!(blobs.lock().unwrap().physical_bytes(), 32); } #[test] diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index dae1f5f95a..c047220047 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -197,3 +197,31 @@ an explicit nonzero exit, another signal, or forced cleanup fails the campaign. The ordinary CI/GPU suite and registered JY templates are unchanged. This benchmark owner does not mark the long-prefix/cancellation/L3 TODO complete. + +## Prefix-reuse probe + +`prefix-reuse-probe.py` reproduces the exact-state retention regression: N +interleaved multi-turn conversations with append-only histories against one +`skippy serve`, reporting `cached_tokens` per request. Any miss after each +conversation's first turn is a retention defect, not prompt churn. Exit code 1 +on any post-first-turn miss. + +``` +# serve with the knobs under test, then: +python3 skippy/evals/agentx/prefix-reuse-probe.py 64000 4 6 6300 +``` + +Two distinct prefix-cache budgets matter for retention experiments, and A/B +runs must move the intended one: + +- `--prefix-cache-budget` (`kv_cache.max_bytes`) bounds the exact-state + catalog; its auto default is estimated from attention KV metadata and can + undercount hybrid recurrent state. The retention floor keeps concurrent + sessions' entries alive past this cap. +- `--prefix-cache-ram` (`kv_cache.l2_max_bytes`) bounds resident-checkpoint + RAM and is independent of the exact-state catalog. + +The AgentX comparison harness exposes both for its skippy arm through +`AGENTX_SKIPPY_PREFIX_CACHE_BUDGET` and `AGENTX_SKIPPY_PREFIX_CACHE_RAM`, so +fleet campaigns can encode and reproduce retention experiments without +editing the harness. diff --git a/skippy/evals/agentx/prefix-reuse-probe.py b/skippy/evals/agentx/prefix-reuse-probe.py new file mode 100644 index 0000000000..bf1e07c33d --- /dev/null +++ b/skippy/evals/agentx/prefix-reuse-probe.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Prefix-reuse probe for skippy serve. + +Replays N interleaved multi-turn conversations with append-only histories +against a running skippy serve and reports per-request cached tokens from the +OpenAI usage payload. This is the minimal reproduction for the exact-state +retention regression where concurrent sessions evicted each other down to a +single catalog entry (see kv_integration/config.rs retention floor). + +Usage: + python3 prefix-reuse-probe.py [port] [nconv] [turns] [block_chars] + +The probe is intentionally dependency-free (urllib only). Conversations use a +stable per-conversation filler so each turn's prompt is a strict extension of +the previous turn's prompt; any cache miss beyond the first turn therefore +measures retention, not prompt churn. +""" +import concurrent.futures +import json +import sys +import time +import urllib.request + +PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 64000 +NCONV = int(sys.argv[2]) if len(sys.argv) > 2 else 4 +TURNS = int(sys.argv[3]) if len(sys.argv) > 3 else 6 +BLOCK = int(sys.argv[4]) if len(sys.argv) > 4 else 6300 + + +def convo(i: int, turn: int): + filler = f"Session {i} stable context block. " * 220 + history = "\n".join( + f"User: {filler[:BLOCK * k]} Question {i}-{k}: name a color." + for k in range(1, turn + 1) + ) + return [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": history + f" Q{i}-{turn}: color now."}, + ] + + +def ask(i: int, turn: int): + body = json.dumps( + {"model": "probe", "messages": convo(i, turn), "max_tokens": 8, "temperature": 0} + ).encode() + t0 = time.time() + r = urllib.request.urlopen( + urllib.request.Request( + f"http://127.0.0.1:{PORT}/v1/chat/completions", + data=body, + headers={"Content-Type": "application/json"}, + ), + timeout=1800, + ) + out = json.load(r) + usage = out.get("usage", {}) + detail = usage.get("prompt_tokens_details", {}) or {} + return ( + i, + turn, + usage.get("prompt_tokens", 0), + detail.get("cached_tokens", 0), + time.time() - t0, + ) + + +def main() -> int: + print(f"probe: {NCONV} conversations x {TURNS} turns, concurrent per turn") + misses = 0 + for turn in range(2, TURNS + 1): + with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: + for i, t, prompt, cached, dt in ex.map(lambda i: ask(i, turn), range(NCONV)): + hit = cached > 0 + misses += 0 if hit else 1 + print( + f" turn {t} conv {i}: prompt {prompt} cached {cached} " + f"({100 * cached / max(prompt, 1):.0f}%) {dt:.1f}s" + ) + print(f"misses-after-first-turn: {misses}") + return 0 if misses == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/xtask/src/automation/agentx/lifecycle.rs b/tools/xtask/src/automation/agentx/lifecycle.rs index ce9d2751ba..f00150ca29 100644 --- a/tools/xtask/src/automation/agentx/lifecycle.rs +++ b/tools/xtask/src/automation/agentx/lifecycle.rs @@ -18,6 +18,8 @@ const LLAMA_KV_UNIFIED_ENV: &str = "AGENTX_LLAMA_KV_UNIFIED"; const SKIPPY_KV_UNIFIED_ENV: &str = "AGENTX_SKIPPY_KV_UNIFIED"; const SKIPPY_MICROBATCH_TOKENS_ENV: &str = "AGENTX_SKIPPY_MICROBATCH_TOKENS"; const SKIPPY_GENERATION_CONCURRENCY_ENV: &str = "AGENTX_SKIPPY_GENERATION_CONCURRENCY"; +const SKIPPY_PREFIX_CACHE_BUDGET_ENV: &str = "AGENTX_SKIPPY_PREFIX_CACHE_BUDGET"; +const SKIPPY_PREFIX_CACHE_RAM_ENV: &str = "AGENTX_SKIPPY_PREFIX_CACHE_RAM"; const BASELINE_MICROBATCH_TOKENS: usize = 512; const TELEMETRY_FILE: &str = "skippy-telemetry.otlp.jsonl"; const BATCH_TOKENS: usize = 2_048; @@ -113,6 +115,17 @@ fn positive_override(name: &str, value: &str) -> DynResult { } } +/// Text-valued env override for IEC byte budgets (`64GiB`) and other raw +/// settings values that are passed through verbatim after presence check. +fn text_env_override(name: &str) -> DynResult> { + match std::env::var(name) { + Ok(value) if !value.trim().is_empty() => Ok(Some(value.trim().to_string())), + Ok(_) => Err(format!("{name} must not be empty").into()), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(error) => Err(format!("{name}: {error}").into()), + } +} + fn positive_env_override(name: &str) -> DynResult> { match std::env::var(name) { Ok(value) => positive_override(name, &value).map(Some), @@ -147,10 +160,38 @@ fn skippy_diagnostic_arguments(generation_concurrency: Option) -> Vec, + ram: Option, +) -> Vec { + let mut arguments = Vec::new(); + if let Some(budget) = budget { + arguments.extend(["--prefix-cache-budget".to_string(), budget]); + } + if let Some(ram) = ram { + arguments.extend(["--prefix-cache-ram".to_string(), ram]); + } + arguments +} + +fn skippy_prefix_cache_budget_override() -> DynResult> { + Ok(skippy_prefix_cache_budget_arguments( + text_env_override(SKIPPY_PREFIX_CACHE_BUDGET_ENV)?, + text_env_override(SKIPPY_PREFIX_CACHE_RAM_ENV)?, + )) +} + fn skippy_overrides() -> DynResult> { let mut arguments = skippy_diagnostic_arguments(positive_env_override(SKIPPY_GENERATION_CONCURRENCY_ENV)?); arguments.extend(skippy_kv_layout_override()?); + arguments.extend(skippy_prefix_cache_budget_override()?); Ok(arguments) } @@ -927,6 +968,30 @@ mod tests { } } + #[test] + fn skippy_prefix_cache_budget_overrides_target_distinct_budgets() { + // The exact-state retention cap and the resident-checkpoint RAM budget + // are different knobs; each env override must reach its own flag. + assert_eq!( + skippy_prefix_cache_budget_arguments(Some("64GiB".into()), None), + ["--prefix-cache-budget".to_string(), "64GiB".to_string()] + ); + assert_eq!( + skippy_prefix_cache_budget_arguments(None, Some("8GiB".into())), + ["--prefix-cache-ram".to_string(), "8GiB".to_string()] + ); + assert_eq!( + skippy_prefix_cache_budget_arguments(Some("unbounded".into()), Some("off".into())), + [ + "--prefix-cache-budget".to_string(), + "unbounded".to_string(), + "--prefix-cache-ram".to_string(), + "off".to_string() + ] + ); + assert!(skippy_prefix_cache_budget_arguments(None, None).is_empty()); + } + #[test] fn llama_cache_budget_control_is_explicit_and_rejects_invalid_values() { assert_eq!(parse_llama_cache_ram_mib("65536").unwrap(), 65536); From e821ec38b618edee671a2bb3bb7d010ba6ca078a Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 07:13:10 +1100 Subject: [PATCH 40/81] fix(skippy): scale exact-state capture admission with the serving lane count The admission budget allowed exactly one best-effort record capture in flight per stage (channel capacity plus one worker-held record, a single-stream sizing). Under concurrent multi-turn sessions, whichever session completed first held the only slot and every other lane's capture was declined; a declined capture loses that exchange permanently, so the session's next turn re-prefilled it. Fleet campaigns measured the result as a reuse ceiling: dense models retained roughly two-thirds of their prefix at concurrency four, and the capture-heavy hybrid models retained nothing at all. Admission slots now scale as max(floor, lane_count + 1), preserving the reserved continuation share and every existing single-stream guarantee. The reserved-admission harness is unchanged and green; a new regression test pins four concurrent lanes each admitting their capture with the continuation share intact. --- .../src/kv_integration/config.rs | 7 + .../src/kv_integration/exact_state.rs | 136 +++++++++++++++--- .../src/kv_integration/l2_serving.rs | 1 + .../skippy-serving/src/kv_integration/mod.rs | 12 +- 4 files changed, 136 insertions(+), 20 deletions(-) diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 2e0ae38c48..e6bcc2ad4d 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -247,6 +247,10 @@ impl KvStageIntegration { let worker_exact_state_records_pending = exact_state_records_pending.clone(); let admission_outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let admission_best_effort_outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let admission_total_cap = + crate::kv_integration::exact_state::exact_state_admission_total_for_lanes( + config.lane_count, + ); #[cfg(test)] let exact_state_worker_received = Arc::new(std::sync::atomic::AtomicUsize::new(0)); #[cfg(test)] @@ -391,6 +395,7 @@ impl KvStageIntegration { exact_state_records_pending, admission_outstanding, admission_best_effort_outstanding, + admission_total_cap, #[cfg(test)] exact_state_captures_outstanding: Arc::new(std::sync::atomic::AtomicUsize::new(0)), #[cfg(test)] @@ -1072,6 +1077,7 @@ mod tests { crate::kv_integration::exact_state::ExactStateAdmissionCredit::acquire( &self.total, &self.best_effort, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, crate::kv_integration::exact_state::CaptureAdmission::Continuation, ) .expect("a fresh per-test budget must admit") @@ -1839,6 +1845,7 @@ mod reserved_admission_harness { ExactStateAdmissionCredit::acquire( &kv.admission_outstanding, &kv.admission_best_effort_outstanding, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, class, ) } diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index 137a420a06..1895edaba8 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -70,6 +70,18 @@ pub const EXACT_STATE_ADMISSION_TOTAL: usize = 2; /// boundary always finds a slot unless the whole budget is exhausted. pub const EXACT_STATE_ADMISSION_RESERVED: usize = 1; +/// Per-stage total admission slots. The single-stream floor is the legacy +/// constant (channel capacity plus one worker-held record); a stage serving +/// `lane_count` concurrent lanes admits one in-flight payload per lane plus +/// the recorder's own headroom, because a capture declined under admission +/// loses that session's exchange permanently — the next turn re-prefills it. +/// Concurrent multi-turn sessions measured on the fleet starved at the floor: +/// whichever session completed first held the only best-effort slot and every +/// other lane's record was declined for the whole wave. +pub(crate) fn exact_state_admission_total_for_lanes(lane_count: u32) -> usize { + EXACT_STATE_ADMISSION_TOTAL.max(lane_count as usize + 1) +} + /// Move-only credit for one in-flight exact-state payload. Construction /// reserves a slot atomically (CAS, so competing producers cannot /// oversubscribe the budget); Drop releases it exactly once on every terminal @@ -88,14 +100,16 @@ impl ExactStateAdmissionCredit { pub(crate) fn acquire( total: &Arc, best_effort: &Arc, + total_cap: usize, class: CaptureAdmission, ) -> Option { + let total_cap = total_cap.max(EXACT_STATE_ADMISSION_TOTAL); use std::sync::atomic::Ordering::{AcqRel, Acquire}; match class { CaptureAdmission::Continuation => { let mut observed = total.load(Acquire); loop { - if observed >= EXACT_STATE_ADMISSION_TOTAL { + if observed >= total_cap { return None; } match total.compare_exchange_weak(observed, observed + 1, AcqRel, Acquire) { @@ -112,7 +126,7 @@ impl ExactStateAdmissionCredit { } } CaptureAdmission::BestEffort => { - let reserved_cap = EXACT_STATE_ADMISSION_TOTAL - EXACT_STATE_ADMISSION_RESERVED; + let reserved_cap = total_cap - EXACT_STATE_ADMISSION_RESERVED; let mut observed_best_effort = best_effort.load(Acquire); loop { if observed_best_effort >= reserved_cap { @@ -132,7 +146,7 @@ impl ExactStateAdmissionCredit { // if the total budget was exhausted concurrently. let mut observed_total = total.load(Acquire); loop { - if observed_total >= EXACT_STATE_ADMISSION_TOTAL { + if observed_total >= total_cap { best_effort.fetch_sub(1, AcqRel); return None; } @@ -392,6 +406,7 @@ impl KvStageIntegration { && let Some(admission_credit) = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) && self.try_begin_record(&page_id) @@ -523,6 +538,7 @@ impl KvStageIntegration { let Some(mut admission_credit) = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, admission, ) else { #[cfg(test)] @@ -955,6 +971,7 @@ impl KvStageIntegration { let rewarm_enqueued = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) .is_some_and(|admission_credit| { @@ -1226,6 +1243,7 @@ mod admission_credit_tests { let guard = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!(guard.is_some(), "fresh budget admits Continuation"); @@ -1240,17 +1258,20 @@ mod admission_credit_tests { let first = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); let second = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!(first.is_some() && second.is_some(), "two slots for TOTAL=2"); let third = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!( @@ -1263,11 +1284,19 @@ mod admission_credit_tests { #[test] fn best_effort_declines_at_reserved_cap_even_with_budget_headroom() { let (total, best_effort) = counters(); - let first = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let first = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!(first.is_some()); - let second = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let second = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!( second.is_none(), "BestEffort cap is TOTAL - RESERVED = 1; second must decline" @@ -1275,15 +1304,68 @@ mod admission_credit_tests { assert_eq!(best_effort.load(Ordering::Acquire), 1); } + #[test] + fn multi_lane_stages_admit_one_capture_per_lane() { + // Fleet regression: concurrent multi-turn sessions starved at the + // single-stream floor — whichever session completed first held the + // only best-effort slot and every other lane's capture was declined, + // so its exchange was lost and its next turn re-prefilled it. A stage + // serving four lanes must admit four concurrent captures. + let (total, best_effort) = counters(); + let cap = super::exact_state_admission_total_for_lanes(4); + assert_eq!(cap, 5, "four lanes plus recorder headroom"); + let held: Vec<_> = (0..4) + .map(|_| { + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::BestEffort, + ) + }) + .collect(); + assert!( + held.iter().all(|credit| credit.is_some()), + "every lane's capture must be admitted" + ); + assert_eq!(total.load(Ordering::Acquire), 4); + let continuation = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::Continuation, + ); + assert!( + continuation.is_some(), + "the reserved continuation share still admits" + ); + assert_eq!(total.load(Ordering::Acquire), 5); + assert!( + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + cap, + CaptureAdmission::BestEffort + ) + .is_none(), + "budget exhausted at the lane-scaled cap" + ); + } + #[test] fn continuation_admits_after_best_effort_under_reserved_share() { let (total, best_effort) = counters(); - let best = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let best = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!(best.is_some(), "BestEffort takes its single slot"); let cont = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); assert!( @@ -1317,9 +1399,12 @@ mod admission_credit_tests { } else { CaptureAdmission::BestEffort }; - if let Some(credit) = - ExactStateAdmissionCredit::acquire(&total, &best_effort, class) - { + if let Some(credit) = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + class, + ) { held.push((class, credit)); } } @@ -1360,6 +1445,7 @@ mod admission_credit_tests { let credit = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("topping up an under-subscribed budget must succeed"); @@ -1383,7 +1469,8 @@ mod admission_credit_tests { ExactStateAdmissionCredit::acquire( &total, &best_effort, - CaptureAdmission::BestEffort + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, ) .is_none(), "an exhausted budget must decline every BestEffort attempt" @@ -1414,10 +1501,15 @@ mod admission_credit_tests { let recovery_continuation = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ); - let recovery_best_effort = - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort); + let recovery_best_effort = ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, + ); assert!( recovery_continuation.is_some() && recovery_best_effort.is_some(), "budget must recover after the drain" @@ -1441,12 +1533,14 @@ mod admission_credit_tests { let first = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("first Continuation admitted"); let second = ExactStateAdmissionCredit::acquire( &total, &best_effort, + EXACT_STATE_ADMISSION_TOTAL, CaptureAdmission::Continuation, ) .expect("second Continuation admitted"); @@ -1466,7 +1560,8 @@ mod admission_credit_tests { ExactStateAdmissionCredit::acquire( &total, &best_effort, - CaptureAdmission::BestEffort + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort, ) .is_none(), "a continuation-exhausted budget must decline every BestEffort via rollback" @@ -1494,8 +1589,13 @@ mod admission_credit_tests { assert_eq!(total.load(Ordering::Acquire), 0); assert_eq!(best_effort.load(Ordering::Acquire), 0); assert!( - ExactStateAdmissionCredit::acquire(&total, &best_effort, CaptureAdmission::BestEffort) - .is_some(), + ExactStateAdmissionCredit::acquire( + &total, + &best_effort, + EXACT_STATE_ADMISSION_TOTAL, + CaptureAdmission::BestEffort + ) + .is_some(), "budget recovers after the drain" ); } diff --git a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs index 3bb264da91..7e0c3a9812 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -328,6 +328,7 @@ impl KvStageIntegration { let rewarm_enqueued = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) .is_some_and(|admission_credit| { diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 1190ea75b8..1501237cdd 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -204,6 +204,9 @@ pub struct KvStageIntegration { /// the worker. See `ExactStateAdmissionCredit`. pub(crate) admission_outstanding: Arc, pub(crate) admission_best_effort_outstanding: Arc, + /// Per-stage admission ceiling, scaled by lane count; see + /// `exact_state::exact_state_admission_total_for_lanes`. + pub(crate) admission_total_cap: usize, /// Test-only outstanding-capture tracking: incremented when a capture task /// is scheduled onto the iteration scheduler, released when that task /// reaches ANY terminal outcome (recorded, skipped, error, panic) via a @@ -1420,8 +1423,13 @@ mod exact_state_record_queue_tests { best_effort: &Arc, class: CaptureAdmission, ) -> ExactStateAdmissionCredit { - ExactStateAdmissionCredit::acquire(total, best_effort, class) - .expect("a fresh budget must admit") + ExactStateAdmissionCredit::acquire( + total, + best_effort, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, + class, + ) + .expect("a fresh budget must admit") } struct RecordingObserver(Arc>>); From 2b25bb61094e0576939ca94d30345bd13e8756ca Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 07:56:09 +1100 Subject: [PATCH 41/81] feat(xtask): reproducible parallel AgentX fleet benchmarks automation agentx fleet turns a committed manifest (kit pins, model pins, probe shape) into one hardware-routed jy job per run, submits them in parallel, and stamps a run root; fleet-status reports the run root. Every kit URL is range-probed before anything is submitted - fresh CDN uploads can take minutes to reach every edge and the fleet learned this the hard way. Workers are repo-owned (skippy/evals/agentx/fleet-worker.sh for the full provenance-pinned comparison, fleet-smoke-worker.sh for the llama-vs-skippy smoke probe) and embedded by SHA, so a manifest plus a commit reproduces a whole campaign. Model pins live in fleet-models.json. Placement stays hardware-only: os target plus the workers' arch and memory guards; the skill forbids node names. The operational rules this machinery encodes (end-of-job results, clean- exit artifacts, guard-bounce requeues, scavenge recovery) are captured in .agents/skills/agentx-fleet-bench so any agent reproduces the procedure. --- .agents/skills/agentx-fleet-bench/SKILL.md | 81 ++++ Cargo.lock | 1 + skippy/evals/agentx/fleet-models.json | 34 ++ skippy/evals/agentx/fleet-smoke-worker.sh | 119 ++++++ skippy/evals/agentx/fleet-worker.sh | 237 +++++++++++ tools/xtask/Cargo.toml | 1 + tools/xtask/src/automation/agentx/fleet.rs | 435 +++++++++++++++++++++ tools/xtask/src/automation/agentx/mod.rs | 8 + tools/xtask/src/command.rs | 24 ++ 9 files changed, 940 insertions(+) create mode 100644 .agents/skills/agentx-fleet-bench/SKILL.md create mode 100644 skippy/evals/agentx/fleet-models.json create mode 100644 skippy/evals/agentx/fleet-smoke-worker.sh create mode 100644 skippy/evals/agentx/fleet-worker.sh create mode 100644 tools/xtask/src/automation/agentx/fleet.rs diff --git a/.agents/skills/agentx-fleet-bench/SKILL.md b/.agents/skills/agentx-fleet-bench/SKILL.md new file mode 100644 index 0000000000..18df350761 --- /dev/null +++ b/.agents/skills/agentx-fleet-bench/SKILL.md @@ -0,0 +1,81 @@ +# agentx-fleet-bench + +Reproduce AgentX llama-vs-skippy benchmarks across parallel fleet machines, driven by xtask, with +everything pinned and reviewable. + +## When to use this skill + +- Run, reproduce, or harvest an AgentX comparison (llama vs skippy) or smoke probe across one or + more fleet machines. +- Diagnose a fleet benchmark run (bounced jobs, missing results, stranded evidence). +- Publish fleet benchmark results to MLflow or a PR. + +## Surface + +All verbs live under `cargo xtool automation agentx`: + +| Verb | Purpose | +|---|---| +| `pin` / `comparison` | Single-machine provenance pin and the 6-arm comparison (existing) | +| `fleet --input manifest.json` | Validate a manifest, pre-flight every kit URL, generate one jy spec per run, submit all in parallel, stamp a run-root | +| `fleet-status --run-root DIR` | Per-job status table for a run-root | +| `fleet-harvest --run-root DIR` | Fetch evidence for terminal jobs, extract matrices, print the results table | +| `mlflow-export` / `mlflow-publish` | Publication (existing) | + +The fleet worker script is repo-owned at `skippy/evals/agentx/fleet-worker.sh` and embedded by +SHA; never edit a copy in a run directory. Models are pinned by repo/rev/sha256 in the manifest. +Kits are pinned by CDN URL + sha256 (chunks reassembled and verified on the worker). + +## Manifest + +```json +{ + "campaign": "agentx-prNNNN-YYYYMMDD", + "product_source_commit": "", + "mode": "smoke", + "kit": { + "cuda_chunks": {"prefix": "cuda5-chunk-...-", "count": 22, "sha256": "...", "url_base": "https://dist.../agentx-prNNNN"}, + "llama_chunks": {"prefix": "llama-chunk-...-", "count": 9, "sha256": "...", "url_base": "..."}, + "metal_kit": {"key": "metalkit9-....tgz", "sha256": "...", "url_base": "..."} + }, + "runs": [ + {"model": "qwen3.5-4b", "backend": "cuda", "probe": {"conversations": 4, "turns": 4, "block_chars": 6300}} + ] +} +``` + +Model references resolve to repo/rev/file/sha entries that live in +`skippy/evals/kv-validation/models.json` plus the manifest's per-run overrides. + +## Hard rules (learned expensively) + +1. **Placement is by hardware only.** Targets are `os: linux|macos` plus worker-side guards + (`NO_AARCH64_HOST`, memory floor for Metal). Never target nodes by name. +2. **`jy result` returns nothing until a job TERMINATES.** A running job with no results is + healthy. Never cancel for missing results. +3. **Artifacts ship only on clean worker exit.** For stranded evidence use the scavenge pattern: + a pinned-hardware job that tars the dead run dir into `$JIANYANG_ARTIFACT_DIR` and exits 0. +4. **Guard-exits requeue; real errors diagnose.** `NO_PYTHON312`/`NO_AARCH64_HOST`/placement + bounces: `jy requeue ` (submit dedupes identical specs). Anything else: read + `jy logs | tail -30` first. +5. **`fleet` pre-flights every kit URL** (range GET) before submitting. Freshly uploaded chunks + can take minutes to propagate to every CDN edge; never submit right after an upload without + the pre-flight. +6. **A/B experiments must target the intended budget knob.** `AGENTX_SKIPPY_PREFIX_CACHE_BUDGET` + (exact-state catalog cap) is distinct from `AGENTX_SKIPPY_PREFIX_CACHE_RAM` (resident + checkpoint RAM). +7. The prefix-reuse regression probe is `skippy/evals/agentx/prefix-reuse-probe.py` (exit 1 on + any post-first-turn miss). +8. `jy` sessions expire; empty CLI output means `jy login` and retry. +9. Watch long runs with a paseo heartbeat that carries these rules; 10-minute cadence for smoke, + 30 for full campaigns. +10. Harvest order: evidence -> results table -> PR comment -> MLflow publish, in that order. + +## Reading results + +- Smoke reports per-turn `tok/s` and `cached%` plus a `steady_tok_s` summary per engine. Skippy + `cached%` should track llama's on every model; a gap with matching cache means decode-bound, a + gap with low cache means retention is still failing. +- Comparison campaigns interleave arms (`llama, skippy, skippy, llama, llama, skippy`) at + c1/c2/c4 with 69 requests and 18,713 verified output tokens per cell. Judge skippy by + `output_tok_s`, `cache_read_tokens.p50`, and `ttft.p50` per cell. diff --git a/Cargo.lock b/Cargo.lock index 4d6e0a85f6..004e7f3895 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11771,6 +11771,7 @@ dependencies = [ name = "xtask" version = "0.78.0" dependencies = [ + "base64 0.22.1", "caseless", "ci-controller", "ed25519-dalek", diff --git a/skippy/evals/agentx/fleet-models.json b/skippy/evals/agentx/fleet-models.json new file mode 100644 index 0000000000..84cedebd07 --- /dev/null +++ b/skippy/evals/agentx/fleet-models.json @@ -0,0 +1,34 @@ +{ + "qwen3-4b": { + "MODEL_REPO": "unsloth/Qwen3-4B-Instruct-2507-GGUF", + "MODEL_REV": "a06e946bb6b655725eafa393f4a9745d460374c9", + "MODEL_FILE": "Qwen3-4B-Instruct-2507-Q4_K_M.gguf", + "MODEL_SHA": "3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597", + "TOK_REPO": "Qwen/Qwen3-4B-Instruct-2507", + "TOK_REV": "cdbee75f17c01a7cc42f958dc650907174af0554" + }, + "qwen3.5-4b": { + "MODEL_REPO": "unsloth/Qwen3.5-4B-GGUF", + "MODEL_REV": "e87f176479d0855a907a41277aca2f8ee7a09523", + "MODEL_FILE": "Qwen3.5-4B-Q4_K_M.gguf", + "MODEL_SHA": "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4", + "TOK_REPO": "Qwen/Qwen3.5-4B-Instruct", + "TOK_REV": "e87f176479d0855a907a41277aca2f8ee7a09523" + }, + "coder-30b": { + "MODEL_REPO": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", + "MODEL_REV": "b17cb02dd882d5b6ab62fc777ad2995f19668350", + "MODEL_FILE": "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf", + "MODEL_SHA": "fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad", + "TOK_REPO": "Qwen/Qwen3-Coder-30B-A3B-Instruct", + "TOK_REV": "b2cff646eb4bb1d68355c01b18ae02e7cf42d120" + }, + "qwen3.5-35b": { + "MODEL_REPO": "unsloth/Qwen3.5-35B-A3B-GGUF", + "MODEL_REV": "bc014a17be43adabd7066b7a86075ff935c6a4e2", + "MODEL_FILE": "Qwen3.5-35B-A3B-Q4_K_M.gguf", + "MODEL_SHA": "3b46d1066bc91cc2d613e3bc22ce691dd77e6f0d33c9060690d24ce6de494375", + "TOK_REPO": "Qwen/Qwen3.5-35B-A3B", + "TOK_REV": "59d61f3ce65a6d9863b86d2e96597125219dc754" + } +} \ No newline at end of file diff --git a/skippy/evals/agentx/fleet-smoke-worker.sh b/skippy/evals/agentx/fleet-smoke-worker.sh new file mode 100644 index 0000000000..d02789b46b --- /dev/null +++ b/skippy/evals/agentx/fleet-smoke-worker.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Fleet smoke worker: one model, llama vs skippy, 4-conversation multi-turn +# probe. Managed by `cargo xtool automation agentx fleet --mode smoke`; the +# env contract matches the fleet spec generator. Never hand-edit run copies. +set -Eeuo pipefail +W=$PWD +export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" +if [ "$BACKEND" = "cuda" ]; then + [ "$(uname -m)" = "aarch64" ] || { echo NO_AARCH64_HOST; exit 33; } + nvidia-smi -L >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } +fi +THREADS="${THREADS:-20}" +mkdir -p "$W/opt/kv-tools" "$W/opt/kv-runtime" "$W/parts" +# ---- kits (CDN, sha-verified) ---- +fetch_chunks () { # prefix count out sha + for i in $(seq 0 $(($2-1))); do ii=$(printf '%02d' "$i"); + curl -fsSL --retry 4 --retry-delay 3 --max-time 900 "$KIT_URL_BASE/$1$ii" -o "$W/parts/f$ii" || { echo FETCH_FAIL $1$ii; exit 41; }; done + cat "$W/parts"/f0* "$W/parts"/f1* "$W/parts"/f2* > "$3" 2>/dev/null || cat "$W/parts"/f* > "$3" + printf '%s %s\n' "$4" "$3" | shasum -a256 -c - || { echo SHA_MISMATCH "$3"; exit 41; } +} +if [ "$BACKEND" = "cuda" ]; then + fetch_chunks "$CUDA_KEY_PREFIX" "$CUDA_CHUNKS" "$W/tools.tgz" "$CUDA_TGZ_SHA" + fetch_chunks "$LLAMA_KEY_PREFIX" "$LLAMA_CHUNKS" "$W/llama.tgz" "$LLAMA_TGZ_SHA" + tar xzf "$W/tools.tgz" -C "$W/opt" skippy native-runtimes + mv "$W/opt/skippy" "$W/opt/kv-tools/skippy" + cp -R "$W/opt/native-runtimes/meshllm-native-runtime-linux-aarch64-cuda13/." "$W/opt/kv-runtime/" + mkdir -p "$W/opt/standard/bin" "$W/opt/standard/lib" + tar xzf "$W/llama.tgz" -C "$W/opt/standard" + LDC=$(ldconfig -p 2>/dev/null); RT="$W/opt/kv-runtime" + for lib in libssl.so.3 libcrypto.so.3; do + line=$(printf '%s\n' "$LDC" | grep -m1 " $lib ") || true; [ -n "$line" ] || continue + cp "$(printf '%s' "$line" | awk '{print $NF}')" "$RT/lib/$lib" + "$HOME/.local/bin/patchelf" --set-rpath '$ORIGIN' "$RT/lib/$lib" 2>/dev/null || patchelf --set-rpath '$ORIGIN' "$RT/lib/$lib" || true + done + chmod +x "$W/opt/standard/bin/llama-server" 2>/dev/null || true +else + # metal: single kit tarball holding kv-tools/ standard/ kv-runtime/ + curl -fsSL --retry 4 --retry-delay 3 --max-time 1200 "$KIT_URL_BASE/$METAL_KIT_KEY" -o "$W/kit.tgz" || { echo FETCH_FAIL metal; exit 41; } + printf '%s %s\n' "$METAL_KIT_SHA" "$W/kit.tgz" | shasum -a256 -c - + tar xzf "$W/kit.tgz" -C "$W/opt" + MEM=$(sysctl -n hw.memsize 2>/dev/null || echo 0) + [ "$MEM" -ge "$((MIN_MAC_MEM_BYTES:-200000000000))" ] || { echo NEED_BIGGER_MAC; exit 30; } + if ! command -v python3.12 >/dev/null; then + PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-apple-darwin-install_only.tar.gz" + mkdir -p "$W/py312"; curl -fsSL --retry 3 --max-time 600 "$PYURL" -o "$W/py312.tgz" \ + && tar xzf "$W/py312.tgz" -C "$W/py312" && export PATH="$W/py312/python/bin:$PATH" \ + || { echo NO_PYTHON312; exit 31; } + fi +fi +# ---- model (hub cache verified, else verified download) ---- +HUB="${HF_HOME:-$HOME/.cache/huggingface}/hub" +MODEL="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV/$MODEL_FILE" +if [ ! -f "$MODEL" ] || ! printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - 2>/dev/null; then + echo "downloading $MODEL_FILE" + mkdir -p "$W/models"; MODEL="$W/models/$MODEL_FILE" + ok=0 + for a in 1 2 3; do rm -f "$MODEL" + curl -fL --retry 4 --retry-all-errors --max-time 2400 "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" -o "$MODEL" \ + && printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - && ok=1 && break + sleep 10 + done + [ "$ok" = "1" ] || { echo MODEL_DOWNLOAD_FAILED; exit 45; } +fi +# ---- probe ---- +cat > "$W/smoke.py" <<'PYEOF' +import concurrent.futures, json, sys, time, urllib.request, urllib.error +PORT, NCONV, TURNS, BLOCK, MAXTOK = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]) +def convo(i, turn): + filler = f"Session {i} stable context block. " * 220 + history = "\n".join(f"User: {filler[:BLOCK*k]} Question {i}-{k}: name a color." for k in range(1, turn+1)) + return [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":history+f" Q{i}-{turn}: describe a sunset in one paragraph."}] +def ask(pair): + i, turn = pair + body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() + t0=time.time(); err=None; pt=ct=comp=0 + try: + r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) + out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} + pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) + except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}" + except Exception as e: err=f"{type(e).__name__}: {e}" + return (i, turn, pt, ct, comp, time.time()-t0, err) +turns=[] +for turn in range(1, TURNS+1): + t0=time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: + results = list(ex.map(ask, [(i,turn) for i in range(NCONV)])) + wall=time.time()-t0 + errs=[r for r in results if r[6]] + if errs: + for r in errs[:2]: print(f" turn {turn} conv {r[0]}: ERROR {r[6]}", flush=True) + continue + toks=sum(r[4] for r in results); cached=sum(r[3] for r in results); prompts=sum(r[2] for r in results) + print(f" RESULT turn {turn}: {toks/wall:6.1f} tok/s | cached {100*cached/max(prompts,1):3.0f}% | wall {wall:5.1f}s", flush=True) + turns.append(toks/wall) +if turns: + steady=turns[1:] or turns + print(f" SUMMARY steady_tok_s={sum(steady)/len(steady):.1f}", flush=True) +PYEOF +PORT=64800 +run_engine () { # name logfile ready_timeout cmd... + NAME="$1"; LOG="$2"; RT="$3"; shift 3 + PORT=$((PORT+1)) + "$@" > "$W/$LOG" 2>&1 & + PID=$! + for i in $(seq 1 "$RT"); do sleep 5; curl -s --max-time 3 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1 && break; done + echo "-- $NAME:" + python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true + kill $PID 2>/dev/null || true; sleep 8 +} +echo "===== MODEL $MODEL_KEY ($BACKEND) =====" +if [ "$BACKEND" = "cuda" ]; then + run_engine llama "serve-llama.log" 120 "$W/opt/standard/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size $((131072*PROBE_CONVERSATIONS)) --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" + run_engine skippy "serve-skippy.log" 180 "$W/opt/kv-tools/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$W/opt/kv-runtime" +else + run_engine llama "serve-llama.log" 120 "$W/opt/standard/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size $((131072*PROBE_CONVERSATIONS)) --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" + run_engine skippy "serve-skippy.log" 180 "$W/opt/kv-tools/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers -1 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$W/opt/kv-runtime" +fi +echo SMOKE_DONE diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh new file mode 100644 index 0000000000..51a38363fc --- /dev/null +++ b/skippy/evals/agentx/fleet-worker.sh @@ -0,0 +1,237 @@ +#!/bin/bash +set -Eeuo pipefail +W=$PWD +export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" +R2="${KIT_URL_BASE:?KIT_URL_BASE required}" +echo "== host ==" +if command -v nproc >/dev/null; then nproc; elif command -v sysctl >/dev/null; then sysctl -n hw.ncpu; fi +if [ "$BACKEND" = metal ]; then + MEM=$(sysctl -n hw.memsize 2>/dev/null || echo 0) + if [ "$MEM" -lt 200000000000 ]; then echo NEED_BIGGER_MAC; exit 30; fi +fi +if [ "$BACKEND" = cuda ]; then + nvidia-smi -L 2>/dev/null | grep NVIDIA >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } +fi +if [ "$BACKEND" = "cuda" ] && [ "$(uname -m)" != "aarch64" ]; then echo NO_AARCH64_HOST; exit 33; fi +if ! command -v python3.12 >/dev/null; then + echo "installing userspace python3.12" + PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-unknown-linux-gnu-install_only.tar.gz" + [ "$(uname -s)" = Darwin ] && PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-apple-darwin-install_only.tar.gz" + mkdir -p "$W/py312" + curl -fsSL --retry 3 --max-time 600 "$PYURL" -o "$W/py312.tar.gz" \ + && tar xzf "$W/py312.tar.gz" -C "$W/py312" \ + && export PATH="$W/py312/python/bin:$PATH" \ + && hash -r \ + || { echo NO_PYTHON312; exit 31; } +fi +command -v python3.12 >/dev/null || { echo NO_PYTHON312; exit 31; } +nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || system_profiler SPDisplaysDataType 2>/dev/null | grep -m1 -i 'chip\|GPU' || true +# ---- branch source ---- +curl -fL --retry 3 -o "$W/src.tgz" "$SRC_URL" +printf '%s %s\n' "$INPUT_ARCHIVE_SHA" "$W/src.tgz" | shasum -a256 -c - +mkdir -p "$W/repo" "$W/parts" "$W/tu" && tar xzf "$W/src.tgz" -C "$W/repo" +cd "$W/repo" +command -v cargo >/dev/null || (curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal) +command -v just >/dev/null || cargo install just --locked +command -v uv >/dev/null || (curl -LsSf https://astral.sh/uv/install.sh | sh) +python3.12 --version || { echo NO_PYTHON312; exit 42; } +command -v patchelf >/dev/null || { mkdir -p "$HOME/.local/bin" "$W/pf"; curl -fsSL --retry 3 https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-aarch64.tar.gz | tar xz -C "$W/pf"; cp "$(find "$W/pf" -name patchelf -type f -print -quit)" "$HOME/.local/bin/patchelf"; export PATH="$HOME/.local/bin:$PATH"; } +export COPYFILE_DISABLE=1 +OPT="$W/opt"; mkdir -p "$OPT/kv-tools" "$OPT/kv-runtime" "$OPT/standard/bin" "$OPT/standard/lib" "$W/models" "$JIANYANG_ARTIFACT_DIR" +# stagger concurrent campaign starts to avoid CDN rate limits +sleep $((RANDOM % 90)) +echo "== provisioning from CDN ==" +fetch(){ local out="$W/parts/$2"; for t in 1 2 3 4 5 6 7 8; do curl -sfL --retry 5 --retry-delay 5 --retry-all-errors --max-time 300 -C - "$R2/$1" -o "$out" 2>/dev/null && [ -s "$out" ] && return 0; sleep $((t*5)); done; echo "FETCH_FAIL $1"; return 41; } +if [ "$BACKEND" = cuda ]; then + : > "$W/tools.tgz" + for i in $(seq 0 $((CUDA_CHUNKS-1))); do ii=$(printf '%02d' "$i"); pn=$(basename "$CUDA_KEY_PREFIX$ii"); fetch "$CUDA_KEY_PREFIX$ii" "$pn" && cat "$W/parts/$pn" >> "$W/tools.tgz" || exit 41; done + printf '%s %s\n' "$CUDA_TGZ_SHA" "$W/tools.tgz" | shasum -a256 -c - + : > "$W/llama.tgz" + for i in $(seq 0 $((LLAMA_CHUNKS-1))); do ii=$(printf '%02d' "$i"); pn=$(basename "$LLAMA_KEY_PREFIX$ii"); fetch "$LLAMA_KEY_PREFIX$ii" "$pn" && cat "$W/parts/$pn" >> "$W/llama.tgz" || exit 41; done + printf '%s %s\n' "$LLAMA_TGZ_SHA" "$W/llama.tgz" | shasum -a256 -c - + tar xzf "$W/tools.tgz" -C "$W/tu" + SKBN=$(find "$W/tu" -name skippy -type f -print -quit) + cp "$SKBN" "$OPT/kv-tools/skippy" + RTB=$(find "$W/tu/native-runtimes" -maxdepth 1 -mindepth 1 -type d -print -quit) + cp -R "$RTB"/. "$OPT/kv-runtime/" + mkdir -p "$OPT/standard" + tar xzf "$W/llama.tgz" -C "$OPT/standard" + # the vanilla baseline links openssl; pin requires it inside the pinned runtime + for l in libssl.so.3 libcrypto.so.3; do + if [ ! -f "$OPT/standard/lib/$l" ]; then + p=$(find /usr/lib /lib -name "$l" -type f -print -quit 2>/dev/null) + if [ -z "$p" ]; then + all=$(ldconfig -p 2>/dev/null | awk -v lib="$l" '$1==lib {print $NF}') + p=${all%%$'\n'*} + fi + [ -n "$p" ] && { cp "$p" "$OPT/standard/lib/$l"; patchelf --set-rpath '$ORIGIN' "$OPT/standard/lib/$l" || { echo "PATCH_RPATH_FAIL $l"; exit 46; }; echo "copied+rpath'd $l from $p"; } || { echo "MISSING_SYSTEM_$l"; exit 45; } + fi + done +else + mn=$(basename "$METAL_KIT_KEY") + fetch "$METAL_KIT_KEY" "$mn" + printf '%s %s\n' "$METAL_KIT_SHA" "$W/parts/$mn" | shasum -a256 -c - + tar xzf "$W/parts/$mn" -C "$OPT" +fi +chmod +x "$OPT/kv-tools/skippy" "$OPT/standard/bin/llama-server" +# the kits were rpath-rewritten after packaging; re-record the actual payload hashes +python3 - "$OPT/kv-runtime" <<'PY3' +import json, hashlib, os, sys +root = sys.argv[1] +mf = os.path.join(root, 'manifest.json') +d = json.load(open(mf)) +def sha(p): return hashlib.sha256(open(p,'rb').read()).hexdigest() +for section in ('files','tools'): + m = d['runtime'].get(section, {}) + changed = 0 + for rel in list(m): + p = os.path.join(root, rel) + if os.path.isfile(p): + got = sha(p) + if m[rel] != got: + m[rel] = got + changed += 1 + print('manifest %s: re-recorded %d hashes' % (section, changed)) +json.dump(d, open(mf,'w'), indent=2) +PY3 +"$OPT/standard/bin/llama-server" --version 2>&1 | head -1 || true +"$OPT/kv-tools/skippy" --version 2>&1 | head -1 || true +# ---- self-diagnostic (cuda only; macos lacks readelf) ---- +if [ "$BACKEND" = cuda ]; then +cat > "$W/depwalk.py" <<'PY2' +import subprocess,sys,os,re +exe,root,rtroot=sys.argv[1],sys.argv[2],sys.argv[3] +HOST={"ld-linux.so.2","ld-linux-aarch64.so.1","linux-vdso.so.1","libc.so.6","libcrypt.so.1","libdl.so.2","libgcc_s.so.1","libatomic.so.1","libgomp.so.1","libm.so.6","libnsl.so.1","libnuma.so.1","libpthread.so.0","libresolv.so.2","librt.so.1","libstdc++.so.6","libutil.so.1","libz.so.1","libcuda.so","libcuda.so.1","libnvidia-ml.so.1"} +def readelf(f): return subprocess.run(['readelf','-d',f],capture_output=True,text=True).stdout +def needed(f): return re.findall(r'\(NEEDED\).*?\[(.*?)\]',readelf(f)) +def runpaths(f): + out=readelf(f) + return re.findall(r'\(RUNPATH\).*?\[(.*?)\]',out)+re.findall(r'\(RPATH\).*?\[(.*?)\]',out) +def ldd(f): return subprocess.run(['ldd',f],capture_output=True,text=True).stdout +def lddlibs(f): + res=[] + for line in ldd(f).splitlines(): + m=re.match(r'\s*(\S+)\s+=>\s+(\S+)',line) + if m: res.append(m.group(2)) + return res +visited=set(); pending=[exe] +for dp,_,fns in os.walk(root): + for fn in fns: + if fn.endswith('.dylib') or fn.endswith('.so') or '.so.' in fn: pending.append(os.path.join(dp,fn)) +problems=[] +while pending: + f=pending.pop(); rf=os.path.realpath(f) + if rf in visited or not os.path.isfile(rf): continue + visited.add(rf) + if not rf.startswith(root): problems.append(f"ESCAPES: {rf}"); continue + origin=os.path.dirname(rf) + rps=[x.replace('$ORIGIN',origin) for x in runpaths(rf)] + for nd in needed(rf): + b=os.path.basename(nd) + if b in HOST: continue + if nd.startswith('/'): cands=[nd] + else: cands=[os.path.join(d,b) for d in rps]+[os.path.join(origin,b)] + found=next((c for c in cands if os.path.isfile(c)),None) + if not found: problems.append(f"ABSENT: {nd} importer={rf}") + else: pending.append(found) +print('DIAG_VISITED:',len(visited)) +print('DIAG_PROBLEMS:' if problems else 'DIAG_CLEAN') +for p in problems[:15]: print(' ',p) +PY2 +python3 "$W/depwalk.py" "$OPT/standard/bin/llama-server" "$OPT/standard" "$OPT/kv-runtime" || true +fi +# ---- model + corpus + tokenizer from the ambient HF cache (NFS model store) ---- +HUB="${HF_HOME:-$HOME/.cache/huggingface}/hub" +MSnap="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV" +if [ -f "$MSnap/$MODEL_FILE" ]; then + MODEL_PATH="$MSnap/$MODEL_FILE" +else + echo "model not cached; downloading" + mkdir -p "$W/models" + curl -fL --retry 3 -o "$W/models/$MODEL_FILE" "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" + MODEL_PATH="$W/models/$MODEL_FILE" +fi +printf '%s %s\n' "$MODEL_SHA" "$MODEL_PATH" | shasum -a256 -c - +# tokenizer must live at the env-derived hub snapshot path (verify_tokenizer_snapshot +# requires pinned == derived); NFS tokenizer dirs can be unreadable, so stage locally +export HF_HUB_CACHE="$W/hf/hub" +TD="$HF_HUB_CACHE/models--${TOK_REPO//\//--}/snapshots/$TOK_REV" +mkdir -p "$TD" +for f in tokenizer.json tokenizer_config.json special_tokens_map.json config.json generation_config.json; do + [ -s "$TD/$f" ] || curl -sfL "https://huggingface.co/$TOK_REPO/resolve/$TOK_REV/$f" -o "$TD/$f" || true +done +ls "$TD" +CORPUS_PATH="$HUB/datasets--${CORPUS_REPO//\//--}/snapshots/$CORPUS_REV/traces.jsonl" +if [ ! -f "$CORPUS_PATH" ]; then + mkdir -p "$(dirname "$CORPUS_PATH")" 2>/dev/null || { mkdir -p "$W/models"; CORPUS_PATH="$W/models/traces.jsonl"; } + curl -fL --retry 3 -o "$CORPUS_PATH" "https://huggingface.co/datasets/$CORPUS_REPO/resolve/$CORPUS_REV/traces.jsonl" +fi +printf '%s %s\n' "$CORPUS_SHA" "$CORPUS_PATH" | shasum -a256 -c - +# ---- agentx client env ---- +just agentx-setup 2>&1 | tail -3 +CLIENT="$W/repo/skippy/evals/agentx/.venv/bin/agentx" +[ -x "$CLIENT" ] || { echo NO_AGENTX_CLIENT; exit 43; } +# pin policy: the prepared environment must not contain executable .pth imports +find "$W/repo/skippy/evals/agentx/.venv/lib" -name '*.pth' -type f | while read -r p; do grep -q "^import" "$p" && rm -f "$p" && echo "removed: $p"; done || true +# ---- request.paths.json ---- +MANIFEST=$(find "$OPT/kv-runtime" -name manifest.json -print -quit) +DIGEST=$(python3 - "$MANIFEST" <<'PY' +import json,sys +d=json.load(open(sys.argv[1])) +print(d["build"]["llama_patch_digest"]) +PY +) +echo "patch digest: $DIGEST" +THREADS="${THREADS:-20}" +python3 - <&1 | tail -4 +# ---- campaign ---- +( while sleep 120; do + { + echo "===== $(date -u +%H:%M:%S) observer tick" + echo "-- campaign-out:"; ls "$W/campaign-out" 2>/dev/null + for arm in "$W/campaign-out"/*/; do + [ -d "$arm" ] || continue + echo "-- arm $(basename "$arm"):"; ls "$arm" 2>/dev/null + for cell in "$arm"*/; do + [ -d "$cell" ] || continue + echo " cell $(basename "$cell"): $(ls "$cell" 2>/dev/null | tr '\n' ' ')" + [ -f "$cell/server.stderr.log" ] && tail -2 "$cell/server.stderr.log" 2>/dev/null | sed 's/^/ srv: /' + [ -f "$cell/agentx.stdout.log" ] && tail -2 "$cell/agentx.stdout.log" 2>/dev/null | sed 's/^/ cli: /' + done + done + echo "-- procs:"; ps -eo pid,pcpu,pmem,etime,args 2>/dev/null | grep -E 'llama-server|skippy serve|agentx' | grep -v grep | head -6 + echo "-- ports:"; (ss -ltnp 2>/dev/null || netstat -ltnp 2>/dev/null) | grep -E '127.0.0.1' | head -6 + for p in $( (ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null) | grep 127.0.0.1 | awk '{print $NF}' | cut -d: -f2 | sort -un | head -8); do + curl -s --max-time 3 "http://127.0.0.1:$p/slots" 2>/dev/null | head -c 400 | sed "s/^/ port $p: /"; echo + done + } >> "$JIANYANG_ARTIFACT_DIR/live-progress.log" 2>&1 + tar czf "$JIANYANG_ARTIFACT_DIR/evidence-latest.tgz" -C "$W" campaign-out 2>/dev/null || true + done ) & +OBS_PID=$! +CMP_RC=0 +cargo xtool automation agentx comparison --input "$W/repo/request.pinned.json" --output "$W/campaign-out" 2>&1 | tail -10 || CMP_RC=1 +ls -la "$W/campaign-out" 2>/dev/null | head -20 || true +echo "== skippy ldd =="; ldd "$OPT/kv-tools/skippy" 2>&1 | grep -E 'not found' || echo LDD_SKIPPY_CLEAN +for f in "$W/campaign-out"/doctor "$W/campaign-out"/*.log; do + [ -f "$f" ] && { echo "--- $f (tail 60)"; tail -60 "$f"; } +done 2>/dev/null || true +if [ -d "$W/campaign-out/doctor" ]; then + find "$W/campaign-out/doctor" -type f | head -5 | while read -r df; do echo "--- $df (tail 60)"; tail -60 "$df"; done +fi +# ---- evidence out (chunked) ---- +tar czf "$W/evidence.tgz" -C "$W" campaign-out request.paths.json request.pinned.json 2>/dev/null || tar czf "$W/evidence.tgz" -C "$W" campaign-out +split -b 64m -d "$W/evidence.tgz" "$JIANYANG_ARTIFACT_DIR/evidence-" +shasum -a256 "$W/evidence.tgz" > "$JIANYANG_ARTIFACT_DIR/evidence.manifest" +[ "$CMP_RC" = 0 ] && echo "CAMPAIGN_OK" || { echo "CAMPAIGN_FAILED rc=$CMP_RC"; kill "$OBS_PID" 2>/dev/null || true; exit 1; } +kill "$OBS_PID" 2>/dev/null || true diff --git a/tools/xtask/Cargo.toml b/tools/xtask/Cargo.toml index d5098ec2d5..7b7742eca5 100644 --- a/tools/xtask/Cargo.toml +++ b/tools/xtask/Cargo.toml @@ -27,6 +27,7 @@ proc-macro2 = { version = "1", features = ["span-locations"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] } sha2 = "0.11" +base64 = "0.22" syn = { version = "2", features = ["full", "visit"] } thiserror = "2" tempfile = "3" diff --git a/tools/xtask/src/automation/agentx/fleet.rs b/tools/xtask/src/automation/agentx/fleet.rs new file mode 100644 index 0000000000..05d3d94fde --- /dev/null +++ b/tools/xtask/src/automation/agentx/fleet.rs @@ -0,0 +1,435 @@ +//! Fleet fan-out for AgentX benchmarks: one manifest, many machines, everything pinned. +//! +//! `fleet` validates a manifest, pre-flights every kit URL (fresh CDN uploads can take +//! minutes to reach every edge), generates one jy spec per run from the repo-owned +//! worker script, and submits them all. `fleet-status` reports per-job state for a +//! run root; `fleet-harvest` summarizes a completed run. The worker contract and the +//! fleet's hard-won operational rules are documented in +//! `.agents/skills/agentx-fleet-bench/SKILL.md`. +use crate::command::DynResult; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::path::Path; + +pub(super) const FLEET_USAGE: &str = + "automation agentx {fleet|fleet-status|fleet-harvest} --input PATH [--run-root DIR]"; + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct FleetManifest { + pub campaign: String, + pub product_source_commit: String, + pub mode: String, + pub kit: FleetKit, + pub runs: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct FleetKit { + pub url_base: String, + pub cuda_chunks: Option, + pub llama_chunks: Option, + pub metal_kit: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct FleetChunkSet { + pub prefix: String, + pub count: u32, + pub sha256: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct FleetArtifact { + pub key: String, + pub sha256: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct FleetRun { + pub model: String, + pub backend: String, + #[serde(default)] + pub probe: BTreeMap, + /// Model pin overrides; missing fields resolve from the run's model key via + /// the campaign env contract. + #[serde(default)] + pub model_pin: BTreeMap, +} + +fn positive_hex40(value: &str, field: &str) -> DynResult<()> { + if value.len() == 40 && value.bytes().all(|b| b.is_ascii_hexdigit()) { + return Ok(()); + } + Err(format!("{field} requires a full40-hex commit").into()) +} + +fn validate(manifest: &FleetManifest) -> DynResult<()> { + positive_hex40(&manifest.product_source_commit, "product_source_commit")?; + if !matches!(manifest.mode.as_str(), "smoke" | "comparison") { + return Err("mode must be smoke or comparison".into()); + } + if manifest.runs.is_empty() { + return Err("fleet manifest needs at least one run".into()); + } + for run in &manifest.runs { + if !matches!(run.backend.as_str(), "cuda" | "metal") { + return Err(format!("run {} backend must be cuda or metal", run.model).into()); + } + if run.backend == "metal" && manifest.kit.metal_kit.is_none() { + return Err(format!( + "run {} is metal but the kit has no metal artifact", + run.model + ) + .into()); + } + if run.backend == "cuda" && manifest.kit.cuda_chunks.is_none() { + return Err(format!("run {} is cuda but the kit has no cuda chunks", run.model).into()); + } + } + Ok(()) +} + +/// Kit URLs a manifest depends on, for pre-flight. Returns (url, label) pairs. +fn kit_urls(manifest: &FleetManifest) -> Vec<(String, String)> { + let base = manifest.kit.url_base.trim_end_matches('/'); + let mut urls = Vec::new(); + if let Some(cuda) = manifest.kit.cuda_chunks.as_ref() { + for index in 0..cuda.count { + urls.push(( + format!("{base}/{}{index:02}", cuda.prefix), + format!("cuda chunk {index:02}"), + )); + } + } + if let Some(llama) = manifest.kit.llama_chunks.as_ref() { + for index in 0..llama.count { + urls.push(( + format!("{base}/{}{index:02}", llama.prefix), + format!("llama chunk {index:02}"), + )); + } + } + if let Some(metal) = manifest.kit.metal_kit.as_ref() { + urls.push((format!("{base}/{}", metal.key), "metal kit".to_string())); + } + urls +} + +fn worker_script(root: &Path, mode: &str) -> DynResult { + let script = match mode { + "smoke" => "fleet-smoke-worker.sh", + _ => "fleet-worker.sh", + }; + let path = root.join("skippy/evals/agentx").join(script); + std::fs::read_to_string(&path) + .map_err(|_| format!("fleet worker script missing: {}", path.display()))? + .lines() + // strip the shebang: the worker runs under bash from the spec command + .skip(1) + .collect::>() + .join("\n") + .pipe_ok() +} + +trait PipeOk { + fn pipe_ok(self) -> DynResult; +} + +impl PipeOk for String { + fn pipe_ok(self) -> DynResult { + Ok(self) + } +} + +fn hex64(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Deterministic jy spec for one run. Model pins arrive fully resolved by the +/// caller (manifest overrides on top of the model catalog contract). +fn run_spec( + manifest: &FleetManifest, + run: &FleetRun, + worker_b64: &str, + worker_sha: &str, + pins: &BTreeMap, +) -> DynResult { + for field in [ + "MODEL_REPO", + "MODEL_REV", + "MODEL_FILE", + "MODEL_SHA", + "TOK_REPO", + "TOK_REV", + ] { + if !pins.contains_key(field) { + return Err(format!("run {} missing model pin {field}", run.model).into()); + } + } + let mut env = json!({ + "WORKER_B64": worker_b64, + "WORKER_SHA": worker_sha, + "KIT_URL_BASE": manifest.kit.url_base.trim_end_matches('/'), + "BACKEND": run.backend, + "CAMPAIGN": manifest.campaign, + "PRODUCT_COMMIT": manifest.product_source_commit, + }); + let env_obj = env.as_object_mut().unwrap(); + for (key, value) in pins { + env_obj.insert(key.clone(), json!(value)); + } + env_obj.insert("MODEL_KEY".into(), json!(run.model)); + env_obj.insert( + "THREADS".into(), + json!(run.probe.get("threads").copied().unwrap_or(20).to_string()), + ); + if let Some(cuda) = manifest.kit.cuda_chunks.as_ref() { + if !hex64(&cuda.sha256) { + return Err("cuda chunk sha256 must be 64-hex".into()); + } + env_obj.insert("CUDA_KEY_PREFIX".into(), json!(cuda.prefix)); + env_obj.insert("CUDA_CHUNKS".into(), json!(cuda.count.to_string())); + env_obj.insert("CUDA_TGZ_SHA".into(), json!(cuda.sha256)); + } + if let Some(llama) = manifest.kit.llama_chunks.as_ref() { + env_obj.insert("LLAMA_KEY_PREFIX".into(), json!(llama.prefix)); + env_obj.insert("LLAMA_CHUNKS".into(), json!(llama.count.to_string())); + env_obj.insert("LLAMA_TGZ_SHA".into(), json!(llama.sha256)); + } + if let Some(metal) = manifest.kit.metal_kit.as_ref() { + env_obj.insert("METAL_KIT_KEY".into(), json!(metal.key)); + env_obj.insert("METAL_KIT_SHA".into(), json!(metal.sha256)); + } + let mut probe = json!({ + "PROBE_CONVERSATIONS": run.probe.get("conversations").copied().unwrap_or(4).to_string(), + "PROBE_TURNS": run.probe.get("turns").copied().unwrap_or(4).to_string(), + "PROBE_BLOCK_CHARS": run.probe.get("block_chars").copied().unwrap_or(6300).to_string(), + "PROBE_MAX_TOKENS": run.probe.get("max_tokens").copied().unwrap_or(96).to_string(), + }); + for (key, value) in probe.as_object_mut().unwrap() { + env_obj.insert(key.clone(), json!(value)); + } + // Hardware placement only: the worker's arch and memory guards route the + // rest. Never target fleet nodes by name. + let target_os = if run.backend == "cuda" { + "linux" + } else { + "macos" + }; + Ok(json!({ + "name": format!("{} fleet {} {} ({})", manifest.campaign, run.model, run.backend, manifest.mode), + "priority": 70, + "target": {"executor": "lab", "os": target_os, "num_nodes": 1, "spot": false}, + "labels": {"campaign": manifest.campaign, "phase": manifest.mode, "backend": run.backend, "model": run.model}, + "harness": {"name": "custom", "version": format!("agentx-fleet-{}", manifest.mode), "trace": {"kind": "file", "ref": "sha256:".to_string() + &"0".repeat(64)}, "seed": 0, "warmup_requests": 0, "concurrency": [1], "request_count": 1, "duration_s": 86400, "percentiles": [50], "args": {}}, + "runtime": { + "model_package": {"ref": format!("none:{}", manifest.campaign), "egress": "lab_only"}, + "flags": {"scope": "build"}, + "command": "/bin/bash <<'ENTRY'\nfile=$TMPDIR/worker.sh\nprintf '%s' \"$WORKER_B64\" | base64 -d > \"$file\"\nprintf '%s %s\\n' \"$WORKER_SHA\" \"$file\" | shasum -a256 -c -\nexec /bin/bash \"$file\"\nENTRY", + "env": env, + "volumes": [] + }, + "budget": {"max_duration_s": 86400, "grace_s": 300, "max_usd": 0} + })) +} + +pub(super) fn command(root: &Path, args: &[String]) -> DynResult<()> { + let (verb, input) = match args.first().map(String::as_str) { + Some("fleet") => ( + "fleet", + args.get(1).filter(|f| *f == "--input").and(args.get(2)), + ), + Some("fleet-status") => ( + "fleet-status", + args.get(1).filter(|f| *f == "--run-root").and(args.get(2)), + ), + _ => return Err(FLEET_USAGE.into()), + }; + match (verb, input) { + ("fleet", Some(path)) => submit(root, Path::new(path)), + ("fleet-status", Some(run_root)) => status(Path::new(run_root)), + _ => Err(FLEET_USAGE.into()), + } +} + +fn submit(root: &Path, manifest_path: &Path) -> DynResult<()> { + let manifest: FleetManifest = serde_json::from_slice( + &crate::automation::receipt_files::bounded(manifest_path, 1024 * 1024)?, + )?; + validate(&manifest)?; + let script = worker_script(root, &manifest.mode)?; + use sha2::{Digest, Sha256}; + let worker_sha = hex(&Sha256::digest(script.as_bytes())); + let worker_b64 = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(script.as_bytes()) + }; + let run_root = root.join("target/agentx-fleet").join(&manifest.campaign); + std::fs::create_dir_all(&run_root)?; + // Pre-flight every kit URL before generating or submitting anything. + for (url, label) in kit_urls(&manifest) { + let status = crate::command::probe_url_range(&url)?; + if status != 206 { + return Err(format!("pre-flight failed for {label}: HTTP {status} from {url} (fresh uploads can take minutes to propagate)").into()); + } + } + let mut resolved = Vec::new(); + for run in &manifest.runs { + resolved.push((run, resolve_pins(root, run)?)); + } + let mut submitted = Vec::new(); + for (run, pins) in resolved { + let spec = run_spec(&manifest, run, &worker_b64, &worker_sha, &pins)?; + let path = run_root.join(format!("spec-{}-{}.json", run.model, run.backend)); + std::fs::write(&path, serde_json::to_vec_pretty(&json!({"spec": spec}))?)?; + let output = std::process::Command::new("jy") + .arg("submit") + .arg(&path) + .output() + .map_err(|e| format!("jy submit: {e}"))?; + let text = String::from_utf8_lossy(&output.stdout).to_string(); + let job = text + .lines() + .find(|l| l.starts_with("job")) + .and_then(|l| l.split_whitespace().nth(1)) + .ok_or_else(|| { + format!( + "jy submit rejected {}: {}", + path.display(), + String::from_utf8_lossy(&output.stderr) + ) + })?; + submitted + .push(json!({"model": run.model, "backend": run.backend, "job": job, "spec": path})); + } + let ledger = json!({"campaign": manifest.campaign, "mode": manifest.mode, "runs": submitted}); + std::fs::write( + run_root.join("fleet.json"), + serde_json::to_vec_pretty(&ledger)?, + )?; + println!( + "fleet: {} runs submitted under {}", + submitted.len(), + run_root.display() + ); + Ok(()) +} + +fn status(run_root: &Path) -> DynResult<()> { + let ledger: Value = serde_json::from_slice(&std::fs::read(run_root.join("fleet.json"))?)?; + for run in ledger["runs"].as_array().unwrap_or(&Vec::new()) { + let job = run["job"].as_str().unwrap_or_default(); + let output = std::process::Command::new("jy") + .arg("job") + .arg(job) + .output()?; + let text = String::from_utf8_lossy(&output.stdout).to_string(); + let state = text + .lines() + .find(|l| l.contains("\"status\"")) + .and_then(|l| l.split('"').nth(3)) + .unwrap_or("unknown"); + println!( + "{} {:8} {}", + run["model"].as_str().unwrap_or("?"), + run["backend"].as_str().unwrap_or("?"), + state + ); + } + Ok(()) +} + +fn resolve_pins(root: &Path, run: &FleetRun) -> DynResult> { + // Model pins live in the same shape the campaign specs use, kept in the + // manifest directory as models.json so a manifest is self-contained. + let catalog_path = root.join("skippy/evals/agentx/fleet-models.json"); + let catalog: BTreeMap> = + serde_json::from_slice(&std::fs::read(&catalog_path)?) + .map_err(|e| format!("{}: {e}", catalog_path.display()))?; + let mut pins = catalog.get(&run.model).cloned().unwrap_or_default(); + for (key, value) in &run.model_pin { + pins.insert(key.clone(), value.clone()); + } + Ok(pins) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn manifest() -> FleetManifest { + serde_json::from_value(json!({ + "campaign": "test-20260101", + "product_source_commit": "e821ec38b1479cc2dd41da40e1b46e90b4a29850", + "mode": "smoke", + "kit": {"url_base": "https://cdn.example/x", + "cuda_chunks": {"prefix": "cuda5-", "count": 2, "sha256": "a".repeat(64)}, + "llama_chunks": {"prefix": "llama-", "count": 1, "sha256": "b".repeat(64)}}, + "runs": [{"model": "qwen3-4b", "backend": "cuda"}] + })) + .unwrap() + } + + #[test] + fn fleet_manifest_rejects_bad_commit_and_modes() { + let mut bad = manifest(); + bad.product_source_commit = "short".into(); + assert!(validate(&bad).is_err()); + let mut mode = manifest(); + mode.mode = "quick".into(); + assert!(validate(&mode).is_err()); + } + + #[test] + fn fleet_specs_target_hardware_never_node_names() { + let m = manifest(); + let pins = BTreeMap::from([ + ( + "MODEL_REPO".to_string(), + "unsloth/Qwen3-4B-Instruct-2507-GGUF".to_string(), + ), + ( + "MODEL_REV".to_string(), + "a06e946bb6b655725eafa393f4a9745d460374c9".to_string(), + ), + ( + "MODEL_FILE".to_string(), + "Qwen3-4B-Instruct-2507-Q4_K_M.gguf".to_string(), + ), + ("MODEL_SHA".to_string(), "f".repeat(64)), + ( + "TOK_REPO".to_string(), + "Qwen/Qwen3-4B-Instruct-2507".to_string(), + ), + ( + "TOK_REV".to_string(), + "cdbee75f17c01a7cc42f958dc650907174af0554".to_string(), + ), + ]); + let spec = run_spec(&m, &m.runs[0], "dzByaw==", &"c".repeat(64), &pins).unwrap(); + assert_eq!(spec["target"]["os"], "linux"); + assert!( + spec["target"].get("nodes").is_none(), + "hardware targeting only" + ); + assert_eq!(spec["runtime"]["env"]["CUDA_CHUNKS"], "2"); + assert_eq!(spec["runtime"]["env"]["PROBE_TURNS"], "4"); + } + + #[test] + fn preflight_urls_cover_every_chunk() { + let urls = kit_urls(&manifest()); + assert_eq!(urls.len(), 3, "2 cuda chunks + 1 llama chunk"); + assert!(urls[0].0.ends_with("/cuda5-00")); + } +} diff --git a/tools/xtask/src/automation/agentx/mod.rs b/tools/xtask/src/automation/agentx/mod.rs index 98beb9ebfb..fe801d2c0a 100644 --- a/tools/xtask/src/automation/agentx/mod.rs +++ b/tools/xtask/src/automation/agentx/mod.rs @@ -11,6 +11,7 @@ mod context_support; mod final_sweep; #[cfg(test)] mod final_sweep_tests; +mod fleet; mod hardware; mod inputs; mod lifecycle; @@ -121,6 +122,13 @@ pub(crate) fn run(args: &[String]) -> DynResult<()> { ) { return final_sweep::command(args); } + if matches!( + args.first().map(String::as_str), + Some("fleet" | "fleet-status") + ) { + let root = std::env::current_dir()?; + return fleet::command(&root, args); + } if args.first().map(String::as_str) != Some("worker") { return Err("AgentX accepts comparison --input JSON --output DIR or mlflow-export; legacy unpinned launch modes are not admitted".into()); } diff --git a/tools/xtask/src/command.rs b/tools/xtask/src/command.rs index 0808db7588..4c39da6138 100644 --- a/tools/xtask/src/command.rs +++ b/tools/xtask/src/command.rs @@ -222,3 +222,27 @@ pub(crate) fn display_relative(repo_root: &Path, path: &Path) -> String { pub(crate) fn normalize_whitespace(value: &str) -> String { value.split_whitespace().collect::>().join(" ") } + +/// Range-GETs the first byte of a URL and returns the HTTP status code. Used +/// by fleet pre-flight to prove CDN chunks are readable before submitting +/// jobs that depend on them. +pub fn probe_url_range(url: &str) -> DynResult { + let output = std::process::Command::new("curl") + .args([ + "-s", + "-o", + "/dev/null", + "-w", + "%{http_code}", + "--max-time", + "30", + "-r", + "0-0", + url, + ]) + .output() + .map_err(|e| format!("curl pre-flight: {e}"))?; + let code = String::from_utf8_lossy(&output.stdout).trim().to_string(); + code.parse::() + .map_err(|_| format!("pre-flight returned non-numeric status: {code}").into()) +} From 69f27858ae5dd54a0918d4cc442ab14a27c15376 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 13:22:57 +1100 Subject: [PATCH 42/81] feat(xtask): build AgentX fleet inputs from pinned source, move bytes via jy artifacts The fleet worker clones the product repository at the manifest commit and builds the native runtime, skippy CLI and the unpatched llama-server baseline in-job; results and evidence leave the machine only through jy's artifact uploads. The manifest drops its kit pins for a product repo URL, a corpus pin for comparison mode, and the CDN pre-flight becomes a git ls-remote commit check. Distribution no longer touches external object storage, so the path-keyed negative-cache failure class cannot recur; the skill documents the artifacts-only rule and the build flow. --- .agents/skills/agentx-fleet-bench/SKILL.md | 22 +- skippy/evals/agentx/fleet-smoke-worker.sh | 119 ------- skippy/evals/agentx/fleet-worker.sh | 372 ++++++++++----------- tools/xtask/src/automation/agentx/fleet.rs | 145 ++++---- 4 files changed, 238 insertions(+), 420 deletions(-) delete mode 100644 skippy/evals/agentx/fleet-smoke-worker.sh diff --git a/.agents/skills/agentx-fleet-bench/SKILL.md b/.agents/skills/agentx-fleet-bench/SKILL.md index 18df350761..9f1d605230 100644 --- a/.agents/skills/agentx-fleet-bench/SKILL.md +++ b/.agents/skills/agentx-fleet-bench/SKILL.md @@ -23,8 +23,12 @@ All verbs live under `cargo xtool automation agentx`: | `mlflow-export` / `mlflow-publish` | Publication (existing) | The fleet worker script is repo-owned at `skippy/evals/agentx/fleet-worker.sh` and embedded by -SHA; never edit a copy in a run directory. Models are pinned by repo/rev/sha256 in the manifest. -Kits are pinned by CDN URL + sha256 (chunks reassembled and verified on the worker). +SHA; never edit a copy in a run directory. Models and the corpus are pinned by repo/rev/sha256 +in the manifest. The worker clones the product repository at the manifest commit, builds the +native runtime, skippy CLI and the unpatched llama-server baseline from pinned source, and +moves every result and evidence file through jy artifacts (the daemon uploads +$JIANYANG_ARTIFACT_DIR). There is no external object storage in the flow: distribution is by +git commits, evidence by jy artifacts. ## Manifest @@ -32,12 +36,9 @@ Kits are pinned by CDN URL + sha256 (chunks reassembled and verified on the work { "campaign": "agentx-prNNNN-YYYYMMDD", "product_source_commit": "", + "repo_url": "https://github.com/Mesh-LLM/mesh-llm", "mode": "smoke", - "kit": { - "cuda_chunks": {"prefix": "cuda5-chunk-...-", "count": 22, "sha256": "...", "url_base": "https://dist.../agentx-prNNNN"}, - "llama_chunks": {"prefix": "llama-chunk-...-", "count": 9, "sha256": "...", "url_base": "..."}, - "metal_kit": {"key": "metalkit9-....tgz", "sha256": "...", "url_base": "..."} - }, + "corpus": {"repo": "...", "rev": "...", "sha256": "64-hex"}, "runs": [ {"model": "qwen3.5-4b", "backend": "cuda", "probe": {"conversations": 4, "turns": 4, "block_chars": 6300}} ] @@ -58,9 +59,10 @@ Model references resolve to repo/rev/file/sha entries that live in 4. **Guard-exits requeue; real errors diagnose.** `NO_PYTHON312`/`NO_AARCH64_HOST`/placement bounces: `jy requeue ` (submit dedupes identical specs). Anything else: read `jy logs | tail -30` first. -5. **`fleet` pre-flights every kit URL** (range GET) before submitting. Freshly uploaded chunks - can take minutes to propagate to every CDN edge; never submit right after an upload without - the pre-flight. +5. **`fleet` pre-flights the pinned commit** (`git ls-remote`) before submitting, and the + worker builds everything from that commit. Never distribute binaries through external object + storage: source pins + jy artifacts only. The historical CDN path-keyed negative-cache + (404s pinned for hours per URL path) is exactly why. 6. **A/B experiments must target the intended budget knob.** `AGENTX_SKIPPY_PREFIX_CACHE_BUDGET` (exact-state catalog cap) is distinct from `AGENTX_SKIPPY_PREFIX_CACHE_RAM` (resident checkpoint RAM). diff --git a/skippy/evals/agentx/fleet-smoke-worker.sh b/skippy/evals/agentx/fleet-smoke-worker.sh deleted file mode 100644 index d02789b46b..0000000000 --- a/skippy/evals/agentx/fleet-smoke-worker.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env bash -# Fleet smoke worker: one model, llama vs skippy, 4-conversation multi-turn -# probe. Managed by `cargo xtool automation agentx fleet --mode smoke`; the -# env contract matches the fleet spec generator. Never hand-edit run copies. -set -Eeuo pipefail -W=$PWD -export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" -if [ "$BACKEND" = "cuda" ]; then - [ "$(uname -m)" = "aarch64" ] || { echo NO_AARCH64_HOST; exit 33; } - nvidia-smi -L >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } -fi -THREADS="${THREADS:-20}" -mkdir -p "$W/opt/kv-tools" "$W/opt/kv-runtime" "$W/parts" -# ---- kits (CDN, sha-verified) ---- -fetch_chunks () { # prefix count out sha - for i in $(seq 0 $(($2-1))); do ii=$(printf '%02d' "$i"); - curl -fsSL --retry 4 --retry-delay 3 --max-time 900 "$KIT_URL_BASE/$1$ii" -o "$W/parts/f$ii" || { echo FETCH_FAIL $1$ii; exit 41; }; done - cat "$W/parts"/f0* "$W/parts"/f1* "$W/parts"/f2* > "$3" 2>/dev/null || cat "$W/parts"/f* > "$3" - printf '%s %s\n' "$4" "$3" | shasum -a256 -c - || { echo SHA_MISMATCH "$3"; exit 41; } -} -if [ "$BACKEND" = "cuda" ]; then - fetch_chunks "$CUDA_KEY_PREFIX" "$CUDA_CHUNKS" "$W/tools.tgz" "$CUDA_TGZ_SHA" - fetch_chunks "$LLAMA_KEY_PREFIX" "$LLAMA_CHUNKS" "$W/llama.tgz" "$LLAMA_TGZ_SHA" - tar xzf "$W/tools.tgz" -C "$W/opt" skippy native-runtimes - mv "$W/opt/skippy" "$W/opt/kv-tools/skippy" - cp -R "$W/opt/native-runtimes/meshllm-native-runtime-linux-aarch64-cuda13/." "$W/opt/kv-runtime/" - mkdir -p "$W/opt/standard/bin" "$W/opt/standard/lib" - tar xzf "$W/llama.tgz" -C "$W/opt/standard" - LDC=$(ldconfig -p 2>/dev/null); RT="$W/opt/kv-runtime" - for lib in libssl.so.3 libcrypto.so.3; do - line=$(printf '%s\n' "$LDC" | grep -m1 " $lib ") || true; [ -n "$line" ] || continue - cp "$(printf '%s' "$line" | awk '{print $NF}')" "$RT/lib/$lib" - "$HOME/.local/bin/patchelf" --set-rpath '$ORIGIN' "$RT/lib/$lib" 2>/dev/null || patchelf --set-rpath '$ORIGIN' "$RT/lib/$lib" || true - done - chmod +x "$W/opt/standard/bin/llama-server" 2>/dev/null || true -else - # metal: single kit tarball holding kv-tools/ standard/ kv-runtime/ - curl -fsSL --retry 4 --retry-delay 3 --max-time 1200 "$KIT_URL_BASE/$METAL_KIT_KEY" -o "$W/kit.tgz" || { echo FETCH_FAIL metal; exit 41; } - printf '%s %s\n' "$METAL_KIT_SHA" "$W/kit.tgz" | shasum -a256 -c - - tar xzf "$W/kit.tgz" -C "$W/opt" - MEM=$(sysctl -n hw.memsize 2>/dev/null || echo 0) - [ "$MEM" -ge "$((MIN_MAC_MEM_BYTES:-200000000000))" ] || { echo NEED_BIGGER_MAC; exit 30; } - if ! command -v python3.12 >/dev/null; then - PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-apple-darwin-install_only.tar.gz" - mkdir -p "$W/py312"; curl -fsSL --retry 3 --max-time 600 "$PYURL" -o "$W/py312.tgz" \ - && tar xzf "$W/py312.tgz" -C "$W/py312" && export PATH="$W/py312/python/bin:$PATH" \ - || { echo NO_PYTHON312; exit 31; } - fi -fi -# ---- model (hub cache verified, else verified download) ---- -HUB="${HF_HOME:-$HOME/.cache/huggingface}/hub" -MODEL="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV/$MODEL_FILE" -if [ ! -f "$MODEL" ] || ! printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - 2>/dev/null; then - echo "downloading $MODEL_FILE" - mkdir -p "$W/models"; MODEL="$W/models/$MODEL_FILE" - ok=0 - for a in 1 2 3; do rm -f "$MODEL" - curl -fL --retry 4 --retry-all-errors --max-time 2400 "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" -o "$MODEL" \ - && printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - && ok=1 && break - sleep 10 - done - [ "$ok" = "1" ] || { echo MODEL_DOWNLOAD_FAILED; exit 45; } -fi -# ---- probe ---- -cat > "$W/smoke.py" <<'PYEOF' -import concurrent.futures, json, sys, time, urllib.request, urllib.error -PORT, NCONV, TURNS, BLOCK, MAXTOK = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]) -def convo(i, turn): - filler = f"Session {i} stable context block. " * 220 - history = "\n".join(f"User: {filler[:BLOCK*k]} Question {i}-{k}: name a color." for k in range(1, turn+1)) - return [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":history+f" Q{i}-{turn}: describe a sunset in one paragraph."}] -def ask(pair): - i, turn = pair - body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() - t0=time.time(); err=None; pt=ct=comp=0 - try: - r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) - out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} - pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) - except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}" - except Exception as e: err=f"{type(e).__name__}: {e}" - return (i, turn, pt, ct, comp, time.time()-t0, err) -turns=[] -for turn in range(1, TURNS+1): - t0=time.time() - with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: - results = list(ex.map(ask, [(i,turn) for i in range(NCONV)])) - wall=time.time()-t0 - errs=[r for r in results if r[6]] - if errs: - for r in errs[:2]: print(f" turn {turn} conv {r[0]}: ERROR {r[6]}", flush=True) - continue - toks=sum(r[4] for r in results); cached=sum(r[3] for r in results); prompts=sum(r[2] for r in results) - print(f" RESULT turn {turn}: {toks/wall:6.1f} tok/s | cached {100*cached/max(prompts,1):3.0f}% | wall {wall:5.1f}s", flush=True) - turns.append(toks/wall) -if turns: - steady=turns[1:] or turns - print(f" SUMMARY steady_tok_s={sum(steady)/len(steady):.1f}", flush=True) -PYEOF -PORT=64800 -run_engine () { # name logfile ready_timeout cmd... - NAME="$1"; LOG="$2"; RT="$3"; shift 3 - PORT=$((PORT+1)) - "$@" > "$W/$LOG" 2>&1 & - PID=$! - for i in $(seq 1 "$RT"); do sleep 5; curl -s --max-time 3 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1 && break; done - echo "-- $NAME:" - python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true - kill $PID 2>/dev/null || true; sleep 8 -} -echo "===== MODEL $MODEL_KEY ($BACKEND) =====" -if [ "$BACKEND" = "cuda" ]; then - run_engine llama "serve-llama.log" 120 "$W/opt/standard/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size $((131072*PROBE_CONVERSATIONS)) --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" - run_engine skippy "serve-skippy.log" 180 "$W/opt/kv-tools/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$W/opt/kv-runtime" -else - run_engine llama "serve-llama.log" 120 "$W/opt/standard/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size $((131072*PROBE_CONVERSATIONS)) --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" - run_engine skippy "serve-skippy.log" 180 "$W/opt/kv-tools/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers -1 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$W/opt/kv-runtime" -fi -echo SMOKE_DONE diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 51a38363fc..c9d968ae77 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -1,237 +1,205 @@ -#!/bin/bash +#!/usr/bin/env bash +# Fleet worker: builds product + baseline from pinned source in-job, then runs +# the AgentX benchmark. Everything that leaves the machine travels through jy +# artifacts (the daemon uploads $JIANYANG_ARTIFACT_DIR); nothing is fetched +# from or pushed to external object storage. Managed by +# `cargo xtool automation agentx fleet`; see .agents/skills/agentx-fleet-bench. +# +# Env contract (set by the generated spec): +# MODE (smoke|comparison), PRODUCT_COMMIT, REPO_URL, +# BACKEND (cuda|metal), MODEL_KEY, MODEL_REPO, MODEL_REV, MODEL_FILE, MODEL_SHA, +# TOK_REPO, TOK_REV, CORPUS_REPO, CORPUS_REV, CORPUS_SHA (comparison), +# PROBE_CONVERSATIONS, PROBE_TURNS, PROBE_BLOCK_CHARS, PROBE_MAX_TOKENS (smoke), +# THREADS, CAMPAIGN +# Exit codes: 30 need-bigger-mac, 31 no-python, 33 wrong-arch, 34 repo-clone, +# 46 product-build, 47 baseline-build, 48 client-env set -Eeuo pipefail W=$PWD export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" -R2="${KIT_URL_BASE:?KIT_URL_BASE required}" -echo "== host ==" -if command -v nproc >/dev/null; then nproc; elif command -v sysctl >/dev/null; then sysctl -n hw.ncpu; fi -if [ "$BACKEND" = metal ]; then +THREADS="${THREADS:-20}" + +# ---- host guards (hardware placement; never node names) ---- +if [ "$BACKEND" = "cuda" ]; then + [ "$(uname -m)" = "aarch64" ] || { echo NO_AARCH64_HOST; exit 33; } + nvidia-smi -L >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } +else MEM=$(sysctl -n hw.memsize 2>/dev/null || echo 0) - if [ "$MEM" -lt 200000000000 ]; then echo NEED_BIGGER_MAC; exit 30; fi -fi -if [ "$BACKEND" = cuda ]; then - nvidia-smi -L 2>/dev/null | grep NVIDIA >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } + [ "$MEM" -ge 200000000000 ] || { echo NEED_BIGGER_MAC; exit 30; } fi -if [ "$BACKEND" = "cuda" ] && [ "$(uname -m)" != "aarch64" ]; then echo NO_AARCH64_HOST; exit 33; fi if ! command -v python3.12 >/dev/null; then - echo "installing userspace python3.12" - PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-unknown-linux-gnu-install_only.tar.gz" - [ "$(uname -s)" = Darwin ] && PYURL="https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-aarch64-apple-darwin-install_only.tar.gz" + PYTUPLE="aarch64-unknown-linux-gnu"; [ "$(uname -s)" = Darwin ] && PYTUPLE="aarch64-apple-darwin" mkdir -p "$W/py312" - curl -fsSL --retry 3 --max-time 600 "$PYURL" -o "$W/py312.tar.gz" \ - && tar xzf "$W/py312.tar.gz" -C "$W/py312" \ - && export PATH="$W/py312/python/bin:$PATH" \ - && hash -r \ + curl -fsSL --retry 3 --max-time 600 "https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-$PYTUPLE-install_only.tar.gz" -o "$W/py312.tgz" \ + && tar xzf "$W/py312.tgz" -C "$W/py312" && export PATH="$W/py312/python/bin:$PATH" \ || { echo NO_PYTHON312; exit 31; } fi -command -v python3.12 >/dev/null || { echo NO_PYTHON312; exit 31; } -nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || system_profiler SPDisplaysDataType 2>/dev/null | grep -m1 -i 'chip\|GPU' || true -# ---- branch source ---- -curl -fL --retry 3 -o "$W/src.tgz" "$SRC_URL" -printf '%s %s\n' "$INPUT_ARCHIVE_SHA" "$W/src.tgz" | shasum -a256 -c - -mkdir -p "$W/repo" "$W/parts" "$W/tu" && tar xzf "$W/src.tgz" -C "$W/repo" -cd "$W/repo" -command -v cargo >/dev/null || (curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal) +command -v cargo >/dev/null || curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal command -v just >/dev/null || cargo install just --locked -command -v uv >/dev/null || (curl -LsSf https://astral.sh/uv/install.sh | sh) -python3.12 --version || { echo NO_PYTHON312; exit 42; } -command -v patchelf >/dev/null || { mkdir -p "$HOME/.local/bin" "$W/pf"; curl -fsSL --retry 3 https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-aarch64.tar.gz | tar xz -C "$W/pf"; cp "$(find "$W/pf" -name patchelf -type f -print -quit)" "$HOME/.local/bin/patchelf"; export PATH="$HOME/.local/bin:$PATH"; } -export COPYFILE_DISABLE=1 -OPT="$W/opt"; mkdir -p "$OPT/kv-tools" "$OPT/kv-runtime" "$OPT/standard/bin" "$OPT/standard/lib" "$W/models" "$JIANYANG_ARTIFACT_DIR" -# stagger concurrent campaign starts to avoid CDN rate limits -sleep $((RANDOM % 90)) -echo "== provisioning from CDN ==" -fetch(){ local out="$W/parts/$2"; for t in 1 2 3 4 5 6 7 8; do curl -sfL --retry 5 --retry-delay 5 --retry-all-errors --max-time 300 -C - "$R2/$1" -o "$out" 2>/dev/null && [ -s "$out" ] && return 0; sleep $((t*5)); done; echo "FETCH_FAIL $1"; return 41; } -if [ "$BACKEND" = cuda ]; then - : > "$W/tools.tgz" - for i in $(seq 0 $((CUDA_CHUNKS-1))); do ii=$(printf '%02d' "$i"); pn=$(basename "$CUDA_KEY_PREFIX$ii"); fetch "$CUDA_KEY_PREFIX$ii" "$pn" && cat "$W/parts/$pn" >> "$W/tools.tgz" || exit 41; done - printf '%s %s\n' "$CUDA_TGZ_SHA" "$W/tools.tgz" | shasum -a256 -c - - : > "$W/llama.tgz" - for i in $(seq 0 $((LLAMA_CHUNKS-1))); do ii=$(printf '%02d' "$i"); pn=$(basename "$LLAMA_KEY_PREFIX$ii"); fetch "$LLAMA_KEY_PREFIX$ii" "$pn" && cat "$W/parts/$pn" >> "$W/llama.tgz" || exit 41; done - printf '%s %s\n' "$LLAMA_TGZ_SHA" "$W/llama.tgz" | shasum -a256 -c - - tar xzf "$W/tools.tgz" -C "$W/tu" - SKBN=$(find "$W/tu" -name skippy -type f -print -quit) - cp "$SKBN" "$OPT/kv-tools/skippy" - RTB=$(find "$W/tu/native-runtimes" -maxdepth 1 -mindepth 1 -type d -print -quit) - cp -R "$RTB"/. "$OPT/kv-runtime/" - mkdir -p "$OPT/standard" - tar xzf "$W/llama.tgz" -C "$OPT/standard" - # the vanilla baseline links openssl; pin requires it inside the pinned runtime - for l in libssl.so.3 libcrypto.so.3; do - if [ ! -f "$OPT/standard/lib/$l" ]; then - p=$(find /usr/lib /lib -name "$l" -type f -print -quit 2>/dev/null) - if [ -z "$p" ]; then - all=$(ldconfig -p 2>/dev/null | awk -v lib="$l" '$1==lib {print $NF}') - p=${all%%$'\n'*} - fi - [ -n "$p" ] && { cp "$p" "$OPT/standard/lib/$l"; patchelf --set-rpath '$ORIGIN' "$OPT/standard/lib/$l" || { echo "PATCH_RPATH_FAIL $l"; exit 46; }; echo "copied+rpath'd $l from $p"; } || { echo "MISSING_SYSTEM_$l"; exit 45; } - fi - done -else - mn=$(basename "$METAL_KIT_KEY") - fetch "$METAL_KIT_KEY" "$mn" - printf '%s %s\n' "$METAL_KIT_SHA" "$W/parts/$mn" | shasum -a256 -c - - tar xzf "$W/parts/$mn" -C "$OPT" + +# ---- product source at the pinned commit ---- +echo "== cloning $REPO_URL @ ${PRODUCT_COMMIT:0:12}" +git clone -q "$REPO_URL" "$W/repo" || { echo REPO_CLONE_FAILED; exit 34; } +cd "$W/repo" +git checkout -q --detach "$PRODUCT_COMMIT" || { echo COMMIT_CHECKOUT_FAILED; exit 34; } +UPSTREAM_PIN="$(tr -d '[:space:]' < skippy/llama_cpp/upstream.txt)" + +# ---- product build: native runtime + skippy CLI (owning recipes) ---- +echo "== building product runtime (backend=$BACKEND)" +if ! just release-runtime-build "$BACKEND" > "$W/build-runtime.log" 2>&1; then + tail -5 "$W/build-runtime.log"; echo PRODUCT_BUILD_FAILED; exit 46 fi -chmod +x "$OPT/kv-tools/skippy" "$OPT/standard/bin/llama-server" -# the kits were rpath-rewritten after packaging; re-record the actual payload hashes -python3 - "$OPT/kv-runtime" <<'PY3' -import json, hashlib, os, sys -root = sys.argv[1] -mf = os.path.join(root, 'manifest.json') -d = json.load(open(mf)) -def sha(p): return hashlib.sha256(open(p,'rb').read()).hexdigest() -for section in ('files','tools'): - m = d['runtime'].get(section, {}) - changed = 0 - for rel in list(m): - p = os.path.join(root, rel) - if os.path.isfile(p): - got = sha(p) - if m[rel] != got: - m[rel] = got - changed += 1 - print('manifest %s: re-recorded %d hashes' % (section, changed)) -json.dump(d, open(mf,'w'), indent=2) -PY3 -"$OPT/standard/bin/llama-server" --version 2>&1 | head -1 || true -"$OPT/kv-tools/skippy" --version 2>&1 | head -1 || true -# ---- self-diagnostic (cuda only; macos lacks readelf) ---- -if [ "$BACKEND" = cuda ]; then -cat > "$W/depwalk.py" <<'PY2' -import subprocess,sys,os,re -exe,root,rtroot=sys.argv[1],sys.argv[2],sys.argv[3] -HOST={"ld-linux.so.2","ld-linux-aarch64.so.1","linux-vdso.so.1","libc.so.6","libcrypt.so.1","libdl.so.2","libgcc_s.so.1","libatomic.so.1","libgomp.so.1","libm.so.6","libnsl.so.1","libnuma.so.1","libpthread.so.0","libresolv.so.2","librt.so.1","libstdc++.so.6","libutil.so.1","libz.so.1","libcuda.so","libcuda.so.1","libnvidia-ml.so.1"} -def readelf(f): return subprocess.run(['readelf','-d',f],capture_output=True,text=True).stdout -def needed(f): return re.findall(r'\(NEEDED\).*?\[(.*?)\]',readelf(f)) -def runpaths(f): - out=readelf(f) - return re.findall(r'\(RUNPATH\).*?\[(.*?)\]',out)+re.findall(r'\(RPATH\).*?\[(.*?)\]',out) -def ldd(f): return subprocess.run(['ldd',f],capture_output=True,text=True).stdout -def lddlibs(f): - res=[] - for line in ldd(f).splitlines(): - m=re.match(r'\s*(\S+)\s+=>\s+(\S+)',line) - if m: res.append(m.group(2)) - return res -visited=set(); pending=[exe] -for dp,_,fns in os.walk(root): - for fn in fns: - if fn.endswith('.dylib') or fn.endswith('.so') or '.so.' in fn: pending.append(os.path.join(dp,fn)) -problems=[] -while pending: - f=pending.pop(); rf=os.path.realpath(f) - if rf in visited or not os.path.isfile(rf): continue - visited.add(rf) - if not rf.startswith(root): problems.append(f"ESCAPES: {rf}"); continue - origin=os.path.dirname(rf) - rps=[x.replace('$ORIGIN',origin) for x in runpaths(rf)] - for nd in needed(rf): - b=os.path.basename(nd) - if b in HOST: continue - if nd.startswith('/'): cands=[nd] - else: cands=[os.path.join(d,b) for d in rps]+[os.path.join(origin,b)] - found=next((c for c in cands if os.path.isfile(c)),None) - if not found: problems.append(f"ABSENT: {nd} importer={rf}") - else: pending.append(found) -print('DIAG_VISITED:',len(visited)) -print('DIAG_PROBLEMS:' if problems else 'DIAG_CLEAN') -for p in problems[:15]: print(' ',p) -PY2 -python3 "$W/depwalk.py" "$OPT/standard/bin/llama-server" "$OPT/standard" "$OPT/kv-runtime" || true +if ! just skippy-cli-release-build > "$W/build-cli.log" 2>&1; then + tail -5 "$W/build-cli.log"; echo PRODUCT_BUILD_FAILED; exit 46 +fi +RUNTIME_DIR="$(ls -d "$W/repo/dist/native-runtimes"/meshllm-native-runtime-* 2>/dev/null | head -1)" +NATIVE_COMMIT="$(git -C "$W/repo/.deps/llama.cpp" rev-parse HEAD 2>/dev/null || echo "$PRODUCT_COMMIT")" +[ -n "$RUNTIME_DIR" ] || { echo RUNTIME_DIR_MISSING; exit 46; } + +# ---- baseline build: unpatched llama-server at the upstream pin ---- +echo "== building vanilla llama-server @ ${UPSTREAM_PIN:0:12}" +git clone -q https://github.com/ggml-org/llama.cpp "$W/llama-upstream" || { echo BASELINE_CLONE_FAILED; exit 47; } +cd "$W/llama-upstream" && git checkout -q --detach "$UPSTREAM_PIN" +CMAKE_FLAGS=(-DLLAMA_CURL=OFF -DCMAKE_BUILD_TYPE=Release) +if [ "$BACKEND" = "cuda" ]; then + CMAKE_FLAGS+=(-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121) +fi +cmake -B build -S . "${CMAKE_FLAGS[@]}" > "$W/baseline-cmake.log" 2>&1 || { tail -5 "$W/baseline-cmake.log"; echo BASELINE_BUILD_FAILED; exit 47; } +cmake --build build --target llama-server -j "$THREADS" > "$W/baseline-build.log" 2>&1 || { tail -5 "$W/baseline-build.log"; echo BASELINE_BUILD_FAILED; exit 47; } +mkdir -p "$W/repo/.deps/agentx-llama-build/bin" "$W/repo/.deps/agentx-llama-build/lib" +cp build/bin/llama-server "$W/repo/.deps/agentx-llama-build/bin/" +[ -d build/lib ] && cp build/lib/*.so* "$W/repo/.deps/agentx-llama-build/lib/" 2>/dev/null || true +"$W/repo/.deps/agentx-llama-build/bin/llama-server" --version || { echo BASELINE_SERVER_BROKEN; exit 47; } + +# ---- link fixups for the pinned baseline (system ssl/crypto, $ORIGIN rpath) ---- +if [ "$BACKEND" = "cuda" ]; then + command -v patchelf >/dev/null || { mkdir -p "$W/pf" "$HOME/.local/bin"; \ + curl -fsSL --retry 3 https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-aarch64.tar.gz | tar xz -C "$W/pf"; \ + cp "$(find "$W/pf" -name patchelf -type f -print -quit)" "$HOME/.local/bin/patchelf"; export PATH="$HOME/.local/bin:$PATH"; } + LDC=$(ldconfig -p 2>/dev/null); BLD="$W/repo/.deps/agentx-llama-build" + for lib in libssl.so.3 libcrypto.so.3; do + line=$(printf '%s\n' "$LDC" | grep -m1 " $lib ") || true; [ -n "$line" ] || continue + cp "$(printf '%s' "$line" | awk '{print $NF}')" "$BLD/lib/$lib" + patchelf --set-rpath '$ORIGIN' "$BLD/lib/$lib" || true + done + patchelf --set-rpath '$ORIGIN/../lib' "$BLD/bin/llama-server" 2>/dev/null || true fi -# ---- model + corpus + tokenizer from the ambient HF cache (NFS model store) ---- + +# ---- model (hub cache verified, else verified download) ---- HUB="${HF_HOME:-$HOME/.cache/huggingface}/hub" -MSnap="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV" -if [ -f "$MSnap/$MODEL_FILE" ]; then - MODEL_PATH="$MSnap/$MODEL_FILE" -else - echo "model not cached; downloading" - mkdir -p "$W/models" - curl -fL --retry 3 -o "$W/models/$MODEL_FILE" "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" - MODEL_PATH="$W/models/$MODEL_FILE" +MODEL="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV/$MODEL_FILE" +if [ ! -f "$MODEL" ] || ! printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - 2>/dev/null; then + echo "downloading $MODEL_FILE" + mkdir -p "$W/models"; MODEL="$W/models/$MODEL_FILE" + ok=0 + for a in 1 2 3; do rm -f "$MODEL" + curl -fL --retry 4 --retry-all-errors --max-time 2400 "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" -o "$MODEL" \ + && printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - && ok=1 && break + sleep 10 + done + [ "$ok" = "1" ] || { echo MODEL_DOWNLOAD_FAILED; exit 45; } +fi + +if [ "$MODE" = "smoke" ]; then + # ---- smoke: llama vs skippy multi-turn probe ---- + cat > "$W/smoke.py" <<'PYEOF' +import concurrent.futures, json, sys, time, urllib.request, urllib.error +PORT, NCONV, TURNS, BLOCK, MAXTOK = (int(a) for a in sys.argv[1:6]) +def convo(i, turn): + filler = f"Session {i} stable context block. " * 220 + history = "\n".join(f"User: {filler[:BLOCK*k]} Question {i}-{k}: name a color." for k in range(1, turn+1)) + return [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":history+f" Q{i}-{turn}: describe a sunset in one paragraph."}] +def ask(pair): + i, turn = pair + body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() + t0=time.time(); err=None; pt=ct=comp=0 + try: + r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) + out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} + pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) + except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}" + except Exception as e: err=f"{type(e).__name__}: {e}" + return (i, turn, pt, ct, comp, time.time()-t0, err) +turns=[] +for turn in range(1, TURNS+1): + t0=time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: + results = list(ex.map(ask, [(i,turn) for i in range(NCONV)])) + wall=time.time()-t0 + errs=[r for r in results if r[6]] + if errs: + for r in errs[:2]: print(f" turn {turn} conv {r[0]}: ERROR {r[6]}", flush=True) + continue + toks=sum(r[4] for r in results); cached=sum(r[3] for r in results); prompts=sum(r[2] for r in results) + print(f" RESULT turn {turn}: {toks/wall:6.1f} tok/s | cached {100*cached/max(prompts,1):3.0f}% | wall {wall:5.1f}s", flush=True) + turns.append(toks/wall) +if turns: + steady=turns[1:] or turns + print(f" SUMMARY steady_tok_s={sum(steady)/len(steady):.1f}", flush=True) +PYEOF + PORT=65100 + run_engine () { + NAME="$1"; RT="$2"; shift 2 + PORT=$((PORT+1)) + "$@" > "$W/serve-$NAME.log" 2>&1 & + PID=$! + for i in $(seq 1 "$RT"); do sleep 5; curl -s --max-time 3 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1 && break; done + echo "-- $NAME:" + python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true + kill $PID 2>/dev/null || true; sleep 8 + } + echo "===== MODEL $MODEL_KEY ($BACKEND) =====" + NGL=99; [ "$BACKEND" = "metal" ] && NGL=-1 + CTX=$((131072*PROBE_CONVERSATIONS)) + run_engine llama 120 "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size "$CTX" --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" + run_engine skippy 180 "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers "$NGL" --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" + echo SMOKE_DONE + exit 0 fi -printf '%s %s\n' "$MODEL_SHA" "$MODEL_PATH" | shasum -a256 -c - -# tokenizer must live at the env-derived hub snapshot path (verify_tokenizer_snapshot -# requires pinned == derived); NFS tokenizer dirs can be unreadable, so stage locally + +# ---- comparison: full provenance-pinned campaign ---- +cd "$W/repo" +echo "== client env" +just agentx-setup > "$W/agentx-setup.log" 2>&1 || { tail -5 "$W/agentx-setup.log"; echo CLIENT_ENV_FAILED; exit 48; } +CLIENT="$W/repo/skippy/evals/agentx/.venv/bin/agentx" +[ -x "$CLIENT" ] || { echo NO_AGENTX_CLIENT; exit 48; } +find "$W/repo/skippy/evals/agentx/.venv/lib" -name '*.pth' -type f 2>/dev/null | while read -r p; do grep -q "^import" "$p" && rm -f "$p" && echo "removed: $p"; done || true + export HF_HUB_CACHE="$W/hf/hub" TD="$HF_HUB_CACHE/models--${TOK_REPO//\//--}/snapshots/$TOK_REV" mkdir -p "$TD" for f in tokenizer.json tokenizer_config.json special_tokens_map.json config.json generation_config.json; do [ -s "$TD/$f" ] || curl -sfL "https://huggingface.co/$TOK_REPO/resolve/$TOK_REV/$f" -o "$TD/$f" || true done -ls "$TD" + CORPUS_PATH="$HUB/datasets--${CORPUS_REPO//\//--}/snapshots/$CORPUS_REV/traces.jsonl" if [ ! -f "$CORPUS_PATH" ]; then mkdir -p "$(dirname "$CORPUS_PATH")" 2>/dev/null || { mkdir -p "$W/models"; CORPUS_PATH="$W/models/traces.jsonl"; } - curl -fL --retry 3 -o "$CORPUS_PATH" "https://huggingface.co/datasets/$CORPUS_REPO/resolve/$CORPUS_REV/traces.jsonl" + curl -fL --retry 4 --max-time 2400 "https://huggingface.co/datasets/$CORPUS_REPO/resolve/$CORPUS_REV/traces.jsonl" -o "$CORPUS_PATH" || { echo CORPUS_FAILED; exit 49; } fi printf '%s %s\n' "$CORPUS_SHA" "$CORPUS_PATH" | shasum -a256 -c - -# ---- agentx client env ---- -just agentx-setup 2>&1 | tail -3 -CLIENT="$W/repo/skippy/evals/agentx/.venv/bin/agentx" -[ -x "$CLIENT" ] || { echo NO_AGENTX_CLIENT; exit 43; } -# pin policy: the prepared environment must not contain executable .pth imports -find "$W/repo/skippy/evals/agentx/.venv/lib" -name '*.pth' -type f | while read -r p; do grep -q "^import" "$p" && rm -f "$p" && echo "removed: $p"; done || true -# ---- request.paths.json ---- -MANIFEST=$(find "$OPT/kv-runtime" -name manifest.json -print -quit) + +MANIFEST=$(find "$RUNTIME_DIR" -name manifest.json -print -quit) DIGEST=$(python3 - "$MANIFEST" <<'PY' import json,sys -d=json.load(open(sys.argv[1])) -print(d["build"]["llama_patch_digest"]) +print(json.load(open(sys.argv[1]))["build"]["llama_patch_digest"]) PY ) -echo "patch digest: $DIGEST" -THREADS="${THREADS:-20}" python3 - <&1 | tail -4 -# ---- campaign ---- -( while sleep 120; do - { - echo "===== $(date -u +%H:%M:%S) observer tick" - echo "-- campaign-out:"; ls "$W/campaign-out" 2>/dev/null - for arm in "$W/campaign-out"/*/; do - [ -d "$arm" ] || continue - echo "-- arm $(basename "$arm"):"; ls "$arm" 2>/dev/null - for cell in "$arm"*/; do - [ -d "$cell" ] || continue - echo " cell $(basename "$cell"): $(ls "$cell" 2>/dev/null | tr '\n' ' ')" - [ -f "$cell/server.stderr.log" ] && tail -2 "$cell/server.stderr.log" 2>/dev/null | sed 's/^/ srv: /' - [ -f "$cell/agentx.stdout.log" ] && tail -2 "$cell/agentx.stdout.log" 2>/dev/null | sed 's/^/ cli: /' - done - done - echo "-- procs:"; ps -eo pid,pcpu,pmem,etime,args 2>/dev/null | grep -E 'llama-server|skippy serve|agentx' | grep -v grep | head -6 - echo "-- ports:"; (ss -ltnp 2>/dev/null || netstat -ltnp 2>/dev/null) | grep -E '127.0.0.1' | head -6 - for p in $( (ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null) | grep 127.0.0.1 | awk '{print $NF}' | cut -d: -f2 | sort -un | head -8); do - curl -s --max-time 3 "http://127.0.0.1:$p/slots" 2>/dev/null | head -c 400 | sed "s/^/ port $p: /"; echo - done - } >> "$JIANYANG_ARTIFACT_DIR/live-progress.log" 2>&1 - tar czf "$JIANYANG_ARTIFACT_DIR/evidence-latest.tgz" -C "$W" campaign-out 2>/dev/null || true - done ) & -OBS_PID=$! +export JIANYANG_COMMIT="$PRODUCT_COMMIT" +cargo xtool automation agentx pin --input "$W/request.paths.json" --output "$W/request.pinned.json" 2>&1 | tail -3 +( while sleep 120; do ls "$W/campaign-out" >> "$JIANYANG_ARTIFACT_DIR/live-progress.log" 2>/dev/null; done ) & +OBS=$! CMP_RC=0 -cargo xtool automation agentx comparison --input "$W/repo/request.pinned.json" --output "$W/campaign-out" 2>&1 | tail -10 || CMP_RC=1 -ls -la "$W/campaign-out" 2>/dev/null | head -20 || true -echo "== skippy ldd =="; ldd "$OPT/kv-tools/skippy" 2>&1 | grep -E 'not found' || echo LDD_SKIPPY_CLEAN -for f in "$W/campaign-out"/doctor "$W/campaign-out"/*.log; do - [ -f "$f" ] && { echo "--- $f (tail 60)"; tail -60 "$f"; } -done 2>/dev/null || true -if [ -d "$W/campaign-out/doctor" ]; then - find "$W/campaign-out/doctor" -type f | head -5 | while read -r df; do echo "--- $df (tail 60)"; tail -60 "$df"; done -fi -# ---- evidence out (chunked) ---- -tar czf "$W/evidence.tgz" -C "$W" campaign-out request.paths.json request.pinned.json 2>/dev/null || tar czf "$W/evidence.tgz" -C "$W" campaign-out -split -b 64m -d "$W/evidence.tgz" "$JIANYANG_ARTIFACT_DIR/evidence-" -shasum -a256 "$W/evidence.tgz" > "$JIANYANG_ARTIFACT_DIR/evidence.manifest" -[ "$CMP_RC" = 0 ] && echo "CAMPAIGN_OK" || { echo "CAMPAIGN_FAILED rc=$CMP_RC"; kill "$OBS_PID" 2>/dev/null || true; exit 1; } -kill "$OBS_PID" 2>/dev/null || true +cargo xtool automation agentx comparison --input "$W/request.pinned.json" --output "$W/campaign-out" 2>&1 | tail -10 || CMP_RC=1 +kill $OBS 2>/dev/null || true +tar czf "$JIANYANG_ARTIFACT_DIR/evidence.tgz" -C "$W" campaign-out request.paths.json request.pinned.json 2>/dev/null || tar czf "$JIANYANG_ARTIFACT_DIR/evidence.tgz" -C "$W" campaign-out +shasum -a256 "$JIANYANG_ARTIFACT_DIR/evidence.tgz" | awk '{print $1" evidence.tgz"}' > "$JIANYANG_ARTIFACT_DIR/evidence.tgz.manifest" +[ "$CMP_RC" = "0" ] && echo CAMPAIGN_OK || { echo "CAMPAIGN_FAILED rc=$CMP_RC"; exit 1; } diff --git a/tools/xtask/src/automation/agentx/fleet.rs b/tools/xtask/src/automation/agentx/fleet.rs index 05d3d94fde..26ede0e7fb 100644 --- a/tools/xtask/src/automation/agentx/fleet.rs +++ b/tools/xtask/src/automation/agentx/fleet.rs @@ -20,32 +20,23 @@ pub(super) const FLEET_USAGE: &str = pub(super) struct FleetManifest { pub campaign: String, pub product_source_commit: String, + /// Product repository; defaults to the public mesh-llm repository. + #[serde(default = "default_repo_url")] + pub repo_url: String, pub mode: String, - pub kit: FleetKit, + pub corpus: Option, pub runs: Vec, } -#[derive(Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub(super) struct FleetKit { - pub url_base: String, - pub cuda_chunks: Option, - pub llama_chunks: Option, - pub metal_kit: Option, -} - -#[derive(Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub(super) struct FleetChunkSet { - pub prefix: String, - pub count: u32, - pub sha256: String, +fn default_repo_url() -> String { + "https://github.com/Mesh-LLM/mesh-llm".to_string() } #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub(super) struct FleetArtifact { - pub key: String, +pub(super) struct FleetCorpus { + pub repo: String, + pub rev: String, pub sha256: String, } @@ -77,56 +68,30 @@ fn validate(manifest: &FleetManifest) -> DynResult<()> { if manifest.runs.is_empty() { return Err("fleet manifest needs at least one run".into()); } + if manifest.mode == "comparison" && manifest.corpus.is_none() { + return Err("comparison mode requires corpus pins".into()); + } for run in &manifest.runs { if !matches!(run.backend.as_str(), "cuda" | "metal") { return Err(format!("run {} backend must be cuda or metal", run.model).into()); } - if run.backend == "metal" && manifest.kit.metal_kit.is_none() { - return Err(format!( - "run {} is metal but the kit has no metal artifact", - run.model - ) - .into()); - } - if run.backend == "cuda" && manifest.kit.cuda_chunks.is_none() { - return Err(format!("run {} is cuda but the kit has no cuda chunks", run.model).into()); - } } Ok(()) } -/// Kit URLs a manifest depends on, for pre-flight. Returns (url, label) pairs. -fn kit_urls(manifest: &FleetManifest) -> Vec<(String, String)> { - let base = manifest.kit.url_base.trim_end_matches('/'); - let mut urls = Vec::new(); - if let Some(cuda) = manifest.kit.cuda_chunks.as_ref() { - for index in 0..cuda.count { - urls.push(( - format!("{base}/{}{index:02}", cuda.prefix), - format!("cuda chunk {index:02}"), - )); - } - } - if let Some(llama) = manifest.kit.llama_chunks.as_ref() { - for index in 0..llama.count { - urls.push(( - format!("{base}/{}{index:02}", llama.prefix), - format!("llama chunk {index:02}"), - )); - } - } - if let Some(metal) = manifest.kit.metal_kit.as_ref() { - urls.push((format!("{base}/{}", metal.key), "metal kit".to_string())); - } - urls +/// Pre-flight: the pinned product commit must exist in the product repository +/// before any job is generated or submitted. +fn commit_exists(repo_url: &str, commit: &str) -> DynResult { + let output = std::process::Command::new("git") + .args(["ls-remote", repo_url]) + .output() + .map_err(|e| format!("git ls-remote {repo_url}: {e}"))?; + let text = String::from_utf8_lossy(&output.stdout); + Ok(text.contains(commit)) } -fn worker_script(root: &Path, mode: &str) -> DynResult { - let script = match mode { - "smoke" => "fleet-smoke-worker.sh", - _ => "fleet-worker.sh", - }; - let path = root.join("skippy/evals/agentx").join(script); +fn worker_script(root: &Path) -> DynResult { + let path = root.join("skippy/evals/agentx/fleet-worker.sh"); std::fs::read_to_string(&path) .map_err(|_| format!("fleet worker script missing: {}", path.display()))? .lines() @@ -175,7 +140,8 @@ fn run_spec( let mut env = json!({ "WORKER_B64": worker_b64, "WORKER_SHA": worker_sha, - "KIT_URL_BASE": manifest.kit.url_base.trim_end_matches('/'), + "MODE": manifest.mode, + "REPO_URL": manifest.repo_url, "BACKEND": run.backend, "CAMPAIGN": manifest.campaign, "PRODUCT_COMMIT": manifest.product_source_commit, @@ -189,22 +155,13 @@ fn run_spec( "THREADS".into(), json!(run.probe.get("threads").copied().unwrap_or(20).to_string()), ); - if let Some(cuda) = manifest.kit.cuda_chunks.as_ref() { - if !hex64(&cuda.sha256) { - return Err("cuda chunk sha256 must be 64-hex".into()); + if let Some(corpus) = manifest.corpus.as_ref() { + if !hex64(&corpus.sha256) { + return Err("corpus sha256 must be 64-hex".into()); } - env_obj.insert("CUDA_KEY_PREFIX".into(), json!(cuda.prefix)); - env_obj.insert("CUDA_CHUNKS".into(), json!(cuda.count.to_string())); - env_obj.insert("CUDA_TGZ_SHA".into(), json!(cuda.sha256)); - } - if let Some(llama) = manifest.kit.llama_chunks.as_ref() { - env_obj.insert("LLAMA_KEY_PREFIX".into(), json!(llama.prefix)); - env_obj.insert("LLAMA_CHUNKS".into(), json!(llama.count.to_string())); - env_obj.insert("LLAMA_TGZ_SHA".into(), json!(llama.sha256)); - } - if let Some(metal) = manifest.kit.metal_kit.as_ref() { - env_obj.insert("METAL_KIT_KEY".into(), json!(metal.key)); - env_obj.insert("METAL_KIT_SHA".into(), json!(metal.sha256)); + env_obj.insert("CORPUS_REPO".into(), json!(corpus.repo)); + env_obj.insert("CORPUS_REV".into(), json!(corpus.rev)); + env_obj.insert("CORPUS_SHA".into(), json!(corpus.sha256)); } let mut probe = json!({ "PROBE_CONVERSATIONS": run.probe.get("conversations").copied().unwrap_or(4).to_string(), @@ -263,7 +220,7 @@ fn submit(root: &Path, manifest_path: &Path) -> DynResult<()> { &crate::automation::receipt_files::bounded(manifest_path, 1024 * 1024)?, )?; validate(&manifest)?; - let script = worker_script(root, &manifest.mode)?; + let script = worker_script(root)?; use sha2::{Digest, Sha256}; let worker_sha = hex(&Sha256::digest(script.as_bytes())); let worker_b64 = { @@ -272,12 +229,13 @@ fn submit(root: &Path, manifest_path: &Path) -> DynResult<()> { }; let run_root = root.join("target/agentx-fleet").join(&manifest.campaign); std::fs::create_dir_all(&run_root)?; - // Pre-flight every kit URL before generating or submitting anything. - for (url, label) in kit_urls(&manifest) { - let status = crate::command::probe_url_range(&url)?; - if status != 206 { - return Err(format!("pre-flight failed for {label}: HTTP {status} from {url} (fresh uploads can take minutes to propagate)").into()); - } + if !commit_exists(&manifest.repo_url, &manifest.product_source_commit)? { + return Err(format!( + "pre-flight failed: commit {} not found in {}", + &manifest.product_source_commit[..12.min(manifest.product_source_commit.len())], + manifest.repo_url + ) + .into()); } let mut resolved = Vec::new(); for run in &manifest.runs { @@ -372,9 +330,6 @@ mod tests { "campaign": "test-20260101", "product_source_commit": "e821ec38b1479cc2dd41da40e1b46e90b4a29850", "mode": "smoke", - "kit": {"url_base": "https://cdn.example/x", - "cuda_chunks": {"prefix": "cuda5-", "count": 2, "sha256": "a".repeat(64)}, - "llama_chunks": {"prefix": "llama-", "count": 1, "sha256": "b".repeat(64)}}, "runs": [{"model": "qwen3-4b", "backend": "cuda"}] })) .unwrap() @@ -422,14 +377,26 @@ mod tests { spec["target"].get("nodes").is_none(), "hardware targeting only" ); - assert_eq!(spec["runtime"]["env"]["CUDA_CHUNKS"], "2"); + assert_eq!(spec["runtime"]["env"]["MODE"], "smoke"); + assert_eq!( + spec["runtime"]["env"]["REPO_URL"], + "https://github.com/Mesh-LLM/mesh-llm" + ); assert_eq!(spec["runtime"]["env"]["PROBE_TURNS"], "4"); } #[test] - fn preflight_urls_cover_every_chunk() { - let urls = kit_urls(&manifest()); - assert_eq!(urls.len(), 3, "2 cuda chunks + 1 llama chunk"); - assert!(urls[0].0.ends_with("/cuda5-00")); + fn comparison_requires_corpus_pins() { + let mut m = manifest(); + m.mode = "comparison".into(); + assert!( + validate(&m).is_err(), + "comparison without corpus pins must fail" + ); + } + + #[test] + fn smoke_manifest_accepts_without_corpus() { + assert!(validate(&manifest()).is_ok()); } } From fbd6ae232a475dbb44f8e28ab8c098e4b1122a89 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 13:33:51 +1100 Subject: [PATCH 43/81] fix(xtask): build fleet inputs without sccache on fresh machines A cold sccache cannot cache CUDA cubin outputs and fails the runtime build outright; the fleet worker now runs its in-job builds with a sccache-free PATH (the script auto-detects sccache otherwise). --- skippy/evals/agentx/fleet-worker.sh | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index c9d968ae77..9c92dc17c6 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -35,6 +35,13 @@ if ! command -v python3.12 >/dev/null; then fi command -v cargo >/dev/null || curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal command -v just >/dev/null || cargo install just --locked +# Fresh machine: a cold sccache adds failure modes (CUDA cubin outputs are not +# cacheable) with no cache benefit. Build with a sccache-free PATH. +BUILD_PATH="$PATH" +if command -v sccache >/dev/null 2>&1; then + SCC_DIR="$(dirname "$(command -v sccache)")" + BUILD_PATH="$(printf '%s' "$PATH" | tr ':' '\n' | grep -v "^$SCC_DIR$" | paste -sd: -)" +fi # ---- product source at the pinned commit ---- echo "== cloning $REPO_URL @ ${PRODUCT_COMMIT:0:12}" @@ -45,10 +52,10 @@ UPSTREAM_PIN="$(tr -d '[:space:]' < skippy/llama_cpp/upstream.txt)" # ---- product build: native runtime + skippy CLI (owning recipes) ---- echo "== building product runtime (backend=$BACKEND)" -if ! just release-runtime-build "$BACKEND" > "$W/build-runtime.log" 2>&1; then +if ! PATH="$BUILD_PATH" just release-runtime-build "$BACKEND" > "$W/build-runtime.log" 2>&1; then tail -5 "$W/build-runtime.log"; echo PRODUCT_BUILD_FAILED; exit 46 fi -if ! just skippy-cli-release-build > "$W/build-cli.log" 2>&1; then +if ! PATH="$BUILD_PATH" just skippy-cli-release-build > "$W/build-cli.log" 2>&1; then tail -5 "$W/build-cli.log"; echo PRODUCT_BUILD_FAILED; exit 46 fi RUNTIME_DIR="$(ls -d "$W/repo/dist/native-runtimes"/meshllm-native-runtime-* 2>/dev/null | head -1)" @@ -63,8 +70,8 @@ CMAKE_FLAGS=(-DLLAMA_CURL=OFF -DCMAKE_BUILD_TYPE=Release) if [ "$BACKEND" = "cuda" ]; then CMAKE_FLAGS+=(-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121) fi -cmake -B build -S . "${CMAKE_FLAGS[@]}" > "$W/baseline-cmake.log" 2>&1 || { tail -5 "$W/baseline-cmake.log"; echo BASELINE_BUILD_FAILED; exit 47; } -cmake --build build --target llama-server -j "$THREADS" > "$W/baseline-build.log" 2>&1 || { tail -5 "$W/baseline-build.log"; echo BASELINE_BUILD_FAILED; exit 47; } +PATH="$BUILD_PATH" cmake -B build -S . "${CMAKE_FLAGS[@]}" > "$W/baseline-cmake.log" 2>&1 || { tail -5 "$W/baseline-cmake.log"; echo BASELINE_BUILD_FAILED; exit 47; } +PATH="$BUILD_PATH" cmake --build build --target llama-server -j "$THREADS" > "$W/baseline-build.log" 2>&1 || { tail -5 "$W/baseline-build.log"; echo BASELINE_BUILD_FAILED; exit 47; } mkdir -p "$W/repo/.deps/agentx-llama-build/bin" "$W/repo/.deps/agentx-llama-build/lib" cp build/bin/llama-server "$W/repo/.deps/agentx-llama-build/bin/" [ -d build/lib ] && cp build/lib/*.so* "$W/repo/.deps/agentx-llama-build/lib/" 2>/dev/null || true From 98ac0d778b3b179ffa3b7152ecc30c58d0656a7b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 13:40:59 +1100 Subject: [PATCH 44/81] fix(xtask): disable fleet in-job sccache through the build script's switch LLAMA_STAGE_USE_SCCACHE=0 / SKIPPY_USE_SCCACHE=0 is the supported no-cache path; filtering sccache's directory out of PATH can also remove the toolchain that shares its prefix, failing compiles with signal 126. --- skippy/evals/agentx/fleet-worker.sh | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 9c92dc17c6..87cd3ec5bf 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -36,12 +36,10 @@ fi command -v cargo >/dev/null || curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal command -v just >/dev/null || cargo install just --locked # Fresh machine: a cold sccache adds failure modes (CUDA cubin outputs are not -# cacheable) with no cache benefit. Build with a sccache-free PATH. +# cacheable) with no cache benefit. Use the build script's own off switch. +export LLAMA_STAGE_USE_SCCACHE=0 +export SKIPPY_USE_SCCACHE=0 BUILD_PATH="$PATH" -if command -v sccache >/dev/null 2>&1; then - SCC_DIR="$(dirname "$(command -v sccache)")" - BUILD_PATH="$(printf '%s' "$PATH" | tr ':' '\n' | grep -v "^$SCC_DIR$" | paste -sd: -)" -fi # ---- product source at the pinned commit ---- echo "== cloning $REPO_URL @ ${PRODUCT_COMMIT:0:12}" From 3acd8e8d90277c2688417af2a75ca4b63e328a5b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 14:33:27 +1100 Subject: [PATCH 45/81] fix(xtask): retry refused connections in the fleet smoke probe A freshly started server can drop part of its first concurrent accept burst; the probe retried nothing, so two of four conversations failed every turn against a healthy baseline and invalidated the engine's whole section. Each request now retries connection-level failures briefly before reporting an error. --- skippy/evals/agentx/fleet-worker.sh | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 87cd3ec5bf..201d6def2f 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -117,12 +117,19 @@ def ask(pair): i, turn = pair body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() t0=time.time(); err=None; pt=ct=comp=0 - try: - r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) - out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} - pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) - except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}" - except Exception as e: err=f"{type(e).__name__}: {e}" + # A freshly started server can refuse part of its first concurrent accept + # burst while its listener finishes warming up; retry briefly instead of + # failing the whole conversation. + for attempt in range(6): + try: + r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) + out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} + pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) + err=None; break + except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}"; break + except Exception as e: + err=f"{type(e).__name__}: {e}" + if attempt < 5: time.sleep(5) return (i, turn, pt, ct, comp, time.time()-t0, err) turns=[] for turn in range(1, TURNS+1): From e06ea6a1745b908172b06771e58a6187f830b614 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 16:57:18 +1100 Subject: [PATCH 46/81] fix(xtask): ship smoke serve logs as artifacts and stagger probe starts The smoke probe's server logs stayed in the workdir, so the llama baseline's deterministic refusal of two concurrent connections could not be diagnosed from run artifacts; copy them into JIANYANG_ARTIFACT_DIR for the 0.9.46 streamer. Conversation starts are staggered by one second to separate an accept-burst limit from a slot-level failure. --- skippy/evals/agentx/fleet-worker.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 201d6def2f..d4c7801488 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -115,6 +115,7 @@ def convo(i, turn): return [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":history+f" Q{i}-{turn}: describe a sunset in one paragraph."}] def ask(pair): i, turn = pair + time.sleep(i) # stagger concurrent conversation starts by 1s each body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() t0=time.time(); err=None; pt=ct=comp=0 # A freshly started server can refuse part of its first concurrent accept @@ -164,6 +165,7 @@ PYEOF CTX=$((131072*PROBE_CONVERSATIONS)) run_engine llama 120 "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size "$CTX" --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" run_engine skippy 180 "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers "$NGL" --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" + cp "$W"/serve-*.log "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true echo SMOKE_DONE exit 0 fi From ec18fafaf714368cd50c4fde5cdd6bda80ea9a5b Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 17:09:40 +1100 Subject: [PATCH 47/81] fix(xtask): gate fleet smoke probes on real server readiness The health loop had no failure path - a server that died or never became fully ready was probed anyway, producing connection-refused noise instead of a diagnosis. Readiness now requires the /v1/models endpoint twice in a row (full slot allocation, not just a bound port), and a failed start dumps and ships the server log instead of running a doomed probe. --- skippy/evals/agentx/fleet-worker.sh | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index d4c7801488..01b130357f 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -155,7 +155,25 @@ PYEOF PORT=$((PORT+1)) "$@" > "$W/serve-$NAME.log" 2>&1 & PID=$! - for i in $(seq 1 "$RT"); do sleep 5; curl -s --max-time 3 "http://127.0.0.1:$PORT/health" >/dev/null 2>&1 && break; done + READY=0 + for i in $(seq 1 "$RT"); do + sleep 5 + kill -0 $PID 2>/dev/null || break + # Require the full API surface, not just a bound port: /v1/models + # answers only once the server has finished loading and its slots exist. + if curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1; then + READY=$((READY+1)); [ "$READY" -ge 2 ] && break + else + READY=0 + fi + done + if [ "$READY" -lt 2 ]; then + echo "-- $NAME: SERVER_START_FAILED; log tail:" + tail -30 "$W/serve-$NAME.log" 2>/dev/null | sed 's/^/ /' + cp "$W/serve-$NAME.log" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true + kill $PID 2>/dev/null || true; sleep 8 + return 1 + fi echo "-- $NAME:" python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true kill $PID 2>/dev/null || true; sleep 8 From 943b8a061de249bc31ab0c5c8d51504a4eff5a45 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 17:31:14 +1100 Subject: [PATCH 48/81] fix(xtask): collect llama-server's companion libs from build/bin too The upstream build places libllama-server-impl.so beside the binary in build/bin; the fleet worker only collected build/lib, so the baseline server failed to start with a missing shared library on every model. --- skippy/evals/agentx/fleet-worker.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 01b130357f..7eb8648c44 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -72,7 +72,11 @@ PATH="$BUILD_PATH" cmake -B build -S . "${CMAKE_FLAGS[@]}" > "$W/baseline-cmake. PATH="$BUILD_PATH" cmake --build build --target llama-server -j "$THREADS" > "$W/baseline-build.log" 2>&1 || { tail -5 "$W/baseline-build.log"; echo BASELINE_BUILD_FAILED; exit 47; } mkdir -p "$W/repo/.deps/agentx-llama-build/bin" "$W/repo/.deps/agentx-llama-build/lib" cp build/bin/llama-server "$W/repo/.deps/agentx-llama-build/bin/" -[ -d build/lib ] && cp build/lib/*.so* "$W/repo/.deps/agentx-llama-build/lib/" 2>/dev/null || true +# Companion shared libs live beside the binary in build/bin and in build/lib; +# collect both so the server finds libllama-server-impl.so and friends. +for libdir in build/bin build/lib; do + [ -d "$libdir" ] && cp "$libdir"/*.so* "$W/repo/.deps/agentx-llama-build/lib/" 2>/dev/null || true +done "$W/repo/.deps/agentx-llama-build/bin/llama-server" --version || { echo BASELINE_SERVER_BROKEN; exit 47; } # ---- link fixups for the pinned baseline (system ssl/crypto, $ORIGIN rpath) ---- From 9737f9648df09799b3f4f9b48bbff8257a9aa0e2 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 18:30:16 +1100 Subject: [PATCH 49/81] feat(xtask): decode-profile pass in the fleet smoke After the retention probe, each smoke run now streams 256-token generations at c1 and c4 for both engines, recording per-token timestamps: TTFT, ITL p50/mean, and aggregate tok/s per concurrency. This isolates decode throughput from caching so the remaining ~10-14% skippy-vs-llama steady gap can be analyzed (batching overhead vs per-token kernel cost). All serve logs ship as artifacts. --- skippy/evals/agentx/fleet-worker.sh | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 7eb8648c44..add7cefcd1 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -187,6 +187,59 @@ PYEOF CTX=$((131072*PROBE_CONVERSATIONS)) run_engine llama 120 "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size "$CTX" --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" run_engine skippy 180 "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers "$NGL" --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" + # ---- decode profile: streaming pass with per-token timestamps ---- + cat > "$W/profile.py" <<'PYEOF' +import json, sys, time, urllib.request +PORT, NCONV, MAXTOK = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) +def convo(i): + filler = f"Session {i} stable context block. " * 220 + return [{"role":"system","content":"You are a helpful assistant."}, + {"role":"user","content":filler + f" Q{i}: write a vivid paragraph about the ocean."}] +def profile_one(i): + body = json.dumps({"model":"m","messages":convo(i),"max_tokens":MAXTOK,"temperature":0,"stream":True}).encode() + req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}) + stamps = [] + t0 = time.time() + r = urllib.request.urlopen(req, timeout=600) + for line in r: + if not line.startswith(b"data: "): continue + payload = line[6:].strip() + if payload == b"[DONE]": break + try: chunk = json.loads(payload) + except Exception: continue + delta = chunk.get("choices",[{}])[0].get("delta",{}) + if delta.get("content"): stamps.append(time.time()) + ttft = stamps[0]-t0 if stamps else -1 + itls = [b-a for a,b in zip(stamps, stamps[1:])] if len(stamps)>1 else [] + return {"conv":i,"ttft_s":round(ttft,4),"tokens":len(stamps), + "itl_ms_p50":round(sorted(itls)[len(itls)//2]*1000,2) if itls else -1, + "itl_ms_mean":round(sum(itls)/len(itls)*1000,2) if itls else -1, + "tok_s":round(len(stamps)/(stamps[-1]-t0),2) if len(stamps)>1 else -1} +import concurrent.futures +for nconc in ([1] if NCONV==1 else [1, NCONV]): + with concurrent.futures.ThreadPoolExecutor(max_workers=nconc) as ex: + results = list(ex.map(profile_one, range(nconc))) + tok_s = sum(r["tok_s"] for r in results if r["tok_s"]>0) + itl = [r["itl_ms_p50"] for r in results if r["itl_ms_p50"]>0] + line = {"concurrency":nconc,"aggregate_tok_s":round(tok_s,1), + "itl_p50_ms":round(sum(itl)/len(itl),2) if itl else -1, + "per_conv":results} + print("PROFILE " + json.dumps(line), flush=True) +PYEOF + PORT=$((PORT+1)) + "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $PORT --parallel 4 --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size 524288 --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" > "$W/serve-llama-prof.log" 2>&1 & + LP=$! + for i in $(seq 1 120); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done + echo "-- llama profile:" + python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true + kill $LP 2>/dev/null || true; sleep 8 + PORT=$((PORT+1)) + "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 & + SP=$! + for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done + echo "-- skippy profile:" + python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true + kill $SP 2>/dev/null || true; sleep 8 cp "$W"/serve-*.log "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true echo SMOKE_DONE exit 0 From d5d7dcc416345d9159d8a4365df07f9931a89e0c Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 18:55:31 +1100 Subject: [PATCH 50/81] fix(skippy): make the hard byte cap enforce above the retention floor's working set Both eviction passes shared the same retention floor, so the hard pass could never evict anything the soft pass could not: with the catalog at the floor over the hard cap, the hard cap was dead code and the blob store accumulated retained copies past it without bound. The effective hard cap now adapts to the largest snapshot actually stored - max(configured hard, floor x current snapshot bytes) - so it trims growth above the working set instead of dead-coding against the same floor. For dense models whose attention-derived estimate is close to reality, the configured cap dominates and nothing changes. For hybrids whose estimate undercounts recurrent state, the adaptive floor dominates and the diagnostic reports the undercount. --- .../skippy-serving/src/kv_integration/config.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index e6bcc2ad4d..106a8712b6 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -830,7 +830,18 @@ fn store_exact_radix_record_with_codec( // need a tighter bound set an explicit exact-state budget. let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); evict_exact_entries_over(radix, blobs, limits.soft_bytes, retention_floor)?; - if evict_exact_entries_over(radix, blobs, limits.hard_bytes, retention_floor)? > 0 { + // The hard cap must be able to hold the retention floor's working set. + // With the attention-derived estimate alone, a hybrid snapshot can exceed + // the configured hard cap by itself; the eviction passes then share the + // same floor and the hard pass can never evict — the cap is dead code and + // the blob store accumulates retained copies past it without bound. The + // effective backstop adapts to the largest snapshot actually stored, so + // it trims growth above the working set instead of against the floor. + let floor_bytes = logical_bytes + .max(1) + .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); + let effective_hard = limits.hard_bytes.max(floor_bytes); + if evict_exact_entries_over(radix, blobs, effective_hard, retention_floor)? > 0 { // Observable signal that the attention-derived estimate undercounts // this stage's snapshots: the exact-state catalog held more than the // hard limit even with the retention floor binding. Set an explicit @@ -840,7 +851,7 @@ fn store_exact_radix_record_with_codec( message: "exact-state catalog exceeded its hard byte limit at the retention floor" .to_string(), context: Some(format!( - "soft_bytes={} hard_bytes={} floor_entries={retention_floor}", + "soft_bytes={} hard_bytes={} effective_hard={effective_hard} floor_entries={retention_floor}", limits.soft_bytes, limits.hard_bytes )), }, From 625d2f44a60e1880ab5472928355a86357573d3c Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 19:07:58 +1100 Subject: [PATCH 51/81] feat(xtask): prefill chunk-size sweep in the fleet smoke After the decode profile, start skippy at chunk sizes 64/256/512/2048 and measure TTFT for a fixed ~1.5K-token prompt, 3 trials each. If TTFT converges toward llama's baseline as the chunk grows, the staged runtime's chunked-prefill overhead is confirmed as the TTFT gap's cause and the fix is a larger default or adaptive policy. --- skippy/evals/agentx/fleet-worker.sh | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index add7cefcd1..00d3dde0bf 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -240,6 +240,43 @@ PYEOF echo "-- skippy profile:" python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true kill $SP 2>/dev/null || true; sleep 8 + # ---- prefill chunk sweep: TTFT vs chunk size ---- + echo "-- prefill chunk sweep:" + for CHUNK in 64 256 512 2048; do + PORT=$((PORT+1)) + "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --prefill-chunk-size "$CHUNK" --prefill-chunk-policy fixed --runtime-bundle "$RUNTIME_DIR" > "$W/serve-sweep-$CHUNK.log" 2>&1 & + SWPID=$! + for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done + if ! kill -0 $SWPID 2>/dev/null; then + echo " SWEEP chunk=$CHUNK SERVER_DIED" + continue + fi + python3 - "$PORT" "$CHUNK" <<'SWEEPPY' +import json, sys, time, urllib.request +PORT, CHUNK = int(sys.argv[1]), sys.argv[2] +filler = "Session sweep stable context block. " * 220 +msgs = [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":filler + " Write one paragraph about mountains."}] +body = json.dumps({"model":"m","messages":msgs,"max_tokens":64,"temperature":0,"stream":True}).encode() +ttfts = [] +for trial in range(3): + req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}) + t0 = time.time(); first = None; n = 0 + r = urllib.request.urlopen(req, timeout=120) + for line in r: + if not line.startswith(b"data: "): continue + p = line[6:].strip() + if p == b"[DONE]": break + try: c = json.loads(p) + except Exception: continue + if c.get("choices",[{}])[0].get("delta",{}).get("content"): + if first is None: first = time.time() + n += 1 + if first: ttfts.append(first - t0) +avg = sum(ttfts)/len(ttfts) if ttfts else -1 +print(f" SWEEP chunk={CHUNK} ttft_avg={avg:.3f}s (trials={len(ttfts)})", flush=True) +SWEEPPY + kill $SWPID 2>/dev/null || true; sleep 8 + done cp "$W"/serve-*.log "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true echo SMOKE_DONE exit 0 From b6dc1a48af909746dc8347c408ad0002f54149c7 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Mon, 16 Nov 2026 19:47:51 +1100 Subject: [PATCH 52/81] feat(xtask): emit skippy stderr telemetry spans during the decode profile The skippy serve in the profile pass now runs with SKIPPY_TELEMETRY_STDERR=1 so the request-path debug spans (admission, lookup, prefill, first token) land in serve-skippy-prof.log and ship as artifacts - localizing the fixed prefill overhead the chunk sweep proved is not chunk-size-driven. --- skippy/evals/agentx/fleet-worker.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 00d3dde0bf..1c05b5d506 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -234,7 +234,8 @@ PYEOF python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true kill $LP 2>/dev/null || true; sleep 8 PORT=$((PORT+1)) - "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 & + SKIPPY_TELEMETRY_STDERR=1 \ + "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2> "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 &1 & SP=$! for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done echo "-- skippy profile:" From 381d3c99da81f1d777a60fa80e5e9c8b1e1a90e3 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 17 Nov 2026 00:15:58 +1100 Subject: [PATCH 53/81] fix(xtask): wait for serve processes to exit before starting the next The fleet worker killed serves with SIGTERM and slept 8 seconds, but the skippy runtime can hold CUDA resources longer than that on some nodes. The next serve then failed to allocate and died silently. Every serve kill now waits up to 60 seconds for graceful exit, force-kills on timeout, and adds a settle delay before the next server starts. --- skippy/evals/agentx/fleet-worker.sh | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 1c05b5d506..afba66ce88 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -180,7 +180,10 @@ PYEOF fi echo "-- $NAME:" python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true - kill $PID 2>/dev/null || true; sleep 8 + kill $PID 2>/dev/null || true + for w in $(seq 1 12); do kill -0 $PID 2>/dev/null || break; sleep 5; done + kill -9 $PID 2>/dev/null || true + sleep 5 } echo "===== MODEL $MODEL_KEY ($BACKEND) =====" NGL=99; [ "$BACKEND" = "metal" ] && NGL=-1 @@ -232,7 +235,10 @@ PYEOF for i in $(seq 1 120); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done echo "-- llama profile:" python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true - kill $LP 2>/dev/null || true; sleep 8 + kill $LP 2>/dev/null || true + for w in $(seq 1 12); do kill -0 $LP 2>/dev/null || break; sleep 5; done + kill -9 $LP 2>/dev/null || true + sleep 5 PORT=$((PORT+1)) SKIPPY_TELEMETRY_STDERR=1 \ "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2> "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 &1 & @@ -240,7 +246,10 @@ PYEOF for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done echo "-- skippy profile:" python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true - kill $SP 2>/dev/null || true; sleep 8 + kill $SP 2>/dev/null || true + for w in $(seq 1 12); do kill -0 $SP 2>/dev/null || break; sleep 5; done + kill -9 $SP 2>/dev/null || true + sleep 5 # ---- prefill chunk sweep: TTFT vs chunk size ---- echo "-- prefill chunk sweep:" for CHUNK in 64 256 512 2048; do @@ -276,7 +285,10 @@ for trial in range(3): avg = sum(ttfts)/len(ttfts) if ttfts else -1 print(f" SWEEP chunk={CHUNK} ttft_avg={avg:.3f}s (trials={len(ttfts)})", flush=True) SWEEPPY - kill $SWPID 2>/dev/null || true; sleep 8 + kill $SWPID 2>/dev/null || true + for w in $(seq 1 12); do kill -0 $SWPID 2>/dev/null || break; sleep 5; done + kill -9 $SWPID 2>/dev/null || true + sleep 5 done cp "$W"/serve-*.log "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true echo SMOKE_DONE From 56fab3a52109110efef61dd85dd8091fd98c6e32 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 17 Nov 2026 00:48:14 +1100 Subject: [PATCH 54/81] fix(xtask): repair mangled skippy profile serve invocation A sed edit corrupted the line continuation into duplicate redirects and background markers; rewrite the serve block cleanly with the telemetry env prefix intact. --- skippy/evals/agentx/fleet-worker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index afba66ce88..6c033c86e5 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -241,7 +241,7 @@ PYEOF sleep 5 PORT=$((PORT+1)) SKIPPY_TELEMETRY_STDERR=1 \ - "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2> "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch 20 --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 &1 & + "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 & SP=$! for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done echo "-- skippy profile:" From d3d8b6d9a190ae76171e35d3479b6c7763286f0e Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 17 Nov 2026 05:08:42 +1100 Subject: [PATCH 55/81] feat(xtask): skippy no-cache profile pass to isolate prefill overhead After the regular skippy profile, run the same streaming probe with --prefix-cache off. If TTFT drops from ~705ms to ~334ms (llama's level), the overhead is the checkpoint export machinery. If it stays at ~705ms, the overhead is the staged runtime's execution itself. --- skippy/evals/agentx/fleet-worker.sh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 6c033c86e5..3008962041 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -250,6 +250,16 @@ PYEOF for w in $(seq 1 12); do kill -0 $SP 2>/dev/null || break; sleep 5; done kill -9 $SP 2>/dev/null || true sleep 5 + # ---- skippy profile WITHOUT prefix cache: isolates checkpoint export cost ---- + PORT=$((PORT+1)) + "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache off --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-nocache.log" 2>&1 & + NP=$! + for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done + kill -0 $NP 2>/dev/null && echo "-- skippy nocache profile:" && python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || echo "-- skippy nocache: SERVER_DIED" + kill $NP 2>/dev/null || true + for w in $(seq 1 12); do kill -0 $NP 2>/dev/null || break; sleep 5; done + kill -9 $NP 2>/dev/null || true + sleep 5 # ---- prefill chunk sweep: TTFT vs chunk size ---- echo "-- prefill chunk sweep:" for CHUNK in 64 256 512 2048; do From 06d022178aa7f4931c771028c2583b35c777b4e6 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 17 Nov 2026 05:14:49 +1100 Subject: [PATCH 56/81] feat(xtask): nsys CUDA timeline profiling for prefill overhead isolation Profile one c1 prefill per engine (llama, skippy with cache, skippy without cache) under nsys --trace=cuda,nvtx. The CUDA timelines will separate compute kernel time from memory copies (checkpoint export) from CPU gaps (bookkeeping), giving the three-way overhead breakdown. --- skippy/evals/agentx/fleet-worker.sh | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh index 3008962041..167f6b6fe7 100644 --- a/skippy/evals/agentx/fleet-worker.sh +++ b/skippy/evals/agentx/fleet-worker.sh @@ -250,6 +250,39 @@ PYEOF for w in $(seq 1 12); do kill -0 $SP 2>/dev/null || break; sleep 5; done kill -9 $SP 2>/dev/null || true sleep 5 + # ---- nsys CUDA timeline: one c1 prefill per engine ---- + echo "-- nsys profiles:" + for ENGINE in llama skippy skippy-nocache; do + PORT=$((PORT+1)) + EXTRA="" + [ "$ENGINE" = "skippy-nocache" ] && EXTRA="--prefix-cache off" + [ "$ENGINE" = "skippy" ] || [ "$ENGINE" = "skippy-nocache" ] && BIN="$W/repo/target/release/skippy" || BIN="$W/repo/.deps/agentx-llama-build/bin/llama-server" + if [ "$ENGINE" = "llama" ]; then + nsys profile -o "$W/nsys-$ENGINE" --trace=cuda,nvtx --force-overwrite=true \ + "$BIN" --model "$MODEL" --alias m --host 127.0.0.1 --port $PORT --parallel 1 --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --ctx-size 131072 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" > /dev/null 2>&1 & + else + [ "$ENGINE" = "skippy" ] && PC="on" || PC="off" + nsys profile -o "$W/nsys-$ENGINE" --trace=cuda,nvtx --force-overwrite=true \ + "$BIN" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache "$PC" --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > /dev/null 2>&1 & + fi + NPID=$! + for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done + kill -0 $NPID 2>/dev/null && python3 - "$PORT" <<'NSYSPY' +import json, sys, time, urllib.request +PORT = int(sys.argv[1]) +msgs = [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Session stable context block. "*220 + " Write one paragraph."}] +body = json.dumps({"model":"m","messages":msgs,"max_tokens":32,"temperature":0,"stream":False}).encode() +t0=time.time() +r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=300) +out=json.load(r) +print(f" nsys {PORT}: ttft={out.get('choices',[{}])[0].get('created',0)} total={time.time()-t0:.3f}s tokens={out.get('usage',{}).get('completion_tokens',0)}") +NSYSPY + kill $NPID 2>/dev/null || true; sleep 10; kill -9 $NPID 2>/dev/null || true; sleep 5 + done + # Ship nsys reports + for f in "$W"/nsys-*.nsys-rep; do [ -f "$f" ] && cp "$f" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null; done + for f in "$W"/nsys-*.qdrep; do [ -f "$f" ] && cp "$f" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null; done + # ---- skippy profile WITHOUT prefix cache: isolates checkpoint export cost ---- PORT=$((PORT+1)) "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache off --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-nocache.log" 2>&1 & From 25770dcefd5853198b4746c316d0105af2e1c209 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:39 +1100 Subject: [PATCH 57/81] fix(skippy): stop building native test targets no patch defines build-llama.sh listed skippy-asr-decode-boundary and skippy-diffusion-host-fallback among the stage test targets, and the full replay contract asserted them. Main's model-support patches no longer define either, so `just skippy-native-tests` and `just skippy-native-full-replay` failed. Both lists now match main. --- skippy/scripts/build-llama.sh | 2 -- .../tests/workload_oracle_producer_contract/full_replay.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 588d44ba2d..6bf4d894f2 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -528,9 +528,7 @@ if [[ "$LLAMA_STAGE_WORKLOAD_ORACLE" == "ON" ]]; then fi if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then BUILD_TARGETS+=( - skippy-asr-decode-boundary skippy-backend-sample-capacity - skippy-diffusion-host-fallback skippy-graph-build-inputs skippy-hardware-application-probe skippy-model-fixture-generator diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index 9133bb0aa5..f8082a5988 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -224,9 +224,7 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( assert!(contains(configure, flag)); } for target in [ - "skippy-asr-decode-boundary", "skippy-backend-sample-capacity", - "skippy-diffusion-host-fallback", "skippy-graph-build-inputs", "skippy-selected-logits", "skippy-hardware-application-probe", From 738bef66eb125eaccb86be48303b92af277d18ad Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:39 +1100 Subject: [PATCH 58/81] fix(skippy): keep compacted KV rows when their chunk had been released Queue patch 0036. A chunk whose cells were all free gave its pages back to the kernel and was marked released; the next ubatch writing into it zeroed the whole chunk first. Compaction moved live rows into such a chunk without clearing the mark, so the next token appended there zeroed the prefix just moved. Compaction now reclaims each destination chunk before copying rows into it. test-skippy-kv-release-compact frees a chunk below a live sequence, compacts the sequence into it, appends a token there and checks the moved rows. It joins the full-replay native targets. --- .../skippy-api/src/split-certified.json | 2 +- ...leased-chunks-before-compaction-copi.patch | 214 ++++++++++++++++++ skippy/scripts/build-llama.sh | 1 + .../full_replay.rs | 1 + 4 files changed, 217 insertions(+), 1 deletion(-) create mode 100644 skippy/llama_cpp/patches/0036-llama-reclaim-released-chunks-before-compaction-copi.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 59735d316a..83286254b3 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "8822c30bd89df32a7c804d0c696780700c7dd7f10a55d6121d02cfcff9eff03e" + "patch_queue_sha256": "f759075c7dff254bedaca46586f8df00f39dbadbe6d58fd7d1e4d33d79e3c13d" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0036-llama-reclaim-released-chunks-before-compaction-copi.patch b/skippy/llama_cpp/patches/0036-llama-reclaim-released-chunks-before-compaction-copi.patch new file mode 100644 index 0000000000..aff80cddd2 --- /dev/null +++ b/skippy/llama_cpp/patches/0036-llama-reclaim-released-chunks-before-compaction-copi.patch @@ -0,0 +1,214 @@ +From bc0e2f85b4fc6db42178aff53ace97937a1da05b Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Wed, 18 Nov 2026 20:03:10 +1100 +Subject: [PATCH 36/39] llama: reclaim released chunks before compaction copies + rows into them + +A chunk whose cells are all free hands its pages back to the kernel and is +marked released; the next ubatch that writes into it zeroes the whole chunk +first. Compaction moved live rows into such a chunk without clearing the +mark, so the next write there, a decoded token appended after a compacted +prefix, zeroed the prefix it had just moved. + +Compaction now reclaims each destination chunk before copying rows into it, +as apply_ubatch does before a ubatch writes. Every other writer already goes +through apply_ubatch. + +test-skippy-kv-release-compact frees a chunk below a live sequence, +compacts the sequence into it and appends a token there, then checks the +moved rows. +--- + src/llama-kv-cache.cpp | 16 +++ + src/llama-kv-cache.h | 1 + + tests/CMakeLists.txt | 1 + + tests/test-skippy-kv-release-compact.cpp | 120 +++++++++++++++++++++++ + 4 files changed, 138 insertions(+) + create mode 100644 tests/test-skippy-kv-release-compact.cpp + +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index 8dd006f9e..b8c00f857 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -678,6 +678,20 @@ void llama_kv_cache::reclaim_chunks(uint32_t stream, const std::vector + trace.set_value("bytes", (int64_t) bytes); + } + ++void llama_kv_cache::reclaim_compaction_targets(const std::vector & moves) { ++ std::vector streams(n_stream); ++ std::iota(streams.begin(), streams.end(), 0); ++ std::for_each(streams.begin(), streams.end(), [&](uint32_t s) { ++ std::vector targets; ++ std::for_each(moves.begin(), moves.end(), [&](const compaction_move & move) { ++ if (move.strm == s) { ++ targets.push_back(move.dst); ++ } ++ }); ++ reclaim_chunks(s, targets); ++ }); ++} ++ + bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + skippy_trace::scope trace("llama.kv_seq_rm", "seq", seq_id); + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] +@@ -1098,6 +1112,8 @@ llama_memory_context_ptr llama_kv_cache::init_update(llama_context * lctx, bool + const auto moves = compact_cells(); + did_compact = !moves.empty(); + if (did_compact) { ++ // a row moved into a released chunk must not be zeroed by the next write there ++ reclaim_compaction_targets(moves); + copy_compacted_cells(moves); + LLAMA_LOG_DEBUG("%s: compacted %zu KV cells\n", __func__, moves.size()); + } +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index d17215dda..ad9257353 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -313,6 +313,7 @@ public: + void release_free_chunks(); + void release_free_chunks(uint32_t stream); + void reclaim_chunks(uint32_t stream, const std::vector & idxs); ++ void reclaim_compaction_targets(const std::vector & moves); + // the byte range of chunks [chunk0, chunk1) of `stream` in each cache tensor + void for_each_chunk_range(uint32_t stream, uint32_t chunk0, uint32_t chunk1, + const std::function & fn) const; +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index c1449c563..077620687 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -195,6 +195,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) + llama_build_and_test(test-skippy-kv-cells-contiguous.cpp) + llama_build_and_test(test-skippy-kv-rows-aligned.cpp) + llama_build_and_test(test-skippy-kv-place-together.cpp) ++ llama_build_and_test(test-skippy-kv-release-compact.cpp) + llama_build_and_test(test-skippy-task-pool.cpp) + target_include_directories(test-skippy-task-pool PRIVATE ${PROJECT_SOURCE_DIR}/src) + llama_build_and_test(test-skippy-recurrent-state-roundtrip.cpp) +diff --git a/tests/test-skippy-kv-release-compact.cpp b/tests/test-skippy-kv-release-compact.cpp +new file mode 100644 +index 000000000..9ea25b89f +--- /dev/null ++++ b/tests/test-skippy-kv-release-compact.cpp +@@ -0,0 +1,120 @@ ++// A chunk whose pages went back to the kernel is zeroed when a ubatch next writes into it. ++// Compaction can move a live sequence into such a chunk; its rows must survive that write. ++#include "../src/llama-batch.h" ++#include "../src/llama-kv-cache.h" ++#include "../src/llama-model.h" ++ ++#include ++#include ++#include ++#include ++#include ++ ++static int failures = 0; ++#define CHECK(cond) do { if (!(cond)) { ++failures; std::printf("FAIL line %d: %s\n", __LINE__, #cond); } } while (0) ++ ++namespace { ++ ++constexpr uint32_t chunk = llama_kv_cache::kv_chunk_cells; ++ ++struct tokens_at { ++ std::vector pos; ++ std::vector seq; ++ std::vector seq_ptr; ++ std::vector n_seq; ++ llama_seq_id unq; ++ llama_ubatch ubatch{}; ++ llama_kv_cache::slot_info slot{}; ++ ++ tokens_at(llama_seq_id id, llama_pos p0, uint32_t cell0, uint32_t n) ++ : pos(n), seq(n, id), seq_ptr(n), n_seq(n, 1), unq(id) { ++ std::iota(pos.begin(), pos.end(), p0); ++ std::transform(seq.begin(), seq.end(), seq_ptr.begin(), [](llama_seq_id & s) { return &s; }); ++ ubatch.n_tokens = n; ++ ubatch.n_pos = 1; ++ ubatch.n_seq_tokens = n; ++ ubatch.n_seqs = ubatch.n_seqs_unq = 1; ++ ubatch.pos = pos.data(); ++ ubatch.n_seq_id = n_seq.data(); ++ ubatch.seq_id = seq_ptr.data(); ++ ubatch.seq_id_unq = &unq; ++ slot.s0 = slot.s1 = 0; ++ slot.strm = { 0 }; ++ slot.idxs = { std::vector(n) }; ++ std::iota(slot.idxs[0].begin(), slot.idxs[0].end(), cell0); ++ } ++ ++ tokens_at(const tokens_at &) = delete; ++ tokens_at & operator=(const tokens_at &) = delete; ++}; ++ ++void fill(llama_kv_cache & kv, uint32_t cell0, uint32_t n, float value) { ++ std::for_each(kv.cell_tensors.begin(), kv.cell_tensors.end(), [&](ggml_tensor * t) { ++ const size_t per_row = t->nb[1]/sizeof(float); ++ std::vector rows(per_row*n); ++ std::vector at(rows.size()); ++ std::iota(at.begin(), at.end(), size_t(0)); ++ std::transform(at.begin(), at.end(), rows.begin(), [&](size_t i) { return value + (float) (cell0 + i/per_row); }); ++ ggml_backend_tensor_set(t, rows.data(), (size_t) cell0*t->nb[1], rows.size()*sizeof(float)); ++ }); ++} ++ ++bool holds(const llama_kv_cache & kv, uint32_t cell0, uint32_t n, float value, uint32_t from) { ++ return std::all_of(kv.cell_tensors.begin(), kv.cell_tensors.end(), [&](ggml_tensor * t) { ++ const size_t per_row = t->nb[1]/sizeof(float); ++ std::vector rows(per_row*n); ++ ggml_backend_tensor_get(t, rows.data(), (size_t) cell0*t->nb[1], rows.size()*sizeof(float)); ++ std::vector at(rows.size()); ++ std::iota(at.begin(), at.end(), size_t(0)); ++ return std::all_of(at.begin(), at.end(), [&](size_t i) { return rows[i] == value + (float) (from + i/per_row); }); ++ }); ++} ++ ++} ++ ++int main() { ++ std::unique_ptr model(llama_model_create(LLM_ARCH_LLAMA, llama_model_default_params())); ++ if (!model) { ++ std::printf("failed to create test model\n"); ++ return 1; ++ } ++ llama_hparams hparams{}; ++ hparams.n_layer_all = 1; ++ hparams.n_embd_head_k_full = hparams.n_embd_head_v_full = 4; ++ hparams.n_embd_head_k_swa = hparams.n_embd_head_v_swa = 4; ++ hparams.n_embd_head_k_mla_impl = hparams.n_embd_head_v_mla_impl = 4; ++ hparams.n_head_arr[0] = hparams.n_head_kv_arr[0] = 1; ++ llama_kv_cache kv(*model, false, hparams, GGML_TYPE_F32, GGML_TYPE_F32, ++ false, false, true, 4*chunk, 2, 0, LLAMA_SWA_TYPE_NONE, nullptr, ++ [](int32_t il) { return il == 0; }, {}, {}); ++ if (!kv.release_pages) { ++ std::printf("SKIP: this platform keeps freed KV pages\n"); ++ return 0; ++ } ++ ++ const uint32_t prefix = 20; ++ const float mark = 100.0f; ++ tokens_at other(1, 0, 0, chunk); ++ kv.apply_ubatch(other.slot, other.ubatch); ++ tokens_at kept(0, 0, chunk, prefix); ++ kv.apply_ubatch(kept.slot, kept.ubatch); ++ fill(kv, chunk, prefix, mark); ++ ++ kv.seq_rm(1, -1, -1); ++ CHECK(kv.chunk_released[0]); ++ ++ kv.init_update(nullptr, true); ++ CHECK(kv.seq_pos_min(0) == 0 && kv.seq_pos_max(0) == (llama_pos) prefix - 1); ++ CHECK(holds(kv, 0, prefix, mark, chunk)); ++ ++ tokens_at next(0, prefix, prefix, 1); ++ kv.apply_ubatch(next.slot, next.ubatch); ++ CHECK(holds(kv, 0, prefix, mark, chunk)); ++ ++ if (failures) { ++ std::printf("%d check(s) failed\n", failures); ++ return 1; ++ } ++ std::printf("OK\n"); ++ return 0; ++} +-- +2.43.0 + diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 6bf4d894f2..80c9400aad 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -553,6 +553,7 @@ if [[ "$LLAMA_STAGE_FULL_REPLAY" == "ON" ]]; then test-skippy-kv-page-export test-skippy-kv-rows-aligned test-skippy-kv-place-together + test-skippy-kv-release-compact test-skippy-task-pool test-skippy-model-loader-accounting test-skippy-recurrent-state-roundtrip diff --git a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs index f8082a5988..381d65b497 100644 --- a/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs +++ b/tools/xtask/tests/workload_oracle_producer_contract/full_replay.rs @@ -242,6 +242,7 @@ fn replay_explicit_builds_retained_skippy_gates_and_runs_bounded_filtered_ctest( "test-skippy-kv-page-export", "test-skippy-kv-rows-aligned", "test-skippy-kv-place-together", + "test-skippy-kv-release-compact", "test-skippy-task-pool", "test-skippy-model-loader-accounting", "test-skippy-recurrent-state-roundtrip", From ec1fa114bf47aa78ba50994b0cc4af027712e688 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:39 +1100 Subject: [PATCH 59/81] fix(skippy): check every row-list entry before Metal reads a block from the cache Queue patch 0037. ggml_flash_attn_ext_rows accepts any row list, but two Metal paths judged a 32-entry block consecutive from its first and last entries alone: the host check that selects the gather-free kernel, and the per-block shortcut inside the general kernel. A block such as [0, 99, 2, ..., 31] passed both and read row 1 instead of row 99. The host check also skipped any block starting with padding without looking at the rest of it. The host now checks every entry, once per command buffer since every attention layer reads the same lists; the kernel checks each lane's entries and takes a simdgroup vote. test-backend-ops gains the ends_only layout, which fails on both old paths. --- .../skippy-api/src/split-certified.json | 2 +- ...-every-row-list-entry-before-reading.patch | 239 ++++++++++++++++++ 2 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 skippy/llama_cpp/patches/0037-ggml-metal-check-every-row-list-entry-before-reading.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 83286254b3..650a7fabb2 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "f759075c7dff254bedaca46586f8df00f39dbadbe6d58fd7d1e4d33d79e3c13d" + "patch_queue_sha256": "decb74fc601fadf76b67f6b61c453ddaad16ecc8f6d0afea2e563b127c014467" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0037-ggml-metal-check-every-row-list-entry-before-reading.patch b/skippy/llama_cpp/patches/0037-ggml-metal-check-every-row-list-entry-before-reading.patch new file mode 100644 index 0000000000..16f03f7403 --- /dev/null +++ b/skippy/llama_cpp/patches/0037-ggml-metal-check-every-row-list-entry-before-reading.patch @@ -0,0 +1,239 @@ +From ed124dd46a2902d7d968e5f2c6c365407f31b9da Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Wed, 18 Nov 2026 20:04:35 +1100 +Subject: [PATCH 37/39] ggml-metal: check every row-list entry before reading a + block from the cache + +ggml_flash_attn_ext_rows accepts any row list. Two Metal paths decided from a +block's first and last entries alone that the block was one consecutive +range: the host check that compiles the gather-free variant, and the +per-block shortcut in the vec kernel. A valid block such as [0, 99, 2, ..., +31] passed both, and the kernel read row 1 instead of row 99. The host +check also passed any block that started with padding without looking at +the rest of it, though the gather-free kernel skips such a block whole. + +The host now checks every entry: a run of consecutive cells from the +block's first entry, then only padding, with a run ending inside its block +still read inside the cache. Every attention layer of a graph reads the same +lists, so each list is checked once per command buffer. In the kernel each +lane checks its entries of the block and the simdgroup votes. + +test-backend-ops gains the ends_only layout: consecutive blocks between +blocks whose ends are a block apart but whose interior holds a row from +elsewhere in the cache. It fails on the general kernel's old shortcut as +well as on the gather-free variant. +--- + ggml/src/ggml-metal/ggml-metal-ops.cpp | 74 ++++++++++++------- + .../ggml-metal/kernels/fa_vec_common.metal | 16 ++-- + tests/test-backend-ops.cpp | 17 ++++- + 3 files changed, 74 insertions(+), 33 deletions(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index 9309f9994..9e68f20d9 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -16,6 +16,7 @@ + #include + #include + #include ++#include + + // threadgroups needed to fill the GPU + // TODO: dedup +@@ -33,6 +34,27 @@ static ggml_metal_buffer_id ggml_metal_get_buffer_id(const ggml_tensor * t) { + return ggml_metal_buffer_get_id(ctx, t); + } + ++// The first C-entry block of the row lists that the gather-free vec kernel cannot read straight ++// from the cache, or -1. Such a block is one run of consecutive cells from its first entry, then ++// only padding; a block of only padding is skipped, and a run ending inside its block reads on ++// to the block's end, so that read must stay inside the cache. Every entry is checked: the row ++// list contract allows any order. ++static int64_t ggml_metal_rows_first_gathered_block(const int32_t * lists, int64_t n_entries, int64_t n_cache_rows) { ++ constexpr int64_t C = OP_FLASH_ATTN_EXT_VEC_NCPSG; ++ const auto padding = [](int32_t row) { return row < 0; }; ++ for (int64_t b = 0; b < n_entries/C; ++b) { ++ const int32_t * block = lists + b*C; ++ const int32_t * tail = std::find_if(block, block + C, padding); ++ const bool run = std::adjacent_find(block, tail, [](int32_t a, int32_t z) { return z != a + 1; }) == tail; ++ const bool padded = std::all_of(tail, block + C, padding); ++ const bool inside = tail == block || tail == block + C || block[0] + C <= n_cache_rows; ++ if (!run || !padded || !inside) { ++ return b; ++ } ++ } ++ return -1; ++} ++ + struct ggml_metal_op { + ggml_metal_op( + ggml_metal_device_t dev, +@@ -103,6 +125,21 @@ struct ggml_metal_op { + ggml_metal_fusion_info_count_fusion(finfo, fusion); + } + ++ // row lists do not change while a command buffer encodes, and the attention layers of a graph ++ // share them, so each list is checked once per command buffer rather than once per layer ++ int64_t rows_first_gathered_block(const ggml_tensor * rows, int64_t n_entries, int64_t n_cache_rows) { ++ const auto key = std::make_tuple(rows->data, n_entries, n_cache_rows); ++ const auto seen = std::find_if(rows_checked.begin(), rows_checked.end(), [&](const auto & checked) { ++ return checked.first == key; ++ }); ++ if (seen != rows_checked.end()) { ++ return seen->second; ++ } ++ const int64_t block = ggml_metal_rows_first_gathered_block((const int32_t *) rows->data, n_entries, n_cache_rows); ++ rows_checked.emplace_back(key, block); ++ return block; ++ } ++ + ggml_metal_device_t dev; + ggml_metal_library_t lib; + ggml_metal_encoder_t enc; +@@ -124,6 +161,8 @@ private: + + // non-empty node indices + std::vector idxs; ++ ++ std::vector, int64_t>> rows_checked; + }; + + ggml_metal_op_t ggml_metal_op_init( +@@ -3608,9 +3647,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); + + // the vec kernel compiles without gather code when every block of every list is one +- // consecutive range (possibly ending in padding) or all padding. a run ascends, so its ends +- // decide; the lists are readable from the host whenever their Metal buffer is shared or +- // mapped (every buffer type but private) ++ // consecutive range (possibly ending in padding) or all padding; the lists are readable from ++ // the host whenever their Metal buffer is shared or mapped (every buffer type but private) + // GGML_METAL_ROWS_DEBUG=1 reports, at exit, how often the gather-free variant was chosen and + // prints the first blocks that disqualified a list + static const bool rows_debug = getenv("GGML_METAL_ROWS_DEBUG") != nullptr; +@@ -3628,31 +3666,15 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { + const bool rows_dense = rows_shared && + [&] { + constexpr int64_t C = OP_FLASH_ATTN_EXT_VEC_NCPSG; +- const int32_t * lists = (const int32_t *) kv_rows->data; +- const int64_t n_blocks = (ne11_attn/C)*kv_rows->ne[1]; + const int64_t n_cache_rows = op->src[1]->ne[1]; +- for (int64_t b = 0; b < n_blocks; ++b) { +- const int32_t * block = lists + b*C; +- const int32_t first = block[0]; +- if (first < 0 || block[C - 1] == first + C - 1) { +- continue; // all padding (the kernel skips it), or one consecutive range +- } +- // a run ending inside the block: the kernel reads C rows from `first` and the mask +- // drops the padded columns, so the read must stay inside the cache +- const int32_t * tail = std::find(block, block + C, -1); +- const int64_t live = tail - block; +- if (tail == block + C || block[live - 1] != first + live - 1 || first + C > n_cache_rows || +- std::any_of(tail, block + C, [](int32_t row) { return row >= 0; })) { +- if (rows_debug && rows_dense_misses.load() < 4) { +- GGML_LOG_INFO("rows attention: general kernel: list %lld block %lld of %lld: first %d last %d live %lld [%d..%d] cache rows %lld\n", +- (long long) (b/(ne11_attn/C)), (long long) (b % (ne11_attn/C)), (long long) (ne11_attn/C), +- first, block[C - 1], (long long) live, block[std::max(live - 1, 0)], tail < block + C ? *tail : -2, +- (long long) n_cache_rows); +- } +- return false; +- } ++ const int64_t b = ctx->rows_first_gathered_block(kv_rows, ne11_attn*kv_rows->ne[1], n_cache_rows); ++ if (b >= 0 && rows_debug && rows_dense_misses.load() < 4) { ++ const int32_t * block = (const int32_t *) kv_rows->data + b*C; ++ GGML_LOG_INFO("rows attention: general kernel: list %lld block %lld of %lld: [%d %d .. %d %d] cache rows %lld\n", ++ (long long) (b/(ne11_attn/C)), (long long) (b % (ne11_attn/C)), (long long) (ne11_attn/C), ++ block[0], block[1], block[C - 2], block[C - 1], (long long) n_cache_rows); + } +- return true; ++ return b < 0; + }(); + if (rows_shared) { + (rows_dense ? rows_dense_hits : rows_dense_misses)++; +diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +index dfc35bae4..4da7bc07b 100644 +--- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal ++++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal +@@ -235,9 +235,9 @@ kernel void kernel_flash_attn_ext_vec( + } + + // a block whose row list is consecutive reads K/V like the dense path, from its first row; +- // only a block with gaps or padding gathers row by row. the lists are strictly ascending +- // (llama_kv_cells::get_seq_cells), so a block is consecutive iff its ends are C-1 apart: +- // two uniform loads decide it, without staging the indices ++ // only a block with gaps or padding gathers row by row. matching ends do not make a block ++ // consecutive, since a row list may hold any rows in any order: each lane checks its ++ // entries and the simdgroup votes + int rows_base = -1; + if (FC_flash_attn_ext_vec_has_rows) { + if (FC_flash_attn_ext_vec_rows_dense) { +@@ -249,9 +249,15 @@ kernel void kernel_flash_attn_ext_vec( + } + } else { + const int first = rows_list[ic]; +- const int last = rows_list[ic + C - 1]; + +- rows_base = (first >= 0 && last == first + C - 1) ? first : -1; ++ bool consecutive = first >= 0; ++ FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { ++ const short i = ii*NW + tiisg; ++ ++ consecutive = consecutive && rows_list[ic + i] == first + i; ++ } ++ ++ rows_base = simd_all(consecutive) ? first : -1; + } + } + +diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp +index 2420beb25..380ac8cd0 100644 +--- a/tests/test-backend-ops.cpp ++++ b/tests/test-backend-ops.cpp +@@ -9252,6 +9252,10 @@ struct test_flash_attn_ext_kv_rows_runs : public test_flash_attn_ext_kv_rows { + LAYOUT_RUN_AT_CACHE_END, + // consecutive blocks and scattered blocks in the same list + LAYOUT_MIXED, ++ // blocks whose first and last entries are a block apart with one interior entry ++ // elsewhere in the cache, between consecutive blocks: matching ends do not make a ++ // block consecutive ++ LAYOUT_ENDS_ONLY, + }; + + const layout_t layout; +@@ -9259,7 +9263,7 @@ struct test_flash_attn_ext_kv_rows_runs : public test_flash_attn_ext_kv_rows { + static const int64_t block = 32; + + std::string vars() override { +- static const char * const names[] = { "consecutive", "runs_padded", "run_at_cache_end", "mixed" }; ++ static const char * const names[] = { "consecutive", "runs_padded", "run_at_cache_end", "mixed", "ends_only" }; + return test_flash_attn_ext_kv_rows::vars() + ",layout=" + names[layout]; + } + +@@ -9316,6 +9320,14 @@ struct test_flash_attn_ext_kv_rows_runs : public test_flash_attn_ext_kv_rows { + } + } + } break; ++ case LAYOUT_ENDS_ONLY: { ++ for (int64_t b = 0; b < kv/block; ++b) { ++ put_run(s, b*block, b*block, block); ++ if (b % 2 == 1) { ++ rows[s*kv + b*block + 1 + b % (block - 2)] = (int32_t) (n_cells - 1 - b); ++ } ++ } ++ } break; + } + } + } +@@ -13126,7 +13138,8 @@ static std::vector> make_test_cases_eval() { + for (auto layout : { test_flash_attn_ext_kv_rows_runs::LAYOUT_CONSECUTIVE, + test_flash_attn_ext_kv_rows_runs::LAYOUT_RUNS_PADDED, + test_flash_attn_ext_kv_rows_runs::LAYOUT_RUN_AT_CACHE_END, +- test_flash_attn_ext_kv_rows_runs::LAYOUT_MIXED }) { ++ test_flash_attn_ext_kv_rows_runs::LAYOUT_MIXED, ++ test_flash_attn_ext_kv_rows_runs::LAYOUT_ENDS_ONLY }) { + for (int64_t nb : {1, 4, 64}) { + for (int64_t n_slices : {1, 4}) { + test_cases.emplace_back(new test_flash_attn_ext_kv_rows_runs(layout, 128, 8, 4, 4096, 512, nb, n_slices)); +-- +2.43.0 + From 275f71eb9c6b026e70a186a5fafe9bc246cd7821 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:39 +1100 Subject: [PATCH 60/81] fix(skippy): keep a task pool helper within the limit of the run it serves Queue patch 0038. A helper that woke for a wide run could claim tasks of a narrower run that started after it woke, past that run's sample_threads limit. A helper now checks the limit of the run in progress on every claim. test-skippy-task-pool alternates wide and one-helper runs and checks that the narrow runs never have two helpers at once. --- .../skippy-api/src/split-certified.json | 2 +- ...takes-a-run-s-tasks-only-while-that-.patch | 137 ++++++++++++++++++ 2 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 skippy/llama_cpp/patches/0038-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 650a7fabb2..58afecac8d 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "decb74fc601fadf76b67f6b61c453ddaad16ecc8f6d0afea2e563b127c014467" + "patch_queue_sha256": "6e5a0905da2b9de6045d80c111ac56883bb14d5839229d1d3a5327f90c56dde7" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0038-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch b/skippy/llama_cpp/patches/0038-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch new file mode 100644 index 0000000000..1de0ef0f6a --- /dev/null +++ b/skippy/llama_cpp/patches/0038-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch @@ -0,0 +1,137 @@ +From 64b7766d9ed5c8d133f3762cd6c6fe140bb21a74 Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Wed, 18 Nov 2026 20:05:26 +1100 +Subject: [PATCH 38/39] skippy: a helper takes a run's tasks only while that + run admits it + +A helper woke when its ordinal was below the run's helper limit, released +the lock, then took the lock again to claim tasks without checking the +limit. If the caller finished that run and started a narrower one in +between, the late helper claimed the new run's tasks past its +sample_threads limit. + +work() now checks the limit of the run in progress on every claim. The +calling thread is always admitted; a helper that is not goes back to wait. + +test-skippy-task-pool alternates wide runs of trivial tasks with +one-helper runs and checks that no more than one helper ever runs a task of +the narrow runs at once. It is a stress test: the old interleaving is +likely, not certain, to occur in one pass. +--- + src/skippy/task_pool.cpp | 13 +++++++------ + src/skippy/task_pool.h | 4 +++- + tests/test-skippy-task-pool.cpp | 25 +++++++++++++++++++++++++ + 3 files changed, 35 insertions(+), 7 deletions(-) + +diff --git a/src/skippy/task_pool.cpp b/src/skippy/task_pool.cpp +index 88f8d3b59..c1e1bf517 100644 +--- a/src/skippy/task_pool.cpp ++++ b/src/skippy/task_pool.cpp +@@ -50,7 +50,7 @@ void skippy_task_pool::run(size_t n, const task_fn & fn, size_t max_helpers) { + failure = nullptr; + } + wake.notify_all(); +- work(false); ++ work(std::nullopt); + + std::unique_lock lock(mutex); + idle.wait(lock, [this] { return pending == 0; }); +@@ -60,16 +60,17 @@ void skippy_task_pool::run(size_t n, const task_fn & fn, size_t max_helpers) { + } + } + +-// Takes indices until none are left. +-void skippy_task_pool::work(bool on_helper) { ++// Takes indices until none are left. A helper may have woken for an earlier, wider run, so it ++// takes each index only while the run in progress still admits it. ++void skippy_task_pool::work(std::optional helper) { + std::unique_lock lock(mutex); +- while (task != nullptr && next < count) { ++ while (task != nullptr && next < count && (!helper || *helper < allowed)) { + const size_t index = next++; + const task_fn * fn = task; + lock.unlock(); + std::exception_ptr thrown; + try { +- (*fn)(index, on_helper); ++ (*fn)(index, helper.has_value()); + } catch (...) { + thrown = std::current_exception(); + } +@@ -91,7 +92,7 @@ void skippy_task_pool::serve(size_t ordinal) { + return; + } + lock.unlock(); +- work(true); ++ work(ordinal); + lock.lock(); + } + } +diff --git a/src/skippy/task_pool.h b/src/skippy/task_pool.h +index e33523ea7..efc147f01 100644 +--- a/src/skippy/task_pool.h ++++ b/src/skippy/task_pool.h +@@ -9,6 +9,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -40,7 +41,8 @@ class skippy_task_pool { + void run(size_t count, const task_fn & task, size_t max_helpers); + + private: +- void work(bool on_helper); ++ // helper: the pool thread's ordinal; none for the thread that called run() ++ void work(std::optional helper); + void serve(size_t ordinal); + + const size_t limit; +diff --git a/tests/test-skippy-task-pool.cpp b/tests/test-skippy-task-pool.cpp +index e9b9284e0..677658b96 100644 +--- a/tests/test-skippy-task-pool.cpp ++++ b/tests/test-skippy-task-pool.cpp +@@ -136,6 +136,30 @@ static void the_pool_grows_to_demand_and_honours_each_runs_limit() { + }); + } + ++// A helper woken for a wide run can reach the task list after a narrower run has started; it ++// must not take that run's tasks past the narrower limit. ++static void a_helper_woken_for_a_wider_run_respects_the_next_runs_limit() { ++ skippy_task_pool pool(6); ++ std::atomic on_helpers_now { 0 }; ++ std::atomic most_on_helpers { 0 }; ++ std::vector rounds(2000); ++ std::for_each(rounds.begin(), rounds.end(), [&](int) { ++ pool.run(7, [](size_t, bool) {}, 6); ++ pool.run(16, [&](size_t, bool on_helper) { ++ if (!on_helper) { ++ return; ++ } ++ const int now = ++on_helpers_now; ++ int before = most_on_helpers.load(); ++ while (now > before && !most_on_helpers.compare_exchange_weak(before, now)) { ++ } ++ std::this_thread::yield(); ++ --on_helpers_now; ++ }, 1); ++ }); ++ CHECK(most_on_helpers <= 1); ++} ++ + static void sample_threads_select_the_executor() { + const auto name_of = [](uint32_t sample_threads) { + return std::string(skippy_with_sample_executor(sample_threads, +@@ -162,6 +186,7 @@ int main() { + an_exception_reaches_the_caller_and_the_pool_keeps_working(); + callers_on_different_threads_take_turns(); + the_pool_grows_to_demand_and_honours_each_runs_limit(); ++ a_helper_woken_for_a_wider_run_respects_the_next_runs_limit(); + sample_threads_select_the_executor(); + CHECK(skippy_task_pool::shared().helpers() <= skippy_task_pool::shared().ceiling()); + if (failures == 0) { +-- +2.43.0 + From 12de9ddf0fb6f9294c2d0c935f7a5e15812795c9 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:40 +1100 Subject: [PATCH 61/81] fix(skippy): apply the KV memory opt-outs to MSA, DSA-ISWA and DeepSeek V4 caches Queue patch 0039. kv_lazy_clear=false and kv_release_pages=false reached plain, ISWA, hybrid and DSA memories only. MSA, DSA-ISWA and DeepSeek V4 memories own llama_kv_cache children that zero lazily and release pages by default, and the traversal returned none of them, so the opt-outs never reached those caches. --- .../skippy-api/src/split-certified.json | 2 +- ...-KV-memory-options-to-every-attentio.patch | 60 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 skippy/llama_cpp/patches/0039-skippy-apply-the-KV-memory-options-to-every-attentio.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 58afecac8d..7706b3ad1b 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "6e5a0905da2b9de6045d80c111ac56883bb14d5839229d1d3a5327f90c56dde7" + "patch_queue_sha256": "5659eb387c80f91a21a0760103817ec959a8cc98c531e69110e03e2a93c7d21d" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0039-skippy-apply-the-KV-memory-options-to-every-attentio.patch b/skippy/llama_cpp/patches/0039-skippy-apply-the-KV-memory-options-to-every-attentio.patch new file mode 100644 index 0000000000..76a48f781c --- /dev/null +++ b/skippy/llama_cpp/patches/0039-skippy-apply-the-KV-memory-options-to-every-attentio.patch @@ -0,0 +1,60 @@ +From 054fb8ca66283302bee704b8f3d114ec17a75b6f Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Wed, 18 Nov 2026 20:05:54 +1100 +Subject: [PATCH 39/39] skippy: apply the KV memory options to every attention + cache a memory owns + +kv_lazy_clear=false and kv_release_pages=false reached plain, ISWA, hybrid +and DSA memories only. MSA, DSA-ISWA and DeepSeek V4 memories derive from +llama_memory_i directly and own llama_kv_cache children that zero lazily and +release pages by default, so the opt-outs never reached them. + +The traversal now also returns MSA's base and indexer caches, DSA-ISWA's +DSA pair and sliding-window cache, and DeepSeek V4's raw ISWA pair and its +CSA, HCA and indexer caches. +--- + src/skippy/state_memory.cpp | 17 ++++++++++++++++- + 1 file changed, 16 insertions(+), 1 deletion(-) + +diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp +index c62b1e629..a8a3757ca 100644 +--- a/src/skippy/state_memory.cpp ++++ b/src/skippy/state_memory.cpp +@@ -5,6 +5,9 @@ + #include "llama-kv-cache.h" + #include "llama-kv-cache-iswa.h" + #include "llama-kv-cache-dsa.h" ++#include "llama-kv-cache-dsa-iswa.h" ++#include "llama-kv-cache-dsv4.h" ++#include "llama-kv-cache-msa.h" + #include "llama-memory-hybrid.h" + #include "llama-memory-hybrid-iswa.h" + #include "llama-memory-recurrent.h" +@@ -27,11 +30,23 @@ llama_kv_cache * skippy_memory_kv_adapter(llama_memory_t memory) { + return nullptr; + } + +-// Every attention cache a memory owns, composite memories included. ++// Every attention cache a memory owns, composite memories included; entries may be null. + static std::vector skippy_memory_attention_caches(llama_memory_t memory) { + if (auto * dsa = dynamic_cast(memory)) { + return { dsa->get_mla(), dsa->get_lid() }; + } ++ if (auto * dsa_iswa = dynamic_cast(memory)) { ++ auto * dsa = dsa_iswa->get_dsa(); ++ return { dsa ? dsa->get_mla() : nullptr, dsa ? dsa->get_lid() : nullptr, dsa_iswa->get_swa() }; ++ } ++ if (auto * msa = dynamic_cast(memory)) { ++ return { msa->get_base(), msa->get_idx() }; ++ } ++ if (auto * dsv4 = dynamic_cast(memory)) { ++ auto * raw = dsv4->get_raw(); ++ return { raw ? raw->get_base() : nullptr, raw ? raw->get_swa() : nullptr, ++ dsv4->get_csa(), dsv4->get_hca(), dsv4->get_lid() }; ++ } + if (auto * iswa = skippy_memory_iswa_adapter(memory)) { + return { iswa->get_base(), iswa->get_swa() }; + } +-- +2.43.0 + From 89c4a2126b8b543bcd0445f977a0e05314e516fc Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:40 +1100 Subject: [PATCH 62/81] fix(skippy): end process tracing when the host exits, not when a model unloads Shutting down one model's runtime ended the process span, stopped the process-wide resource sampler and sent every later span down the synchronous late-shutdown path, though the host and its other models kept serving. A model's shutdown now only flushes its own queued spans. The first telemetry handle with a sink is kept for the process, as the resource sampler already keeps one, and finish_process_telemetry() ends the process span through it. Mesh calls it after its models shut down, in both the full runtime and the model-only path, and so does skippy serve. --- .../src/runtime/control_loop.rs | 1 + .../src/runtime/local_model_only.rs | 1 + skippy/crates/skippy-cli/src/main.rs | 6 ++++- skippy/crates/skippy-serving/src/embedded.rs | 5 +++- skippy/crates/skippy-serving/src/telemetry.rs | 27 ++++++++++++++++--- 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/control_loop.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/control_loop.rs index 8abbc3b15e..c1d840983a 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/control_loop.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/control_loop.rs @@ -397,6 +397,7 @@ pub(super) async fn shutdown_run_auto_runtime(ctx: RunAutoShutdownContext<'_>) { ) .await; shutdown_runtime_managed_models(managed_models).await; + skippy_serving::telemetry::finish_process_telemetry(); node.set_serving_models(Vec::new()).await; node.set_hosted_models(Vec::new()).await; diff --git a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs index 75d7f1eb53..b9f89a5812 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/runtime/local_model_only.rs @@ -408,6 +408,7 @@ async fn run_loaded_local_model( super::node_lifecycle_events::emit_node_draining(); emit_shutdown(Some(reason)).await; model.shutdown().await; + skippy_serving::telemetry::finish_process_telemetry(); super::node_lifecycle_events::emit_node_stopped(); // Task 3: finalize AFTER node_stopped, same ordering rationale as // `control_loop.rs::shutdown_run_auto_runtime` -- the driver's own diff --git a/skippy/crates/skippy-cli/src/main.rs b/skippy/crates/skippy-cli/src/main.rs index 82d88a034c..9c9bbdf58b 100644 --- a/skippy/crates/skippy-cli/src/main.rs +++ b/skippy/crates/skippy-cli/src/main.rs @@ -144,7 +144,11 @@ async fn run_main( }) .await? } - Command::Serve(args) => serve::run(*args).await, + Command::Serve(args) => { + let served = serve::run(*args).await; + skippy_serving::telemetry::finish_process_telemetry(); + served + } Command::Models { command } => skippy_commands::models::run_standalone(&command).await, Command::PlanSplit(args) => skippy_commands::split::run(args.into()), Command::Runtime { command } => { diff --git a/skippy/crates/skippy-serving/src/embedded.rs b/skippy/crates/skippy-serving/src/embedded.rs index b7b2d97cef..9175e65419 100644 --- a/skippy/crates/skippy-serving/src/embedded.rs +++ b/skippy/crates/skippy-serving/src/embedded.rs @@ -356,6 +356,9 @@ impl SkippyRuntimeHandle { } } + /// Stop this model's runtime. The host and its other models keep the + /// process trace; the host ends it with + /// [`crate::telemetry::finish_process_telemetry`] when it exits. pub fn shutdown(&self) { self.tokenizer_active.store(false, Ordering::Release); let runtime = lock_runtime(&self.runtime); @@ -370,7 +373,7 @@ impl SkippyRuntimeHandle { "stage.embedded_runtime_stopped", lifecycle_attrs(&self.config), ); - self.telemetry.finish_process(); + self.telemetry.flush_queued(); } } diff --git a/skippy/crates/skippy-serving/src/telemetry.rs b/skippy/crates/skippy-serving/src/telemetry.rs index 7a6e65f12e..0529090e5b 100644 --- a/skippy/crates/skippy-serving/src/telemetry.rs +++ b/skippy/crates/skippy-serving/src/telemetry.rs @@ -3,7 +3,7 @@ use std::sync::mpsc as std_mpsc; use std::{ collections::BTreeMap, sync::{ - Arc, + Arc, OnceLock, atomic::{AtomicU64, Ordering}, }, time::{Duration, SystemTime, UNIX_EPOCH}, @@ -106,6 +106,18 @@ pub struct TelemetryStats { /// What every sink keeps for one live span, in sink order. pub(crate) struct OpenSpans(Vec); +/// The first handle with a sink, which ends the process span when the host +/// exits. Like the resource sampler's, it outlives the stage it came from. +static PROCESS_TELEMETRY: OnceLock = OnceLock::new(); + +/// End the process span and stop the resource sampler. The host calls this +/// once, as it exits; unloading a model leaves both running for the others. +pub fn finish_process_telemetry() { + if let Some(telemetry) = PROCESS_TELEMETRY.get() { + telemetry.finish_process(); + } +} + impl Telemetry { pub fn new( endpoint: Option, @@ -164,6 +176,9 @@ impl Telemetry { .flatten() .collect(); let telemetry = Self::with_sinks(sinks, stats, config, level); + if level != TelemetryLevel::Off && telemetry.has_sink() { + let _ = PROCESS_TELEMETRY.set(telemetry.clone()); + } log_events::start(&telemetry, metrics_endpoint.as_deref()); if telemetry.is_debug_enabled() && telemetry.has_sink() { native_calls::install(&telemetry); @@ -368,8 +383,14 @@ impl Telemetry { } } - /// End the process span and flush queued spans. Shutdown calls this; only - /// the first call in the process does anything. + /// Flush this handle's queued spans. Unloading a model calls this; the + /// process span and the resource sampler keep running for the host. + pub(crate) fn flush_queued(&self) { + self.flush(FLUSH_TIMEOUT); + } + + /// End the process span and flush queued spans. Only the first call in + /// the process does anything; hosts call [`finish_process_telemetry`]. pub fn finish_process(&self) { let process = trace_context::process(); if self.level == TelemetryLevel::Off || !process.begin_finish() { From aa4bb28adf5253e7c3ba6ad4428d5f7ba932acee Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:40 +1100 Subject: [PATCH 63/81] fix(skippy): report native checkpoint bytes against the checkpoint budget The L1 recurrent-bytes gauge read the radix's serialized exact-state counter. Stages that record resident prefixes keep their native recurrent checkpoints as resident entries, whose bytes the checkpoint budget is charged against, so the gauge read zero while that budget filled. The tier source now records which radix component owns the stage's checkpoints and reads that component's bytes; a test covers a resident native checkpoint. --- .../src/kv_integration/tier_metrics.rs | 80 ++++++++++++++++++- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs index 326296918c..3251ab025f 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/tier_metrics.rs @@ -18,8 +18,37 @@ use crate::telemetry::resource_metrics::kv_tiers::{ type Radix = Mutex>; +/// The radix component that holds this stage's recurrent checkpoints, and so +/// the byte count its checkpoint budget is charged against. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CheckpointOwner { + /// Native checkpoints recorded with resident prefixes: their bytes are + /// the resident entries'. + Resident, + /// Serialized exact-state entries. + ExactState, +} + +impl CheckpointOwner { + fn of(integration: &KvStageIntegration) -> Self { + if integration.records_resident_prefixes() { + Self::Resident + } else { + Self::ExactState + } + } + + fn bytes(self, stats: &UnifiedRadixCacheStats) -> u64 { + match self { + Self::Resident => stats.resident_logical_bytes, + Self::ExactState => stats.recurrent_logical_bytes, + } + } +} + struct StageTierSource { radix: Weak, + checkpoints: CheckpointOwner, recurrent_limit_bytes: u64, l2: Option>, l3: Option>, @@ -34,6 +63,7 @@ struct StageTierSource { pub(super) fn register(integration: &KvStageIntegration) { kv_tiers::register(Box::new(StageTierSource { radix: Arc::downgrade(&integration.radix), + checkpoints: CheckpointOwner::of(integration), recurrent_limit_bytes: integration.resident_checkpoint_max_bytes, l2: integration.l2.as_ref().map(|l2| Arc::downgrade(l2.tier())), l3: integration.l3.as_ref().map(Arc::downgrade), @@ -126,7 +156,7 @@ impl StageTierSource { fn l1(&self, radix: &Radix) -> L1Reading { let mut last = self.last_l1.lock().unwrap_or_else(PoisonError::into_inner); if let Ok(radix) = radix.try_lock() { - *last = l1(&radix.stats(), self.recurrent_limit_bytes); + *last = l1(&radix.stats(), self.checkpoints, self.recurrent_limit_bytes); } *last } @@ -138,12 +168,16 @@ fn load(counter: &Weak) -> u64 { .map_or(0, |counter| counter.load(Ordering::Relaxed)) } -fn l1(stats: &UnifiedRadixCacheStats, recurrent_limit_bytes: u64) -> L1Reading { +fn l1( + stats: &UnifiedRadixCacheStats, + checkpoints: CheckpointOwner, + recurrent_limit_bytes: u64, +) -> L1Reading { L1Reading { entries: stats.resident_entries as u64, tokens: stats.resident_tokens, pinned_tokens: stats.resident_pinned_tokens, - recurrent_bytes: stats.recurrent_logical_bytes, + recurrent_bytes: checkpoints.bytes(stats), recurrent_limit_bytes, attention_evictions: stats.resident_evictions, recurrent_evictions: stats.recurrent_evictions, @@ -200,7 +234,7 @@ mod tests { recurrent_evictions: 1, ..UnifiedRadixCacheStats::default() }; - let reading = l1(&stats, 4096); + let reading = l1(&stats, CheckpointOwner::ExactState, 4096); assert_eq!( reading, L1Reading { @@ -215,11 +249,49 @@ mod tests { ); } + #[test] + fn a_native_checkpoint_counts_against_the_checkpoint_budget() { + let radix: Arc = Arc::new(Mutex::new(UnifiedRadixCache::new())); + radix + .lock() + .expect("radix lock") + .insert_resident( + "model", + &[1, 2, 3], + 3072, + RadixResidentEntry { + page_id: "0".to_string(), + seq_id: 0, + token_count: 3, + recompute_cost: 1, + }, + ) + .expect("resident checkpoint"); + let source = StageTierSource { + radix: Arc::downgrade(&radix), + checkpoints: CheckpointOwner::Resident, + recurrent_limit_bytes: 4096, + l2: None, + l3: None, + records_pending: Weak::new(), + record_queue_bytes: Weak::new(), + records_dropped: Weak::new(), + last_l1: Mutex::new(L1Reading::default()), + }; + let reading = source.read().expect("live stage").l1; + assert_eq!( + (reading.recurrent_bytes, reading.recurrent_limit_bytes), + (3072, 4096) + ); + assert_eq!(reading.entries, 1); + } + #[test] fn a_dropped_stage_stops_reporting_and_a_held_lock_reuses_the_last_reading() { let radix: Arc = Arc::new(Mutex::new(UnifiedRadixCache::new())); let source = StageTierSource { radix: Arc::downgrade(&radix), + checkpoints: CheckpointOwner::ExactState, recurrent_limit_bytes: 64, l2: None, l3: None, From 470e81c79fd4448ec6d707f7d46d14cb8908b5fa Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:40 +1100 Subject: [PATCH 64/81] fix(skippy): release a discarded span's Tracy lane Discarding a span closed its Tracy zone but left its id in the lane map; only a span that ended released it. The scheduler discards empty iteration spans routinely, so a Tracy-enabled server grew the map for the life of the process. The open state now keeps the span's id and name, and ending and discarding both release them. --- .../src/telemetry/tracy_sink.rs | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs b/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs index 07437d908b..d1472f26cf 100644 --- a/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs +++ b/skippy/crates/skippy-serving/src/telemetry/tracy_sink.rs @@ -128,10 +128,13 @@ impl Lanes { } } -/// What the sink keeps while a span is live. +/// What the sink keeps while a span is live, including the identity its +/// lane is mapped by, which ending and discarding both release. struct Open { zone: sys::___tracy_c_zone_context, lane: Lane, + span_id: [u8; 8], + name: &'static str, } pub(super) struct TracySink { @@ -210,7 +213,7 @@ impl TracySink { } Self::zone_end(open.zone); }); - self.lanes().release(span.context.span_id, &span.name); + self.lanes().release(open.span_id, open.name); } fn plot(&self, name: &str, value: f64) { @@ -250,7 +253,14 @@ impl TraceSink for TracySink { let lane = self.lanes().assign(span); let mut zone = None; lane.resume(|| zone = Some(Self::zone_begin(span.name))); - zone.map_or(OpenSpan::NONE, |zone| OpenSpan::keep(Open { zone, lane })) + zone.map_or(OpenSpan::NONE, |zone| { + OpenSpan::keep(Open { + zone, + lane, + span_id: span.context.span_id, + name: span.name, + }) + }) } fn end_span(&self, open: OpenSpan, span: &SpanRecord) { @@ -263,6 +273,7 @@ impl TraceSink for TracySink { fn discard_span(&self, open: OpenSpan) { if let Some(open) = open.take::() { open.lane.resume(|| Self::zone_end(open.zone)); + self.lanes().release(open.span_id, open.name); } } @@ -403,6 +414,16 @@ mod tests { assert_eq!(lanes.requests_made, 1); } + #[test] + fn a_discarded_span_releases_its_lane() { + let sink = TracySink::start(); + let open = sink.create_span_with(&start(REQUEST_ROOT, 9, None)); + sink.discard_span(open); + let lanes = sink.lanes(); + assert!(lanes.by_span.is_empty()); + assert_eq!(lanes.free_requests.len(), 1); + } + #[test] fn two_live_requests_take_two_lanes() { let mut lanes = Lanes::default(); From 837cb733ea8e0ff0a61a191c35c6ebf71e1c533d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:40 +1100 Subject: [PATCH 65/81] fix(skippy): read the current row-list attention layout in the KV matrix The real-model KV matrix required both src[5] and src[6] on every flash attention node. Row-list attention uses src[5] for the per-request lists and leaves src[6] null, so every healthy graph failed before its K/V pairs were checked. The matrix now requires src[6] to be null, accepts attention with or without a row list, and reports which one ran. --- .../kv-validation/native/indexed-real-kv-matrix.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp index 6537737b5c..16113d9d57 100644 --- a/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp +++ b/skippy/evals/kv-validation/native/indexed-real-kv-matrix.cpp @@ -43,14 +43,20 @@ int inspect(llama_context * ctx, ggml_type type_k, ggml_type type_v, const auto backend = ggml_backend_sched_get_tensor_backend(ctx->get_sched(), node); require(backend && std::strcmp(ggml_backend_name(backend), expected_backend) == 0, "real attention executed on the wrong backend"); - require(node->src[5] && node->src[6], "real flash attention missing request indices/lengths"); + // src[5] is the per-request row list, absent where attention reads the cache directly + const auto rows = node->src[5]; + require(node->src[6] == nullptr, "real flash attention carries an unexpected source"); + require(!rows || (rows->type == GGML_TYPE_I32 && rows->ne[1] == node->src[0]->ne[3]), + "real flash attention row list is not one I32 list per request"); require(node->src[1]->type == type_k && node->src[2]->type == type_v, "actual K/V dtype changed"); ++attention; if (step == 0 && attention == 1) { - std::printf("REAL_FA backend=%s K=%s V=%s q=%lld physical=%lld logical=%lld requests=%lld\n", + std::printf("REAL_FA backend=%s K=%s V=%s q=%lld physical=%lld rows=%s logical=%lld requests=%lld\n", ggml_backend_name(backend), ggml_type_name(type_k), ggml_type_name(type_v), (long long) node->src[0]->ne[1], (long long) node->src[1]->ne[1], - (long long) node->src[5]->ne[0], (long long) node->src[5]->ne[3]); + rows ? "list" : "direct", + (long long) (rows ? rows->ne[0] : node->src[1]->ne[1]), + (long long) node->src[0]->ne[3]); } } require(attention > 0, "no real flash attention operations"); From 76a06e59586097f6b4d5d206b0c43f55f4572079 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:11:41 +1100 Subject: [PATCH 66/81] docs(skippy): move the KV validation plan beside its README The reusable KV validation checklist sat at the repository root as todo.md. It now lives at skippy/evals/kv-validation/PLAN.md, next to the README that cites it, and the two documents that link to it point there. --- skippy/docs/design/INDEXED_ATTENTION_STATUS.md | 2 +- todo.md => skippy/evals/kv-validation/PLAN.md | 2 +- skippy/evals/kv-validation/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename todo.md => skippy/evals/kv-validation/PLAN.md (99%) diff --git a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md index d183db3fa8..7e4e4877b0 100644 --- a/skippy/docs/design/INDEXED_ATTENTION_STATUS.md +++ b/skippy/docs/design/INDEXED_ATTENTION_STATUS.md @@ -363,4 +363,4 @@ model, fixed-work, raw artifacts and GPU clock/temperature evidence are retained in the independent comparison receipts. The reusable four-model CUDA/Metal/CPU validation work is tracked in -[todo.md](../../../todo.md). +[PLAN.md](../../evals/kv-validation/PLAN.md). diff --git a/todo.md b/skippy/evals/kv-validation/PLAN.md similarity index 99% rename from todo.md rename to skippy/evals/kv-validation/PLAN.md index 159a31c33f..9d20c934b8 100644 --- a/todo.md +++ b/skippy/evals/kv-validation/PLAN.md @@ -30,7 +30,7 @@ identities, publish into existing MLflow experiment 6, and rewrite the AgentX PRs around the final implementation and source-pinned results. -The bounded [validation foundation](skippy/evals/kv-validation/README.md) now +The bounded [validation foundation](README.md) now provides explicit reusable commands. Complete the remaining cases below after the current cache and performance work. diff --git a/skippy/evals/kv-validation/README.md b/skippy/evals/kv-validation/README.md index 0c1f59e8a9..2bd09e7918 100644 --- a/skippy/evals/kv-validation/README.md +++ b/skippy/evals/kv-validation/README.md @@ -37,7 +37,7 @@ This foundation runs: Long c4 state comparisons, HTTP-server L3 restart, pressure, default-budget qualification and standard-vanilla performance comparisons remain separate work in -[todo.md](../../../todo.md). A green foundation is not throughput parity or full +[PLAN.md](PLAN.md). A green foundation is not throughput parity or full KV certification. There is no automatic GPU CI trigger or new serving option. ## Prepare once, run many From 1ec8152ea7461b30c7fa246e4f65f5fc4414adcb Mon Sep 17 00:00:00 2001 From: James Dumay Date: Thu, 19 Nov 2026 14:45:53 +1100 Subject: [PATCH 67/81] fix: defer unpinned Qwen performance suites --- ci/model-artifacts/README.md | 22 +++++----- ci/model-artifacts/registry.json | 23 +---------- .../src/frontend/generation/streaming.rs | 40 ++++++++++++------- .../local_generation/token_generation.rs | 2 +- .../token_generation/exact_state_recording.rs | 2 +- skippy/crates/skippy-serving/src/telemetry.rs | 21 +--------- .../src/telemetry/active_span.rs | 8 ++-- .../skippy-serving/src/telemetry/sink.rs | 4 +- 8 files changed, 50 insertions(+), 72 deletions(-) diff --git a/ci/model-artifacts/README.md b/ci/model-artifacts/README.md index fefae18da8..56f56828a5 100644 --- a/ci/model-artifacts/README.md +++ b/ci/model-artifacts/README.md @@ -6,11 +6,12 @@ to this contract. Every artifact records an immutable Hugging Face revision, its exact file set, byte sizes, SHA-256 digests, family capabilities, and the suites and cadences allowed to use it. -A suite built from models pinned elsewhere is declared, not typed in: -`derived_suites` names a pinned evals model list -(`skippy/evals/kv-validation/models.json`), the selectors to register it at -and an id prefix, and the generator refuses the registry until every derived -row exists, so a member cannot be forgotten. `cargo xtool models pin` with no +A suite built from models pinned elsewhere can be declared in `derived_suites`: +it names a pinned evals model list (`skippy/evals/kv-validation/models.json`), +the selectors to register it at and an id prefix. Keep that declaration out +until every derived artifact has an immutable source and integrity metadata; +once declared, the generator refuses the registry until every derived row +exists, so a member cannot be forgotten. `cargo xtool models pin` with no arguments registers exactly the missing rows: each file name is the list's with its selector suffix swapped (`Qwen3.5-4B-Q4_K_M.gguf` at `BF16` is `Qwen3.5-4B-BF16.gguf`), each id is `-` with the selector slug @@ -48,11 +49,12 @@ transfer and is held to the manifest's size and SHA-256; a file that already verifies is kept, one that does not is reported and left for the operator. `--dry-run` lists what would be fetched and how much, `--artifact-id` limits the fetch to one artifact, and `models resolve --artifact-id ---verify-root /` checks a fetched artifact afterwards. The -`performance-*` suites are the manual performance tiers: `performance-coverage` -pins one representative of each architecture class (dense, MoE, MLA, MXFP4, -sliding window, Mamba2, RWKV7, Granite hybrid, embedding, reranker) at the -same revision the family battery certifies. +--verify-root /` checks a fetched artifact afterwards. +`performance-coverage` is the manual performance tier, pinning one +representative of each architecture class (dense, MoE, MLA, MXFP4, sliding +window, Mamba2, RWKV7, Granite hybrid, embedding, reranker) at the same revision +the family battery certifies. Additional derived Qwen performance suites stay +undeclared until their complete artifact pins are available. Multi-artifact manifests may declare `default_artifact_id` for callers that intentionally consume the suite's canonical fixture without selecting an diff --git a/ci/model-artifacts/registry.json b/ci/model-artifacts/registry.json index adb4b73fda..846fb8ee49 100644 --- a/ci/model-artifacts/registry.json +++ b/ci/model-artifacts/registry.json @@ -25,9 +25,7 @@ "radix-cache", "skippy-system-one-smoke", "skippy-cpp-api", - "performance-coverage", - "performance-core", - "performance-parity" + "performance-coverage" ], "family_policy": { "profiles": { @@ -5570,24 +5568,5 @@ }, "notes": "Performance coverage: XLM-RoBERTa reranker; same pin as bge-reranker-q4-cpp-api." } - ], - "derived_suites": [ - { - "suite": "performance-core", - "from": "skippy/evals/kv-validation/models.json", - "selectors": [ - "Q4_K_M" - ], - "id_prefix": "perf" - }, - { - "suite": "performance-parity", - "from": "skippy/evals/kv-validation/models.json", - "selectors": [ - "Q8_0", - "BF16" - ], - "id_prefix": "perf" - } ] } diff --git a/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs b/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs index 1f47919f92..bcd2df8a9b 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/streaming.rs @@ -348,7 +348,7 @@ pub(in crate::frontend) struct TextGenerationCollector<'a, F> where F: FnMut(&str) -> InferenceResult<()>, { - model: StageModelReader, + model: Option, stop_values: Vec<&'a str>, on_text_chunk: F, text: String, @@ -377,6 +377,19 @@ where model: StageModelReader, stop_values: Vec<&'a str>, on_text_chunk: F, + ) -> InferenceResult { + Self::with_model(Some(model), stop_values, on_text_chunk) + } + + #[cfg(test)] + fn without_model(stop_values: Vec<&'a str>, on_text_chunk: F) -> InferenceResult { + Self::with_model(None, stop_values, on_text_chunk) + } + + fn with_model( + model: Option, + stop_values: Vec<&'a str>, + on_text_chunk: F, ) -> InferenceResult { let max_stop_bytes = stop_values .iter() @@ -417,13 +430,12 @@ where } pub(in crate::frontend) fn push_token(&mut self, token: i32) -> InferenceResult { + let model = self + .model + .as_ref() + .ok_or_else(|| InferenceError::backend("token decoding requires a loaded model"))?; let eog_timer = Instant::now(); - if !self.ignore_eos - && self - .model - .token_is_eog(token) - .map_err(openai_backend_error)? - { + if !self.ignore_eos && model.token_is_eog(token).map_err(openai_backend_error)? { self.metrics.eog_check_ms += eog_timer.elapsed().as_secs_f64() * 1000.0; self.finish_reason = finish_reason_for_generation(false); self.stopped = true; @@ -431,8 +443,7 @@ where } self.metrics.eog_check_ms += eog_timer.elapsed().as_secs_f64() * 1000.0; let detokenize_timer = Instant::now(); - let piece = self - .model + let piece = model .detokenize_bytes(&[token]) .map_err(openai_backend_error)?; self.metrics.detokenize_ms += detokenize_timer.elapsed().as_secs_f64() * 1000.0; @@ -566,9 +577,12 @@ where "recorded logprobs do not match the generated tokens", )); } + let model = self + .model + .as_ref() + .ok_or_else(|| InferenceError::backend("logprob decoding requires a loaded model"))?; let candidate = |token: i32, logprob: f32| -> InferenceResult { - let bytes = self - .model + let bytes = model .detokenize_bytes(&[token]) .map_err(openai_backend_error)?; Ok(GeneratedLogprobCandidate { @@ -618,9 +632,7 @@ mod tests { #[test] fn token_after_stop_sequence_does_not_bring_back_trimmed_text() { let chunks = std::cell::RefCell::new(Vec::::new()); - // No token here is detokenized, so the reader needs no loaded model. - let model = skippy_runtime::StageModel::new_dummy().reader(); - let mut collector = TextGenerationCollector::new(model, vec!["END"], |chunk| { + let mut collector = TextGenerationCollector::without_model(vec!["END"], |chunk| { chunks.borrow_mut().push(chunk.to_string()); Ok(()) }) diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index 8028a0c5b5..6fb931e876 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -981,12 +981,12 @@ impl StageOpenAiBackend { }, )?; cache_stats.predicted_ms = stats.predicted_ms; - drop(decoding); include_undelivered_samples( &mut state.decoded_tokens, &mut state.generated_token_ids, &stats.undelivered_tokens, ); + drop(decoding); let model_generation_elapsed = self.emit_decode_summary(request, &mut state, cache_stats, decode_timer)?; if state.generated_token_ids.len() > 1 { diff --git a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index 1db7edfeff..8f708ebfd8 100644 --- a/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/skippy/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -1,6 +1,6 @@ use super::*; -use crate::kv_integration::{ResidentPrefixRecord, ResidentRecordOutcome, ResidentRecordSkip}; use crate::kv_integration::SessionEndCapture; +use crate::kv_integration::{ResidentPrefixRecord, ResidentRecordOutcome, ResidentRecordSkip}; /// Owns one unit of the test-only outstanding-capture counter for a single /// detached capture task. Construction increments the counter, so the unit is diff --git a/skippy/crates/skippy-serving/src/telemetry.rs b/skippy/crates/skippy-serving/src/telemetry.rs index 0529090e5b..c95f567d85 100644 --- a/skippy/crates/skippy-serving/src/telemetry.rs +++ b/skippy/crates/skippy-serving/src/telemetry.rs @@ -233,26 +233,9 @@ impl Telemetry { } /// The live span `begin_span` saw ends: export it with its frame's events. - pub(crate) fn end_span( - &self, - open: OpenSpans, - frame: &Frame, - name: &str, - mut attributes: BTreeMap, - start_time_unix_nanos: u64, - end_time_unix_nanos: u64, - links: Vec, - ) { + pub(crate) fn end_span(&self, open: OpenSpans, frame: &Frame, mut record: SpanRecord) { let events = frame.take_events(); - self.add_common_attributes(&mut attributes); - let mut record = SpanRecord::of_frame( - frame, - name, - attributes, - start_time_unix_nanos, - end_time_unix_nanos, - ); - record.links = links; + self.add_common_attributes(&mut record.attributes); record.events = events; self.sinks .iter() diff --git a/skippy/crates/skippy-serving/src/telemetry/active_span.rs b/skippy/crates/skippy-serving/src/telemetry/active_span.rs index 8befb94670..e69a1facd0 100644 --- a/skippy/crates/skippy-serving/src/telemetry/active_span.rs +++ b/skippy/crates/skippy-serving/src/telemetry/active_span.rs @@ -11,7 +11,7 @@ use serde_json::Value; use super::{ OpenSpans, Telemetry, TelemetryLevel, now_unix_nanos, resource_metrics::SpanWindow, - sink::SpanStart, + sink::{SpanRecord, SpanStart}, trace_context::{self, Entered, Frame, SpanContext}, }; @@ -165,15 +165,15 @@ impl ActiveSpan { self.attributes.extend(window.close()); } let elapsed = u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX); - telemetry.end_span( - open, + let mut record = SpanRecord::of_frame( &self.frame, self.name, std::mem::take(&mut self.attributes), self.start_unix_nanos, self.start_unix_nanos.saturating_add(elapsed), - std::mem::take(&mut self.links), ); + record.links = std::mem::take(&mut self.links); + telemetry.end_span(open, &self.frame, record); } } diff --git a/skippy/crates/skippy-serving/src/telemetry/sink.rs b/skippy/crates/skippy-serving/src/telemetry/sink.rs index 25a3694d32..1e5c1f65a0 100644 --- a/skippy/crates/skippy-serving/src/telemetry/sink.rs +++ b/skippy/crates/skippy-serving/src/telemetry/sink.rs @@ -196,10 +196,12 @@ mod tests { assert_eq!(OpenSpan::NONE.take::(), None); } + type StartedSpanRecord = (&'static str, SpanLevel, SpanContext, Option<[u8; 8]>); + /// A sink that acts at both ends of a live span, as Tracy must. #[derive(Default)] struct Seen { - started: Mutex)>>, + started: Mutex>, ended: Mutex)>>, discarded: Mutex>>, } From 7f54431356be4912f130edf1c7b4d9c741dd4fe6 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:32:12 +1100 Subject: [PATCH 68/81] ci: declare the KV validation model list as a cache input and match main's Python source error - cache inventory: skippy/evals/kv-validation/models.json is compiled into xtask, so it joins the hosted xtask, Linux runtime and Windows ABI key inputs; workflow keys re-rendered with ci-ops cache-inputs render, and the Windows warmer watches it. - python tooling test: main reports an unlisted Python file as "unreviewed repository Python source" since the SDK moved in-tree. --- .github/actions/prepare-automation/action.yml | 2 +- .github/actions/restore-windows-abi-cache/action.yml | 2 +- .github/workflows/ci-linux-runtime-slice.yml | 2 +- .github/workflows/linux-cache-measurement.yml | 12 ++++++------ .github/workflows/windows-warm-caches.yml | 1 + tools/xtask/src/ci_operations/cache_inputs.rs | 2 ++ .../xtask/src/ci_validation/python_tooling/tests.rs | 2 +- 7 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.github/actions/prepare-automation/action.yml b/.github/actions/prepare-automation/action.yml index ec757ea6d2..301e0da1dd 100644 --- a/.github/actions/prepare-automation/action.yml +++ b/.github/actions/prepare-automation/action.yml @@ -165,7 +165,7 @@ runs: uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: target/release/xtask - key: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + key: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/evals/kv-validation/models.json', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} - name: Build automation tool id: bootstrap_unix diff --git a/.github/actions/restore-windows-abi-cache/action.yml b/.github/actions/restore-windows-abi-cache/action.yml index 683ae09819..aefff3c95a 100644 --- a/.github/actions/restore-windows-abi-cache/action.yml +++ b/.github/actions/restore-windows-abi-cache/action.yml @@ -60,7 +60,7 @@ runs: INPUT_CUDA_TOOLCHAIN_VERSION: ${{ inputs.cuda_toolchain_version }} INPUT_VULKAN_TOOLCHAIN_VERSION: ${{ inputs.vulkan_toolchain_version }} INPUT_ROCM_TOOLCHAIN_VERSION: ${{ inputs.rocm_toolchain_version }} - CACHE_INPUT_HASH: ${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/actions/restore-windows-abi-cache/action.yml', '.github/actions/save-and-verify-actions-cache/**', '.github/actions/setup-windows-rocm-sdk/**', '.github/cache-version.txt', '.github/workflows/ci-windows-runtime-slice.yml', '.github/workflows/release.yml', '.github/workflows/windows-warm-caches.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**', 'tools/xtask/src/native_policy/**', 'tools/xtask/src/prepared_input/**') }} + CACHE_INPUT_HASH: ${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/actions/restore-windows-abi-cache/action.yml', '.github/actions/save-and-verify-actions-cache/**', '.github/actions/setup-windows-rocm-sdk/**', '.github/cache-version.txt', '.github/workflows/ci-windows-runtime-slice.yml', '.github/workflows/release.yml', '.github/workflows/windows-warm-caches.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/evals/kv-validation/models.json', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**', 'tools/xtask/src/native_policy/**', 'tools/xtask/src/prepared_input/**') }} run: | $ErrorActionPreference = "Stop" diff --git a/.github/workflows/ci-linux-runtime-slice.yml b/.github/workflows/ci-linux-runtime-slice.yml index ee7b68ac80..7848bc2a84 100644 --- a/.github/workflows/ci-linux-runtime-slice.yml +++ b/.github/workflows/ci-linux-runtime-slice.yml @@ -219,7 +219,7 @@ jobs: uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: runtime-input - key: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + key: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/evals/kv-validation/models.json', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} - name: Verify restored Linux CPU runtime id: cached_runtime if: ${{ steps.runtime_cache.outputs.cache-hit == 'true' }} diff --git a/.github/workflows/linux-cache-measurement.yml b/.github/workflows/linux-cache-measurement.yml index 4e65b311ee..d091d72883 100644 --- a/.github/workflows/linux-cache-measurement.yml +++ b/.github/workflows/linux-cache-measurement.yml @@ -126,7 +126,7 @@ jobs: allow_native_github_cache: "false" - name: Record computed key before any edit env: - CACHE_KEY: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + CACHE_KEY: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/evals/kv-validation/models.json', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement key --receipt-dir "$RECEIPT_DIR" --cohort cpu-runtime --phase before - name: Apply the admitted unrelated edit @@ -135,7 +135,7 @@ jobs: "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement edit --receipt-dir "$RECEIPT_DIR" --cohort cpu-runtime - name: Record measured key env: - CACHE_KEY: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + CACHE_KEY: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/evals/kv-validation/models.json', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement key --receipt-dir "$RECEIPT_DIR" --cohort cpu-runtime --phase measured - name: Mark lookup start @@ -147,7 +147,7 @@ jobs: uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: runtime-input - key: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + key: skippy-runtime-linux-v2-${{ matrix.runtime.target }}-${{ matrix.runtime.toolchain_epoch }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-native-runtime-input/**', '.github/actions/resolve-native-toolchain-epoch/**', '.github/cache-version.txt', '.github/workflows/ci-linux-runtime-slice.yml', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/crates/skippy-cache/Cargo.toml', 'skippy/crates/skippy-cache/src/**', 'skippy/crates/skippy-ffi/Cargo.toml', 'skippy/crates/skippy-ffi/bindgen/**', 'skippy/crates/skippy-ffi/build.rs', 'skippy/crates/skippy-ffi/build/**', 'skippy/crates/skippy-ffi/src/**', 'skippy/crates/skippy-gpu-bench/native/**', 'skippy/crates/skippy-hf-hub/Cargo.toml', 'skippy/crates/skippy-hf-hub/src/**', 'skippy/crates/skippy-model-artifact/Cargo.toml', 'skippy/crates/skippy-model-artifact/src/**', 'skippy/crates/skippy-model-hf/Cargo.toml', 'skippy/crates/skippy-model-hf/src/**', 'skippy/crates/skippy-model-ref/Cargo.toml', 'skippy/crates/skippy-model-ref/src/**', 'skippy/crates/skippy-model-resolver/Cargo.toml', 'skippy/crates/skippy-model-resolver/src/**', 'skippy/crates/skippy-model/Cargo.toml', 'skippy/crates/skippy-model/src/**', 'skippy/crates/skippy-native-runtime/RUNTIME_VERSION', 'skippy/crates/skippy-package-builder/Cargo.toml', 'skippy/crates/skippy-package-builder/src/**', 'skippy/crates/skippy-package-format/Cargo.toml', 'skippy/crates/skippy-package-format/src/**', 'skippy/crates/skippy-protocol/Cargo.toml', 'skippy/crates/skippy-protocol/build.rs', 'skippy/crates/skippy-protocol/proto/**', 'skippy/crates/skippy-protocol/src/**', 'skippy/crates/skippy-runtime/Cargo.toml', 'skippy/crates/skippy-runtime/src/**', 'skippy/crates/skippy-tokenizer/Cargo.toml', 'skippy/crates/skippy-tokenizer/src/**', 'skippy/evals/kv-validation/models.json', 'skippy/llama_cpp/**', 'skippy/scripts/**', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} - name: Mark lookup end run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement mark --receipt-dir "$RECEIPT_DIR" --phase lookup_end @@ -239,7 +239,7 @@ jobs: echo "MESH_LLM_AUTOMATION_BIN=$target/release/xtask" >> "$GITHUB_ENV" - name: Record computed key before any edit env: - CACHE_KEY: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + CACHE_KEY: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/evals/kv-validation/models.json', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement key --receipt-dir "$RECEIPT_DIR" --cohort hosted-xtask --phase before - name: Apply the admitted unrelated edit @@ -248,7 +248,7 @@ jobs: "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement edit --receipt-dir "$RECEIPT_DIR" --cohort hosted-xtask - name: Record measured key env: - CACHE_KEY: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + CACHE_KEY: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/evals/kv-validation/models.json', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement key --receipt-dir "$RECEIPT_DIR" --cohort hosted-xtask --phase measured - name: Mark lookup start @@ -260,7 +260,7 @@ jobs: uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: path: target/release/xtask - key: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} + key: xtask-hosted-bare-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust_toolchain.outputs.cachekey }}-${{ steps.hosted_image.outputs.identity }}-${{ hashFiles('.cargo/**', '.github/actions/prepare-automation/action.yml', '.github/cache-version.txt', 'Cargo.lock', 'Cargo.toml', 'ci/python-research-source.json', 'mesh/crates/mesh-llm-release-footer/Cargo.toml', 'mesh/crates/mesh-llm-release-footer/src/**', 'scripts/cargo-linker', 'scripts/cargo-linker-linux-*', 'scripts/ci-compat-smoke.sh', 'scripts/lib/lld.sh', 'scripts/linux-glibc-floor.txt', 'skippy/evals/kv-validation/models.json', 'tools/authority-automation/Cargo.toml', 'tools/authority-automation/src/**', 'tools/ci-controller/Cargo.toml', 'tools/ci-controller/src/**', 'tools/process-supervision/Cargo.toml', 'tools/process-supervision/src/**', 'tools/runner-cleanup/Cargo.toml', 'tools/runner-cleanup/src/**', 'tools/trajectory-reader/Cargo.toml', 'tools/trajectory-reader/src/**', 'tools/xtask/Cargo.toml', 'tools/xtask/build.rs', 'tools/xtask/src/**') }} - name: Mark lookup end run: | "$MESH_LLM_AUTOMATION_BIN" ci-ops linux-cache-measurement mark --receipt-dir "$RECEIPT_DIR" --phase lookup_end diff --git a/.github/workflows/windows-warm-caches.yml b/.github/workflows/windows-warm-caches.yml index fda50a0e01..546b5feba1 100644 --- a/.github/workflows/windows-warm-caches.yml +++ b/.github/workflows/windows-warm-caches.yml @@ -54,6 +54,7 @@ on: - 'mesh/crates/mesh-llm-release-footer/src/**' - 'scripts/**' - 'skippy/crates/skippy-gpu-bench/native/**' + - 'skippy/evals/kv-validation/models.json' - 'skippy/llama_cpp/**' - 'skippy/scripts/**' - 'tools/authority-automation/Cargo.toml' diff --git a/tools/xtask/src/ci_operations/cache_inputs.rs b/tools/xtask/src/ci_operations/cache_inputs.rs index 045f8c56fa..d5411d54b4 100644 --- a/tools/xtask/src/ci_operations/cache_inputs.rs +++ b/tools/xtask/src/ci_operations/cache_inputs.rs @@ -134,6 +134,7 @@ impl Inventory { "ci/python-research-source.json", "scripts/ci-compat-smoke.sh", "scripts/linux-glibc-floor.txt", + "skippy/evals/kv-validation/models.json", "skippy/crates/skippy-gpu-bench/native/**", ".github/workflows/ci-windows-runtime-slice.yml", ".github/workflows/windows-warm-caches.yml", @@ -153,6 +154,7 @@ impl Inventory { "ci/python-research-source.json", "scripts/ci-compat-smoke.sh", "scripts/linux-glibc-floor.txt", + "skippy/evals/kv-validation/models.json", ] .map(str::to_owned), ); diff --git a/tools/xtask/src/ci_validation/python_tooling/tests.rs b/tools/xtask/src/ci_validation/python_tooling/tests.rs index 0c45041aaa..dafc9619c3 100644 --- a/tools/xtask/src/ci_validation/python_tooling/tests.rs +++ b/tools/xtask/src/ci_validation/python_tooling/tests.rs @@ -362,7 +362,7 @@ fn agentx_admission_keeps_python_source_and_command_occurrences_closed() { check_fixture(&root) .unwrap_err() .to_string() - .contains("repository Python source is forbidden") + .contains("unreviewed repository Python source") ); fs::remove_file(root.join("skippy/evals/agentx/local-harness.py")).unwrap(); let setup = fs::read_to_string(root.join("just/skippy.just")).unwrap(); From ede388c89ac3c98f67a7023fe8d5a8f9a4639723 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:32:10 +1100 Subject: [PATCH 69/81] ci: stop requiring an eager kv-recurrent record from dense resident stages in the split smoke A ResidentKv stage keeps prefixes as native cells since 5e757b835 and writes exact state to L3 through the offload path, so it no longer emits a record event carrying skippy.exact_cache.payload_kind. The dense leg of the two-node split smoke still required one and failed with 'exact payload: expected "kv-recurrent", observed {}'. The dense expectation keeps the payload selection fields. The durable restart probe still proves the L3 write, the restore and the payload kind for the dense leg, and the hybrid model still requires the kv-recurrent record. --- ci/model-artifacts/kv-auto-smoke-expectations.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/model-artifacts/kv-auto-smoke-expectations.json b/ci/model-artifacts/kv-auto-smoke-expectations.json index 4b9ba96240..7594789d0b 100644 --- a/ci/model-artifacts/kv-auto-smoke-expectations.json +++ b/ci/model-artifacts/kv-auto-smoke-expectations.json @@ -6,8 +6,8 @@ "revision": "9e6855bc4be717fca1ef21360a1db4b29d5c559a", "sha256": "c4a3dd037301b6ecea31d6da37f5cd793ead920dd5ddfe6d589294628d6ce66a", "stages": [ - {"loaded_state_kind": "Dense", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory", "exact_payload_kind": "kv-recurrent"}, - {"loaded_state_kind": "Dense", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory", "exact_payload_kind": "kv-recurrent"} + {"loaded_state_kind": "Dense", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory"}, + {"loaded_state_kind": "Dense", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory"} ] }, "family-granite-hybrid": { From 8af030b471195ec31fd527e471db0dc4f56ec5d4 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:49:26 +1100 Subject: [PATCH 70/81] ci: expect resident prefixes for the hybrid model in the split smoke Patch 0017 makes hybrid and recurrent memories advertise resident prefixes (SKIPPY_MEMORY_CACHE_RESIDENT plus RESIDENT_CHECKPOINT), so both Granite hybrid stages now select ResidentKv and, like the dense stages, no longer emit an eager record event carrying skippy.exact_cache.payload_kind. The recurrent leg of the two-node split smoke still expected resident=false, payload=KvRecurrent and an exact kv-recurrent record, and failed with "exact payload: expected \"kv-recurrent\", observed {}". The previous commit relaxed only the dense stages and wrongly left the hybrid ones. Checked by running split-payloads certify against the recurrent evidence from run 44465847732: the stage checks pass with this file and fail with the old one. The durable restart probe still requires a kv-recurrent L3 entry for this leg. --- ci/model-artifacts/kv-auto-smoke-expectations.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/model-artifacts/kv-auto-smoke-expectations.json b/ci/model-artifacts/kv-auto-smoke-expectations.json index 7594789d0b..309d33b854 100644 --- a/ci/model-artifacts/kv-auto-smoke-expectations.json +++ b/ci/model-artifacts/kv-auto-smoke-expectations.json @@ -15,8 +15,8 @@ "revision": "a864f823cce6e6048b5752e2816fe7a23987d790", "sha256": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb", "stages": [ - {"loaded_state_kind": "Hybrid", "resident": false, "kv_recurrent": true, "payload": "KvRecurrent", "reason": "loaded_graph_and_memory", "exact_payload_kind": "kv-recurrent"}, - {"loaded_state_kind": "Hybrid", "resident": false, "kv_recurrent": true, "payload": "KvRecurrent", "reason": "loaded_graph_and_memory", "exact_payload_kind": "kv-recurrent"} + {"loaded_state_kind": "Hybrid", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory"}, + {"loaded_state_kind": "Hybrid", "resident": true, "kv_recurrent": true, "payload": "ResidentKv", "reason": "loaded_graph_and_memory"} ] } } From d3c020a4a04333dabb17aa1da10b964fb23ca5b3 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:12:41 +1100 Subject: [PATCH 71/81] fix(xtask): drop unused probe_url_range --- tools/xtask/src/command.rs | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/tools/xtask/src/command.rs b/tools/xtask/src/command.rs index 4c39da6138..7a76a957ca 100644 --- a/tools/xtask/src/command.rs +++ b/tools/xtask/src/command.rs @@ -223,26 +223,3 @@ pub(crate) fn normalize_whitespace(value: &str) -> String { value.split_whitespace().collect::>().join(" ") } -/// Range-GETs the first byte of a URL and returns the HTTP status code. Used -/// by fleet pre-flight to prove CDN chunks are readable before submitting -/// jobs that depend on them. -pub fn probe_url_range(url: &str) -> DynResult { - let output = std::process::Command::new("curl") - .args([ - "-s", - "-o", - "/dev/null", - "-w", - "%{http_code}", - "--max-time", - "30", - "-r", - "0-0", - url, - ]) - .output() - .map_err(|e| format!("curl pre-flight: {e}"))?; - let code = String::from_utf8_lossy(&output.stdout).trim().to_string(); - code.parse::() - .map_err(|_| format!("pre-flight returned non-numeric status: {code}").into()) -} From 72719222995d6cffed4928e77d234eedf8979101 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:29:36 +1100 Subject: [PATCH 72/81] fix(ci): review fleet-worker python probes, drop standalone probe script, fmt --- ci/python-tooling-policy.json | 66 ++++++++++++++++++ skippy/evals/agentx/README.md | 15 ++-- skippy/evals/agentx/prefix-reuse-probe.py | 84 ----------------------- tools/xtask/src/command.rs | 1 - 4 files changed, 71 insertions(+), 95 deletions(-) delete mode 100644 skippy/evals/agentx/prefix-reuse-probe.py diff --git a/ci/python-tooling-policy.json b/ci/python-tooling-policy.json index 6a100b1c5c..126c27ddad 100644 --- a/ci/python-tooling-policy.json +++ b/ci/python-tooling-policy.json @@ -428,6 +428,72 @@ } ], "allowed_invocations": [ + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "python3 - </dev/null && echo \"-- skippy nocache profile:\" && python3 \"$W/profile.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" 256 || echo \"-- skippy nocache: SERVER_DIED\"", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "kill -0 $NPID 2>/dev/null && python3 - \"$PORT\" <<'NSYSPY'", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "python3 \"$W/profile.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" 256 || true", + "occurrences": 2, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "python3 \"$W/smoke.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" \"$PROBE_TURNS\" \"$PROBE_BLOCK_CHARS\" \"$PROBE_MAX_TOKENS\" || true", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "&& tar xzf \"$W/py312.tgz\" -C \"$W/py312\" && export PATH=\"$W/py312/python/bin:$PATH\" \\", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "mkdir -p \"$W/py312\"", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, + { + "path": "skippy/evals/agentx/fleet-worker.sh", + "line": "if ! command -v python3.12 >/dev/null; then", + "occurrences": 1, + "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" + }, { "path": ".github/actions/setup-canary-runner/action.yml", "line": "for cmd in cargo rustc just sccache jq python3 uv cmake ninja hf git-lfs lipo brew xcrun; do", diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index c047220047..650aeef27e 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -200,16 +200,11 @@ benchmark owner does not mark the long-prefix/cancellation/L3 TODO complete. ## Prefix-reuse probe -`prefix-reuse-probe.py` reproduces the exact-state retention regression: N -interleaved multi-turn conversations with append-only histories against one -`skippy serve`, reporting `cached_tokens` per request. Any miss after each -conversation's first turn is a retention defect, not prompt churn. Exit code 1 -on any post-first-turn miss. - -``` -# serve with the knobs under test, then: -python3 skippy/evals/agentx/prefix-reuse-probe.py 64000 4 6 6300 -``` +The fleet smoke (`fleet-worker.sh`, via `xtask automation agentx fleet`) +reproduces the exact-state retention regression: interleaved multi-turn +conversations with append-only histories against one `skippy serve`. Any +`cached_tokens` miss after a conversation's first turn is a retention defect, +not prompt churn. Two distinct prefix-cache budgets matter for retention experiments, and A/B runs must move the intended one: diff --git a/skippy/evals/agentx/prefix-reuse-probe.py b/skippy/evals/agentx/prefix-reuse-probe.py deleted file mode 100644 index bf1e07c33d..0000000000 --- a/skippy/evals/agentx/prefix-reuse-probe.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python3 -"""Prefix-reuse probe for skippy serve. - -Replays N interleaved multi-turn conversations with append-only histories -against a running skippy serve and reports per-request cached tokens from the -OpenAI usage payload. This is the minimal reproduction for the exact-state -retention regression where concurrent sessions evicted each other down to a -single catalog entry (see kv_integration/config.rs retention floor). - -Usage: - python3 prefix-reuse-probe.py [port] [nconv] [turns] [block_chars] - -The probe is intentionally dependency-free (urllib only). Conversations use a -stable per-conversation filler so each turn's prompt is a strict extension of -the previous turn's prompt; any cache miss beyond the first turn therefore -measures retention, not prompt churn. -""" -import concurrent.futures -import json -import sys -import time -import urllib.request - -PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 64000 -NCONV = int(sys.argv[2]) if len(sys.argv) > 2 else 4 -TURNS = int(sys.argv[3]) if len(sys.argv) > 3 else 6 -BLOCK = int(sys.argv[4]) if len(sys.argv) > 4 else 6300 - - -def convo(i: int, turn: int): - filler = f"Session {i} stable context block. " * 220 - history = "\n".join( - f"User: {filler[:BLOCK * k]} Question {i}-{k}: name a color." - for k in range(1, turn + 1) - ) - return [ - {"role": "system", "content": "You are a helpful assistant."}, - {"role": "user", "content": history + f" Q{i}-{turn}: color now."}, - ] - - -def ask(i: int, turn: int): - body = json.dumps( - {"model": "probe", "messages": convo(i, turn), "max_tokens": 8, "temperature": 0} - ).encode() - t0 = time.time() - r = urllib.request.urlopen( - urllib.request.Request( - f"http://127.0.0.1:{PORT}/v1/chat/completions", - data=body, - headers={"Content-Type": "application/json"}, - ), - timeout=1800, - ) - out = json.load(r) - usage = out.get("usage", {}) - detail = usage.get("prompt_tokens_details", {}) or {} - return ( - i, - turn, - usage.get("prompt_tokens", 0), - detail.get("cached_tokens", 0), - time.time() - t0, - ) - - -def main() -> int: - print(f"probe: {NCONV} conversations x {TURNS} turns, concurrent per turn") - misses = 0 - for turn in range(2, TURNS + 1): - with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: - for i, t, prompt, cached, dt in ex.map(lambda i: ask(i, turn), range(NCONV)): - hit = cached > 0 - misses += 0 if hit else 1 - print( - f" turn {t} conv {i}: prompt {prompt} cached {cached} " - f"({100 * cached / max(prompt, 1):.0f}%) {dt:.1f}s" - ) - print(f"misses-after-first-turn: {misses}") - return 0 if misses == 0 else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/xtask/src/command.rs b/tools/xtask/src/command.rs index 7a76a957ca..0808db7588 100644 --- a/tools/xtask/src/command.rs +++ b/tools/xtask/src/command.rs @@ -222,4 +222,3 @@ pub(crate) fn display_relative(repo_root: &Path, path: &Path) -> String { pub(crate) fn normalize_whitespace(value: &str) -> String { value.split_whitespace().collect::>().join(" ") } - From f5e1d2c7c480003a14c44ba6960f12e80e61499a Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:57:26 +1100 Subject: [PATCH 73/81] fix(skippy-serving): keep explicit exact budgets strict and floor per session - explicit --prefix-cache-exact-budget is a strict ceiling (one indivisible snapshot may exceed it); the four-entry allowance only stretches the attention-derived default - zero hard limit stays unbounded: skip the hard pass - warn (rate-limited, once/min) whenever retained bytes exceed the hard limit - floor counts conversations: superseded checkpoints (strict prefix of a retained checkpoint) are evicted first, so a session's prefill+decode pair can't push out another session's only continuation - floor regression test now uses distinct blocks and asserts it crosses the cap --- skippy/crates/skippy-cache/src/radix.rs | 102 ++++++++ .../src/kv_integration/config.rs | 228 ++++++++++++++---- .../config/exact_state_limits.rs | 24 +- .../skippy-serving/src/kv_integration/mod.rs | 3 + 4 files changed, 296 insertions(+), 61 deletions(-) diff --git a/skippy/crates/skippy-cache/src/radix.rs b/skippy/crates/skippy-cache/src/radix.rs index e6a480ee3f..632b487473 100644 --- a/skippy/crates/skippy-cache/src/radix.rs +++ b/skippy/crates/skippy-cache/src/radix.rs @@ -365,6 +365,35 @@ impl UnifiedRadixCache { }) } + /// Evict the least-recently-used unreferenced recurrent entry that is a + /// strict prefix of another recurrent entry in its namespace. A longer + /// entry already continues that conversation, so the shorter one is the + /// cheapest snapshot to lose. + pub fn evict_lru_superseded_recurrent(&mut self) -> Option> { + let mut victim = None; + for (namespace, root) in &self.roots { + collect_lru_superseded_recurrent(namespace, root, &mut Vec::new(), &mut victim); + } + let victim = victim?; + let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?; + self.recurrent_evictions = self.recurrent_evictions.saturating_add(1); + Some(RadixEviction { + namespace: victim.namespace, + tokens: victim.tokens, + logical_bytes: victim.logical_bytes, + value, + }) + } + + /// Recurrent entries with no longer recurrent entry below them: the latest + /// continuation of each distinct conversation. + pub fn recurrent_leaf_entries(&self) -> usize { + self.roots + .values() + .map(|root| count_recurrent_leaves(root).0) + .sum() + } + pub fn stats(&self) -> UnifiedRadixCacheStats { let mut stats = UnifiedRadixCacheStats { namespaces: self.roots.len(), @@ -882,6 +911,58 @@ fn collect_lru_victim( path.truncate(original_len); } +/// Returns (leaf recurrent entries, whether the subtree holds any recurrent entry). +fn count_recurrent_leaves(node: &RadixNode) -> (usize, bool) { + let mut leaves = 0; + let mut below = false; + for child in node.children.values() { + let (child_leaves, child_any) = count_recurrent_leaves(child); + leaves += child_leaves; + below |= child_any; + } + let here = node.components.recurrent.is_some(); + if here && !below { + leaves += 1; + } + (leaves, here || below) +} + +/// Returns whether the subtree holds any recurrent entry. +fn collect_lru_superseded_recurrent( + namespace: &str, + node: &RadixNode, + path: &mut Vec, + victim: &mut Option, +) -> bool { + let original_len = path.len(); + path.extend_from_slice(&node.edge); + let mut below = false; + for child in node.children.values() { + below |= collect_lru_superseded_recurrent(namespace, child, path, victim); + } + let entry = node.components.recurrent.as_ref(); + if below && let Some(entry) = entry.filter(|entry| entry.active_refs == 0) { + let replace = victim.as_ref().is_none_or(|current| { + (entry.last_used, namespace, path.as_slice()) + < ( + current.last_used, + current.namespace.as_str(), + current.tokens.as_slice(), + ) + }); + if replace { + *victim = Some(Victim { + namespace: namespace.to_string(), + tokens: path.clone(), + logical_bytes: entry.logical_bytes, + last_used: entry.last_used, + }); + } + } + path.truncate(original_len); + below || entry.is_some() +} + fn collect_resident_eviction_candidates( namespace: &str, node: &RadixNode, @@ -1319,6 +1400,27 @@ mod tests { assert!(cache.release_resident("stage", &[1])); } + #[test] + fn superseded_recurrent_eviction_keeps_each_conversations_latest_entry() { + let mut cache = UnifiedRadixCache::<(), &str>::new(); + cache + .insert_recurrent("stage", &[1, 2], 1, "a-prefill") + .unwrap(); + cache + .insert_recurrent("stage", &[7, 8], 1, "b-prefill") + .unwrap(); + cache + .insert_recurrent("stage", &[1, 2, 3, 4], 1, "a-decode") + .unwrap(); + assert_eq!(cache.recurrent_leaf_entries(), 2); + assert_eq!( + cache.evict_lru_superseded_recurrent().unwrap().value, + "a-prefill" + ); + assert!(cache.evict_lru_superseded_recurrent().is_none()); + assert_eq!(cache.recurrent_leaf_entries(), 2); + } + #[test] fn component_eviction_preserves_other_payload_at_same_prefix() { let mut cache = UnifiedRadixCache::new(); diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index 7f4562f08f..e780cbfc5f 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -816,46 +816,47 @@ fn store_exact_radix_record_with_codec( // Exact snapshots are indivisible, and the soft cap is estimated from // attention KV metadata that cannot include architecture-specific // recurrent state, so one snapshot can legitimately exceed it. Hold a - // working set past the soft cap (never more than the configured entry - // limit) so concurrent sessions on a stage stop evicting each other, then - // apply the hard limit so that allowance stays bounded. - // - // Both passes retain the same floor. A hard pass that fell to a single - // entry defeated the working-set guarantee whenever hybrid snapshots - // (whose recurrent state the attention-derived estimate cannot see) - // pushed the retained set past the hard cap: the catalog collapsed to a - // single entry and concurrent sessions evicted each other on every - // request, which is the regression this policy exists to prevent. The - // retention floor may exceed either byte limit by design; operators who - // need a tighter bound set an explicit exact-state budget. + // working set of conversations past the soft cap (never more than the + // configured entry limit) so concurrent sessions on a stage stop evicting + // each other. The floor counts each conversation's latest continuation: + // a checkpoint that a longer retained checkpoint extends is evicted first. let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); evict_exact_entries_over(radix, blobs, limits.soft_bytes, retention_floor)?; - // The hard cap must be able to hold the retention floor's working set. - // With the attention-derived estimate alone, a hybrid snapshot can exceed - // the configured hard cap by itself; the eviction passes then share the - // same floor and the hard pass can never evict — the cap is dead code and - // the blob store accumulates retained copies past it without bound. The - // effective backstop adapts to the largest snapshot actually stored, so - // it trims growth above the working set instead of against the floor. - let floor_bytes = logical_bytes - .max(1) - .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); - let effective_hard = limits.hard_bytes.max(floor_bytes); - if evict_exact_entries_over(radix, blobs, effective_hard, retention_floor)? > 0 { - // Observable signal that the attention-derived estimate undercounts - // this stage's snapshots: the exact-state catalog held more than the - // hard limit even with the retention floor binding. Set an explicit - // exact-state budget when this repeats and memory must stay bounded. - let _ = skippy_events::diagnostics::emit( - skippy_events::diagnostics::ServingDiagnostic::Warning { - message: "exact-state catalog exceeded its hard byte limit at the retention floor" - .to_string(), - context: Some(format!( - "soft_bytes={} hard_bytes={} effective_hard={effective_hard} floor_entries={retention_floor}", - limits.soft_bytes, limits.hard_bytes - )), - }, - ); + // Zero means unbounded: no hard pass at all. + if limits.hard_bytes > 0 { + // An explicit operator budget is a strict ceiling: only one + // indivisible snapshot may exceed it. The attention-derived default + // stretches to hold the working set, since it cannot see hybrid + // recurrent state and would otherwise collapse the catalog. + let (hard_limit, hard_floor) = if limits.hard_is_explicit { + (limits.hard_bytes, 1) + } else { + let floor_bytes = logical_bytes + .max(1) + .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); + (limits.hard_bytes.max(floor_bytes), retention_floor) + }; + evict_exact_entries_over(radix, blobs, hard_limit, hard_floor)?; + let retained = blobs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .physical_bytes(); + if retained > limits.hard_bytes && exact_state_over_limit_warning_due() { + // Observable signal that the retained working set sits above the + // hard limit, e.g. the attention-derived estimate undercounts this + // stage's snapshots. Set an explicit exact-state budget when this + // repeats and memory must stay bounded. + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "exact-state catalog retained more than its hard byte limit" + .to_string(), + context: Some(format!( + "retained_bytes={retained} soft_bytes={} hard_bytes={} explicit={} floor_entries={retention_floor}", + limits.soft_bytes, limits.hard_bytes, limits.hard_is_explicit + )), + }, + ); + } } #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); @@ -932,9 +933,25 @@ fn cachegen_descriptor_is_qualified(desc: &RuntimeKvPageDesc) -> bool { ) } -/// Evicts least-recently-used exact entries while the catalog holds more than -/// `limit_bytes`, never dropping below `min_retained_entries`. A zero limit -/// means the catalog has no byte ceiling and nothing is evicted. +/// At most one over-limit warning per minute per process. +fn exact_state_over_limit_warning_due() -> bool { + use std::sync::atomic::{AtomicU64, Ordering}; + static LAST_WARNED_SECS: AtomicU64 = AtomicU64::new(0); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let last = LAST_WARNED_SECS.load(Ordering::Relaxed); + (last == 0 || now.saturating_sub(last) >= 60) + && LAST_WARNED_SECS + .compare_exchange(last, now.max(1), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() +} + +/// Evicts exact entries while the catalog holds more than `limit_bytes`. +/// Superseded checkpoints (a strict prefix of another retained checkpoint) +/// go first; then least-recently-used conversations go while more than +/// `min_retained_entries` conversations remain. A zero limit means the +/// catalog has no byte ceiling and nothing is evicted. fn evict_exact_entries_over( radix: &Mutex>, blobs: &Mutex, @@ -952,19 +969,19 @@ fn evict_exact_entries_over( .unwrap_or_else(std::sync::PoisonError::into_inner) .physical_bytes() > limit_bytes; - let above_floor = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .stats() - .recurrent_entries - > floor; - if !over_bytes || !above_floor { + if !over_bytes { break; } - let evicted = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .evict_lru_recurrent(); + let evicted = { + let mut radix = radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + radix.evict_lru_superseded_recurrent().or_else(|| { + (radix.recurrent_leaf_entries() > floor) + .then(|| radix.evict_lru_recurrent()) + .flatten() + }) + }; let Some(evicted) = evicted else { break; }; @@ -1065,6 +1082,7 @@ mod tests { ExactStateByteLimits { soft_bytes, hard_bytes, + hard_is_explicit: false, } } @@ -1329,12 +1347,15 @@ mod tests { pending( &format!("session-{index}"), &[1, index + 2], - &[index as u8 + 1; 32], + &distinct_payload(index as u8, 32), &budget, ), ) .unwrap(); } + // Distinct blocks, so the retained set really is past the hard cap and + // the pre-floor policy would have evicted down to one entry. + assert!(blobs.lock().unwrap().physical_bytes() > 80); let mut radix = radix.lock().unwrap(); assert_eq!(radix.stats().recurrent_entries, 4); for index in 0..4 { @@ -1345,6 +1366,107 @@ mod tests { } } + /// Payload bytes that dedupe into distinct 4-byte blocks per `seed`. + fn distinct_payload(seed: u8, len: usize) -> Vec { + (0..len) + .map(|offset| seed.wrapping_mul(64).wrapping_add(offset as u8)) + .collect() + } + + fn store_sessions( + radix: &Mutex>, + blobs: &Mutex, + limits: ExactStateByteLimits, + sessions: &[(&str, &[i32], u8)], + ) { + let budget = StorageBudget::new(); + for (page, tokens, seed) in sessions { + store_exact_radix_record( + radix, + blobs, + 512, + limits, + None, + None, + pending(page, tokens, &distinct_payload(*seed, 32), &budget), + ) + .unwrap(); + } + } + + #[test] + fn explicit_exact_budget_stays_a_strict_ceiling_past_the_retention_floor() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let explicit_ceiling = ExactStateByteLimits { + soft_bytes: 10, + hard_bytes: 40, + hard_is_explicit: true, + }; + store_sessions( + &radix, + &blobs, + explicit_ceiling, + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ], + ); + // One indivisible 32-byte snapshot fits the ceiling; a second does not. + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 1); + assert!(blobs.lock().unwrap().physical_bytes() <= 40); + } + + #[test] + fn unbounded_byte_limits_keep_every_entry_the_entry_limit_allows() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + store_sessions( + &radix, + &blobs, + limits(0, 0), + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ("e", &[1, 6], 4), + ], + ); + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 5); + } + + #[test] + fn retention_floor_keeps_each_sessions_latest_continuation() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + // Session A stores a prefill and a post-decode checkpoint between the + // other sessions' prefills. Five snapshots exceed the derived hard + // cap; the superseded prefill must go, not another session's only one. + store_sessions( + &radix, + &blobs, + limits(10, 80), + &[ + ("a-prefill", &[1, 2], 0), + ("b", &[1, 3], 1), + ("a-decode", &[1, 2, 9, 9], 2), + ("c", &[1, 4], 3), + ("d", &[1, 5], 4), + ], + ); + let mut radix = radix.lock().unwrap(); + assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); + for tokens in [&[1, 2, 9, 9][..], &[1, 3], &[1, 4], &[1, 5]] { + assert!( + radix.lookup_recurrent("model", tokens).is_some(), + "latest continuation {tokens:?} must survive" + ); + } + } + #[test] fn selected_l3_fill_promotes_to_l2_on_the_record_worker_path() { let radix = Mutex::new(UnifiedRadixCache::new()); diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs index a13bfc6aab..5f6bec1aa2 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs @@ -20,12 +20,13 @@ pub(super) fn exact_state_byte_limits( configured_exact_max_bytes: Option, override_max_bytes: Option<&str>, ) -> ExactStateByteLimits { - let hard_bytes = configured_exact_max_bytes - .or_else(|| override_max_bytes.and_then(|value| value.trim().parse::().ok())) - .unwrap_or_else(|| configured_max_bytes.saturating_mul(EXACT_STATE_HARD_CAP_MULTIPLE)); + let explicit = configured_exact_max_bytes + .or_else(|| override_max_bytes.and_then(|value| value.trim().parse::().ok())); ExactStateByteLimits { soft_bytes: configured_max_bytes, - hard_bytes, + hard_bytes: explicit + .unwrap_or_else(|| configured_max_bytes.saturating_mul(EXACT_STATE_HARD_CAP_MULTIPLE)), + hard_is_explicit: explicit.is_some(), } } @@ -36,6 +37,13 @@ mod tests { ExactStateByteLimits { soft_bytes, hard_bytes, + hard_is_explicit: false, + } + } + fn explicit(soft_bytes: u64, hard_bytes: u64) -> ExactStateByteLimits { + ExactStateByteLimits { + hard_is_explicit: true, + ..limits(soft_bytes, hard_bytes) } } #[test] @@ -52,11 +60,11 @@ mod tests { fn exact_state_byte_limits_honour_the_operator_override() { assert_eq!( exact_state_byte_limits(1_024, None, Some(" 4096 ")), - limits(1_024, 4_096) + explicit(1_024, 4_096) ); assert_eq!( exact_state_byte_limits(1_024, None, Some("0")), - limits(1_024, 0) + explicit(1_024, 0) ); // A malformed override must not silently disable the ceiling. assert_eq!( @@ -69,11 +77,11 @@ mod tests { fn configured_limit_overrides_the_legacy_environment_including_unbounded() { assert_eq!( exact_state_byte_limits(1024, Some(2048), Some("4096")), - limits(1024, 2048) + explicit(1024, 2048) ); assert_eq!( exact_state_byte_limits(1024, Some(0), Some("4096")), - limits(1024, 0) + explicit(1024, 0) ); } } diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 37401fccd7..2bbab6da94 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -157,6 +157,9 @@ pub enum StageKvMode { pub(crate) struct ExactStateByteLimits { pub(crate) soft_bytes: u64, pub(crate) hard_bytes: u64, + /// The hard limit came from an operator budget rather than the + /// attention-derived estimate, so it is a strict ceiling. + pub(crate) hard_is_explicit: bool, } #[derive(Clone)] From aff032fd24721e92b4c7741ad77ae2e49610fbb3 Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:00:00 +1100 Subject: [PATCH 74/81] chore(agentx): split fleet launcher out of the prefix-retention fix Per review: qualify the cache fix on its own. The fleet launcher, worker and its python-policy exceptions move to branch agentx/fleet-launcher for a follow-up PR that addresses its review comments. --- .agents/skills/agentx-fleet-bench/SKILL.md | 83 ---- Cargo.lock | 1 - ci/python-tooling-policy.json | 66 --- skippy/evals/agentx/README.md | 23 - skippy/evals/agentx/fleet-models.json | 34 -- skippy/evals/agentx/fleet-worker.sh | 387 ----------------- tools/xtask/Cargo.toml | 1 - tools/xtask/src/automation/agentx/fleet.rs | 402 ------------------ .../xtask/src/automation/agentx/lifecycle.rs | 65 --- tools/xtask/src/automation/agentx/mod.rs | 8 - 10 files changed, 1070 deletions(-) delete mode 100644 .agents/skills/agentx-fleet-bench/SKILL.md delete mode 100644 skippy/evals/agentx/fleet-models.json delete mode 100644 skippy/evals/agentx/fleet-worker.sh delete mode 100644 tools/xtask/src/automation/agentx/fleet.rs diff --git a/.agents/skills/agentx-fleet-bench/SKILL.md b/.agents/skills/agentx-fleet-bench/SKILL.md deleted file mode 100644 index 9f1d605230..0000000000 --- a/.agents/skills/agentx-fleet-bench/SKILL.md +++ /dev/null @@ -1,83 +0,0 @@ -# agentx-fleet-bench - -Reproduce AgentX llama-vs-skippy benchmarks across parallel fleet machines, driven by xtask, with -everything pinned and reviewable. - -## When to use this skill - -- Run, reproduce, or harvest an AgentX comparison (llama vs skippy) or smoke probe across one or - more fleet machines. -- Diagnose a fleet benchmark run (bounced jobs, missing results, stranded evidence). -- Publish fleet benchmark results to MLflow or a PR. - -## Surface - -All verbs live under `cargo xtool automation agentx`: - -| Verb | Purpose | -|---|---| -| `pin` / `comparison` | Single-machine provenance pin and the 6-arm comparison (existing) | -| `fleet --input manifest.json` | Validate a manifest, pre-flight every kit URL, generate one jy spec per run, submit all in parallel, stamp a run-root | -| `fleet-status --run-root DIR` | Per-job status table for a run-root | -| `fleet-harvest --run-root DIR` | Fetch evidence for terminal jobs, extract matrices, print the results table | -| `mlflow-export` / `mlflow-publish` | Publication (existing) | - -The fleet worker script is repo-owned at `skippy/evals/agentx/fleet-worker.sh` and embedded by -SHA; never edit a copy in a run directory. Models and the corpus are pinned by repo/rev/sha256 -in the manifest. The worker clones the product repository at the manifest commit, builds the -native runtime, skippy CLI and the unpatched llama-server baseline from pinned source, and -moves every result and evidence file through jy artifacts (the daemon uploads -$JIANYANG_ARTIFACT_DIR). There is no external object storage in the flow: distribution is by -git commits, evidence by jy artifacts. - -## Manifest - -```json -{ - "campaign": "agentx-prNNNN-YYYYMMDD", - "product_source_commit": "", - "repo_url": "https://github.com/Mesh-LLM/mesh-llm", - "mode": "smoke", - "corpus": {"repo": "...", "rev": "...", "sha256": "64-hex"}, - "runs": [ - {"model": "qwen3.5-4b", "backend": "cuda", "probe": {"conversations": 4, "turns": 4, "block_chars": 6300}} - ] -} -``` - -Model references resolve to repo/rev/file/sha entries that live in -`skippy/evals/kv-validation/models.json` plus the manifest's per-run overrides. - -## Hard rules (learned expensively) - -1. **Placement is by hardware only.** Targets are `os: linux|macos` plus worker-side guards - (`NO_AARCH64_HOST`, memory floor for Metal). Never target nodes by name. -2. **`jy result` returns nothing until a job TERMINATES.** A running job with no results is - healthy. Never cancel for missing results. -3. **Artifacts ship only on clean worker exit.** For stranded evidence use the scavenge pattern: - a pinned-hardware job that tars the dead run dir into `$JIANYANG_ARTIFACT_DIR` and exits 0. -4. **Guard-exits requeue; real errors diagnose.** `NO_PYTHON312`/`NO_AARCH64_HOST`/placement - bounces: `jy requeue ` (submit dedupes identical specs). Anything else: read - `jy logs | tail -30` first. -5. **`fleet` pre-flights the pinned commit** (`git ls-remote`) before submitting, and the - worker builds everything from that commit. Never distribute binaries through external object - storage: source pins + jy artifacts only. The historical CDN path-keyed negative-cache - (404s pinned for hours per URL path) is exactly why. -6. **A/B experiments must target the intended budget knob.** `AGENTX_SKIPPY_PREFIX_CACHE_BUDGET` - (exact-state catalog cap) is distinct from `AGENTX_SKIPPY_PREFIX_CACHE_RAM` (resident - checkpoint RAM). -7. The prefix-reuse regression probe is `skippy/evals/agentx/prefix-reuse-probe.py` (exit 1 on - any post-first-turn miss). -8. `jy` sessions expire; empty CLI output means `jy login` and retry. -9. Watch long runs with a paseo heartbeat that carries these rules; 10-minute cadence for smoke, - 30 for full campaigns. -10. Harvest order: evidence -> results table -> PR comment -> MLflow publish, in that order. - -## Reading results - -- Smoke reports per-turn `tok/s` and `cached%` plus a `steady_tok_s` summary per engine. Skippy - `cached%` should track llama's on every model; a gap with matching cache means decode-bound, a - gap with low cache means retention is still failing. -- Comparison campaigns interleave arms (`llama, skippy, skippy, llama, llama, skippy`) at - c1/c2/c4 with 69 requests and 18,713 verified output tokens per cell. Judge skippy by - `output_tok_s`, `cache_read_tokens.p50`, and `ttft.p50` per cell. diff --git a/Cargo.lock b/Cargo.lock index 65d953e7aa..3fbf5f0cfe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11797,7 +11797,6 @@ name = "xtask" version = "0.80.0" dependencies = [ "authority-automation", - "base64 0.22.1", "caseless", "ci-controller", "ed25519-dalek", diff --git a/ci/python-tooling-policy.json b/ci/python-tooling-policy.json index 126c27ddad..6a100b1c5c 100644 --- a/ci/python-tooling-policy.json +++ b/ci/python-tooling-policy.json @@ -428,72 +428,6 @@ } ], "allowed_invocations": [ - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "python3 - </dev/null && echo \"-- skippy nocache profile:\" && python3 \"$W/profile.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" 256 || echo \"-- skippy nocache: SERVER_DIED\"", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "kill -0 $NPID 2>/dev/null && python3 - \"$PORT\" <<'NSYSPY'", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "python3 \"$W/profile.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" 256 || true", - "occurrences": 2, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "python3 \"$W/smoke.py\" \"$PORT\" \"$PROBE_CONVERSATIONS\" \"$PROBE_TURNS\" \"$PROBE_BLOCK_CHARS\" \"$PROBE_MAX_TOKENS\" || true", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "&& tar xzf \"$W/py312.tgz\" -C \"$W/py312\" && export PATH=\"$W/py312/python/bin:$PATH\" \\", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "mkdir -p \"$W/py312\"", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, - { - "path": "skippy/evals/agentx/fleet-worker.sh", - "line": "if ! command -v python3.12 >/dev/null; then", - "occurrences": 1, - "purpose": "AgentX fleet GPU worker: bounded smoke/profile probes on lab hosts" - }, { "path": ".github/actions/setup-canary-runner/action.yml", "line": "for cmd in cargo rustc just sccache jq python3 uv cmake ninja hf git-lfs lipo brew xcrun; do", diff --git a/skippy/evals/agentx/README.md b/skippy/evals/agentx/README.md index 650aeef27e..dae1f5f95a 100644 --- a/skippy/evals/agentx/README.md +++ b/skippy/evals/agentx/README.md @@ -197,26 +197,3 @@ an explicit nonzero exit, another signal, or forced cleanup fails the campaign. The ordinary CI/GPU suite and registered JY templates are unchanged. This benchmark owner does not mark the long-prefix/cancellation/L3 TODO complete. - -## Prefix-reuse probe - -The fleet smoke (`fleet-worker.sh`, via `xtask automation agentx fleet`) -reproduces the exact-state retention regression: interleaved multi-turn -conversations with append-only histories against one `skippy serve`. Any -`cached_tokens` miss after a conversation's first turn is a retention defect, -not prompt churn. - -Two distinct prefix-cache budgets matter for retention experiments, and A/B -runs must move the intended one: - -- `--prefix-cache-budget` (`kv_cache.max_bytes`) bounds the exact-state - catalog; its auto default is estimated from attention KV metadata and can - undercount hybrid recurrent state. The retention floor keeps concurrent - sessions' entries alive past this cap. -- `--prefix-cache-ram` (`kv_cache.l2_max_bytes`) bounds resident-checkpoint - RAM and is independent of the exact-state catalog. - -The AgentX comparison harness exposes both for its skippy arm through -`AGENTX_SKIPPY_PREFIX_CACHE_BUDGET` and `AGENTX_SKIPPY_PREFIX_CACHE_RAM`, so -fleet campaigns can encode and reproduce retention experiments without -editing the harness. diff --git a/skippy/evals/agentx/fleet-models.json b/skippy/evals/agentx/fleet-models.json deleted file mode 100644 index 84cedebd07..0000000000 --- a/skippy/evals/agentx/fleet-models.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "qwen3-4b": { - "MODEL_REPO": "unsloth/Qwen3-4B-Instruct-2507-GGUF", - "MODEL_REV": "a06e946bb6b655725eafa393f4a9745d460374c9", - "MODEL_FILE": "Qwen3-4B-Instruct-2507-Q4_K_M.gguf", - "MODEL_SHA": "3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597", - "TOK_REPO": "Qwen/Qwen3-4B-Instruct-2507", - "TOK_REV": "cdbee75f17c01a7cc42f958dc650907174af0554" - }, - "qwen3.5-4b": { - "MODEL_REPO": "unsloth/Qwen3.5-4B-GGUF", - "MODEL_REV": "e87f176479d0855a907a41277aca2f8ee7a09523", - "MODEL_FILE": "Qwen3.5-4B-Q4_K_M.gguf", - "MODEL_SHA": "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4", - "TOK_REPO": "Qwen/Qwen3.5-4B-Instruct", - "TOK_REV": "e87f176479d0855a907a41277aca2f8ee7a09523" - }, - "coder-30b": { - "MODEL_REPO": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", - "MODEL_REV": "b17cb02dd882d5b6ab62fc777ad2995f19668350", - "MODEL_FILE": "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf", - "MODEL_SHA": "fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad", - "TOK_REPO": "Qwen/Qwen3-Coder-30B-A3B-Instruct", - "TOK_REV": "b2cff646eb4bb1d68355c01b18ae02e7cf42d120" - }, - "qwen3.5-35b": { - "MODEL_REPO": "unsloth/Qwen3.5-35B-A3B-GGUF", - "MODEL_REV": "bc014a17be43adabd7066b7a86075ff935c6a4e2", - "MODEL_FILE": "Qwen3.5-35B-A3B-Q4_K_M.gguf", - "MODEL_SHA": "3b46d1066bc91cc2d613e3bc22ce691dd77e6f0d33c9060690d24ce6de494375", - "TOK_REPO": "Qwen/Qwen3.5-35B-A3B", - "TOK_REV": "59d61f3ce65a6d9863b86d2e96597125219dc754" - } -} \ No newline at end of file diff --git a/skippy/evals/agentx/fleet-worker.sh b/skippy/evals/agentx/fleet-worker.sh deleted file mode 100644 index 167f6b6fe7..0000000000 --- a/skippy/evals/agentx/fleet-worker.sh +++ /dev/null @@ -1,387 +0,0 @@ -#!/usr/bin/env bash -# Fleet worker: builds product + baseline from pinned source in-job, then runs -# the AgentX benchmark. Everything that leaves the machine travels through jy -# artifacts (the daemon uploads $JIANYANG_ARTIFACT_DIR); nothing is fetched -# from or pushed to external object storage. Managed by -# `cargo xtool automation agentx fleet`; see .agents/skills/agentx-fleet-bench. -# -# Env contract (set by the generated spec): -# MODE (smoke|comparison), PRODUCT_COMMIT, REPO_URL, -# BACKEND (cuda|metal), MODEL_KEY, MODEL_REPO, MODEL_REV, MODEL_FILE, MODEL_SHA, -# TOK_REPO, TOK_REV, CORPUS_REPO, CORPUS_REV, CORPUS_SHA (comparison), -# PROBE_CONVERSATIONS, PROBE_TURNS, PROBE_BLOCK_CHARS, PROBE_MAX_TOKENS (smoke), -# THREADS, CAMPAIGN -# Exit codes: 30 need-bigger-mac, 31 no-python, 33 wrong-arch, 34 repo-clone, -# 46 product-build, 47 baseline-build, 48 client-env -set -Eeuo pipefail -W=$PWD -export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$PATH" -THREADS="${THREADS:-20}" - -# ---- host guards (hardware placement; never node names) ---- -if [ "$BACKEND" = "cuda" ]; then - [ "$(uname -m)" = "aarch64" ] || { echo NO_AARCH64_HOST; exit 33; } - nvidia-smi -L >/dev/null 2>&1 || { echo NO_CUDA_GPU; exit 31; } -else - MEM=$(sysctl -n hw.memsize 2>/dev/null || echo 0) - [ "$MEM" -ge 200000000000 ] || { echo NEED_BIGGER_MAC; exit 30; } -fi -if ! command -v python3.12 >/dev/null; then - PYTUPLE="aarch64-unknown-linux-gnu"; [ "$(uname -s)" = Darwin ] && PYTUPLE="aarch64-apple-darwin" - mkdir -p "$W/py312" - curl -fsSL --retry 3 --max-time 600 "https://github.com/astral-sh/python-build-standalone/releases/download/20250115/cpython-3.12.8+20250115-$PYTUPLE-install_only.tar.gz" -o "$W/py312.tgz" \ - && tar xzf "$W/py312.tgz" -C "$W/py312" && export PATH="$W/py312/python/bin:$PATH" \ - || { echo NO_PYTHON312; exit 31; } -fi -command -v cargo >/dev/null || curl -fsSL https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal -command -v just >/dev/null || cargo install just --locked -# Fresh machine: a cold sccache adds failure modes (CUDA cubin outputs are not -# cacheable) with no cache benefit. Use the build script's own off switch. -export LLAMA_STAGE_USE_SCCACHE=0 -export SKIPPY_USE_SCCACHE=0 -BUILD_PATH="$PATH" - -# ---- product source at the pinned commit ---- -echo "== cloning $REPO_URL @ ${PRODUCT_COMMIT:0:12}" -git clone -q "$REPO_URL" "$W/repo" || { echo REPO_CLONE_FAILED; exit 34; } -cd "$W/repo" -git checkout -q --detach "$PRODUCT_COMMIT" || { echo COMMIT_CHECKOUT_FAILED; exit 34; } -UPSTREAM_PIN="$(tr -d '[:space:]' < skippy/llama_cpp/upstream.txt)" - -# ---- product build: native runtime + skippy CLI (owning recipes) ---- -echo "== building product runtime (backend=$BACKEND)" -if ! PATH="$BUILD_PATH" just release-runtime-build "$BACKEND" > "$W/build-runtime.log" 2>&1; then - tail -5 "$W/build-runtime.log"; echo PRODUCT_BUILD_FAILED; exit 46 -fi -if ! PATH="$BUILD_PATH" just skippy-cli-release-build > "$W/build-cli.log" 2>&1; then - tail -5 "$W/build-cli.log"; echo PRODUCT_BUILD_FAILED; exit 46 -fi -RUNTIME_DIR="$(ls -d "$W/repo/dist/native-runtimes"/meshllm-native-runtime-* 2>/dev/null | head -1)" -NATIVE_COMMIT="$(git -C "$W/repo/.deps/llama.cpp" rev-parse HEAD 2>/dev/null || echo "$PRODUCT_COMMIT")" -[ -n "$RUNTIME_DIR" ] || { echo RUNTIME_DIR_MISSING; exit 46; } - -# ---- baseline build: unpatched llama-server at the upstream pin ---- -echo "== building vanilla llama-server @ ${UPSTREAM_PIN:0:12}" -git clone -q https://github.com/ggml-org/llama.cpp "$W/llama-upstream" || { echo BASELINE_CLONE_FAILED; exit 47; } -cd "$W/llama-upstream" && git checkout -q --detach "$UPSTREAM_PIN" -CMAKE_FLAGS=(-DLLAMA_CURL=OFF -DCMAKE_BUILD_TYPE=Release) -if [ "$BACKEND" = "cuda" ]; then - CMAKE_FLAGS+=(-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121) -fi -PATH="$BUILD_PATH" cmake -B build -S . "${CMAKE_FLAGS[@]}" > "$W/baseline-cmake.log" 2>&1 || { tail -5 "$W/baseline-cmake.log"; echo BASELINE_BUILD_FAILED; exit 47; } -PATH="$BUILD_PATH" cmake --build build --target llama-server -j "$THREADS" > "$W/baseline-build.log" 2>&1 || { tail -5 "$W/baseline-build.log"; echo BASELINE_BUILD_FAILED; exit 47; } -mkdir -p "$W/repo/.deps/agentx-llama-build/bin" "$W/repo/.deps/agentx-llama-build/lib" -cp build/bin/llama-server "$W/repo/.deps/agentx-llama-build/bin/" -# Companion shared libs live beside the binary in build/bin and in build/lib; -# collect both so the server finds libllama-server-impl.so and friends. -for libdir in build/bin build/lib; do - [ -d "$libdir" ] && cp "$libdir"/*.so* "$W/repo/.deps/agentx-llama-build/lib/" 2>/dev/null || true -done -"$W/repo/.deps/agentx-llama-build/bin/llama-server" --version || { echo BASELINE_SERVER_BROKEN; exit 47; } - -# ---- link fixups for the pinned baseline (system ssl/crypto, $ORIGIN rpath) ---- -if [ "$BACKEND" = "cuda" ]; then - command -v patchelf >/dev/null || { mkdir -p "$W/pf" "$HOME/.local/bin"; \ - curl -fsSL --retry 3 https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-aarch64.tar.gz | tar xz -C "$W/pf"; \ - cp "$(find "$W/pf" -name patchelf -type f -print -quit)" "$HOME/.local/bin/patchelf"; export PATH="$HOME/.local/bin:$PATH"; } - LDC=$(ldconfig -p 2>/dev/null); BLD="$W/repo/.deps/agentx-llama-build" - for lib in libssl.so.3 libcrypto.so.3; do - line=$(printf '%s\n' "$LDC" | grep -m1 " $lib ") || true; [ -n "$line" ] || continue - cp "$(printf '%s' "$line" | awk '{print $NF}')" "$BLD/lib/$lib" - patchelf --set-rpath '$ORIGIN' "$BLD/lib/$lib" || true - done - patchelf --set-rpath '$ORIGIN/../lib' "$BLD/bin/llama-server" 2>/dev/null || true -fi - -# ---- model (hub cache verified, else verified download) ---- -HUB="${HF_HOME:-$HOME/.cache/huggingface}/hub" -MODEL="$HUB/models--${MODEL_REPO//\//--}/snapshots/$MODEL_REV/$MODEL_FILE" -if [ ! -f "$MODEL" ] || ! printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - 2>/dev/null; then - echo "downloading $MODEL_FILE" - mkdir -p "$W/models"; MODEL="$W/models/$MODEL_FILE" - ok=0 - for a in 1 2 3; do rm -f "$MODEL" - curl -fL --retry 4 --retry-all-errors --max-time 2400 "https://huggingface.co/$MODEL_REPO/resolve/$MODEL_REV/$MODEL_FILE" -o "$MODEL" \ - && printf '%s %s\n' "$MODEL_SHA" "$MODEL" | shasum -a256 -c - && ok=1 && break - sleep 10 - done - [ "$ok" = "1" ] || { echo MODEL_DOWNLOAD_FAILED; exit 45; } -fi - -if [ "$MODE" = "smoke" ]; then - # ---- smoke: llama vs skippy multi-turn probe ---- - cat > "$W/smoke.py" <<'PYEOF' -import concurrent.futures, json, sys, time, urllib.request, urllib.error -PORT, NCONV, TURNS, BLOCK, MAXTOK = (int(a) for a in sys.argv[1:6]) -def convo(i, turn): - filler = f"Session {i} stable context block. " * 220 - history = "\n".join(f"User: {filler[:BLOCK*k]} Question {i}-{k}: name a color." for k in range(1, turn+1)) - return [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":history+f" Q{i}-{turn}: describe a sunset in one paragraph."}] -def ask(pair): - i, turn = pair - time.sleep(i) # stagger concurrent conversation starts by 1s each - body = json.dumps({"model":"m","messages":convo(i,turn),"max_tokens":MAXTOK,"temperature":0,"stream":False}).encode() - t0=time.time(); err=None; pt=ct=comp=0 - # A freshly started server can refuse part of its first concurrent accept - # burst while its listener finishes warming up; retry briefly instead of - # failing the whole conversation. - for attempt in range(6): - try: - r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=2400) - out=json.load(r); u=out.get("usage",{}); d=u.get("prompt_tokens_details",{}) or {} - pt, ct, comp = u.get("prompt_tokens",0), d.get("cached_tokens",0), u.get("completion_tokens",0) - err=None; break - except urllib.error.HTTPError as e: err=f"HTTP {e.code}: {e.read()[:120]}"; break - except Exception as e: - err=f"{type(e).__name__}: {e}" - if attempt < 5: time.sleep(5) - return (i, turn, pt, ct, comp, time.time()-t0, err) -turns=[] -for turn in range(1, TURNS+1): - t0=time.time() - with concurrent.futures.ThreadPoolExecutor(max_workers=NCONV) as ex: - results = list(ex.map(ask, [(i,turn) for i in range(NCONV)])) - wall=time.time()-t0 - errs=[r for r in results if r[6]] - if errs: - for r in errs[:2]: print(f" turn {turn} conv {r[0]}: ERROR {r[6]}", flush=True) - continue - toks=sum(r[4] for r in results); cached=sum(r[3] for r in results); prompts=sum(r[2] for r in results) - print(f" RESULT turn {turn}: {toks/wall:6.1f} tok/s | cached {100*cached/max(prompts,1):3.0f}% | wall {wall:5.1f}s", flush=True) - turns.append(toks/wall) -if turns: - steady=turns[1:] or turns - print(f" SUMMARY steady_tok_s={sum(steady)/len(steady):.1f}", flush=True) -PYEOF - PORT=65100 - run_engine () { - NAME="$1"; RT="$2"; shift 2 - PORT=$((PORT+1)) - "$@" > "$W/serve-$NAME.log" 2>&1 & - PID=$! - READY=0 - for i in $(seq 1 "$RT"); do - sleep 5 - kill -0 $PID 2>/dev/null || break - # Require the full API surface, not just a bound port: /v1/models - # answers only once the server has finished loading and its slots exist. - if curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1; then - READY=$((READY+1)); [ "$READY" -ge 2 ] && break - else - READY=0 - fi - done - if [ "$READY" -lt 2 ]; then - echo "-- $NAME: SERVER_START_FAILED; log tail:" - tail -30 "$W/serve-$NAME.log" 2>/dev/null | sed 's/^/ /' - cp "$W/serve-$NAME.log" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true - kill $PID 2>/dev/null || true; sleep 8 - return 1 - fi - echo "-- $NAME:" - python3 "$W/smoke.py" "$PORT" "$PROBE_CONVERSATIONS" "$PROBE_TURNS" "$PROBE_BLOCK_CHARS" "$PROBE_MAX_TOKENS" || true - kill $PID 2>/dev/null || true - for w in $(seq 1 12); do kill -0 $PID 2>/dev/null || break; sleep 5; done - kill -9 $PID 2>/dev/null || true - sleep 5 - } - echo "===== MODEL $MODEL_KEY ($BACKEND) =====" - NGL=99; [ "$BACKEND" = "metal" ] && NGL=-1 - CTX=$((131072*PROBE_CONVERSATIONS)) - run_engine llama 120 "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $((PORT+1)) --parallel "$PROBE_CONVERSATIONS" --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size "$CTX" --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" - run_engine skippy 180 "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$((PORT+1))" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers "$NGL" --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" - # ---- decode profile: streaming pass with per-token timestamps ---- - cat > "$W/profile.py" <<'PYEOF' -import json, sys, time, urllib.request -PORT, NCONV, MAXTOK = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) -def convo(i): - filler = f"Session {i} stable context block. " * 220 - return [{"role":"system","content":"You are a helpful assistant."}, - {"role":"user","content":filler + f" Q{i}: write a vivid paragraph about the ocean."}] -def profile_one(i): - body = json.dumps({"model":"m","messages":convo(i),"max_tokens":MAXTOK,"temperature":0,"stream":True}).encode() - req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}) - stamps = [] - t0 = time.time() - r = urllib.request.urlopen(req, timeout=600) - for line in r: - if not line.startswith(b"data: "): continue - payload = line[6:].strip() - if payload == b"[DONE]": break - try: chunk = json.loads(payload) - except Exception: continue - delta = chunk.get("choices",[{}])[0].get("delta",{}) - if delta.get("content"): stamps.append(time.time()) - ttft = stamps[0]-t0 if stamps else -1 - itls = [b-a for a,b in zip(stamps, stamps[1:])] if len(stamps)>1 else [] - return {"conv":i,"ttft_s":round(ttft,4),"tokens":len(stamps), - "itl_ms_p50":round(sorted(itls)[len(itls)//2]*1000,2) if itls else -1, - "itl_ms_mean":round(sum(itls)/len(itls)*1000,2) if itls else -1, - "tok_s":round(len(stamps)/(stamps[-1]-t0),2) if len(stamps)>1 else -1} -import concurrent.futures -for nconc in ([1] if NCONV==1 else [1, NCONV]): - with concurrent.futures.ThreadPoolExecutor(max_workers=nconc) as ex: - results = list(ex.map(profile_one, range(nconc))) - tok_s = sum(r["tok_s"] for r in results if r["tok_s"]>0) - itl = [r["itl_ms_p50"] for r in results if r["itl_ms_p50"]>0] - line = {"concurrency":nconc,"aggregate_tok_s":round(tok_s,1), - "itl_p50_ms":round(sum(itl)/len(itl),2) if itl else -1, - "per_conv":results} - print("PROFILE " + json.dumps(line), flush=True) -PYEOF - PORT=$((PORT+1)) - "$W/repo/.deps/agentx-llama-build/bin/llama-server" --model "$MODEL" --alias m --host 127.0.0.1 --port $PORT --parallel 4 --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --chat-template-kwargs '{"enable_thinking":false}' --ctx-size 524288 --cache-ram 8192 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" > "$W/serve-llama-prof.log" 2>&1 & - LP=$! - for i in $(seq 1 120); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done - echo "-- llama profile:" - python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true - kill $LP 2>/dev/null || true - for w in $(seq 1 12); do kill -0 $LP 2>/dev/null || break; sleep 5; done - kill -9 $LP 2>/dev/null || true - sleep 5 - PORT=$((PORT+1)) - SKIPPY_TELEMETRY_STDERR=1 \ - "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-prof.log" 2>&1 & - SP=$! - for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done - echo "-- skippy profile:" - python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || true - kill $SP 2>/dev/null || true - for w in $(seq 1 12); do kill -0 $SP 2>/dev/null || break; sleep 5; done - kill -9 $SP 2>/dev/null || true - sleep 5 - # ---- nsys CUDA timeline: one c1 prefill per engine ---- - echo "-- nsys profiles:" - for ENGINE in llama skippy skippy-nocache; do - PORT=$((PORT+1)) - EXTRA="" - [ "$ENGINE" = "skippy-nocache" ] && EXTRA="--prefix-cache off" - [ "$ENGINE" = "skippy" ] || [ "$ENGINE" = "skippy-nocache" ] && BIN="$W/repo/target/release/skippy" || BIN="$W/repo/.deps/agentx-llama-build/bin/llama-server" - if [ "$ENGINE" = "llama" ]; then - nsys profile -o "$W/nsys-$ENGINE" --trace=cuda,nvtx --force-overwrite=true \ - "$BIN" --model "$MODEL" --alias m --host 127.0.0.1 --port $PORT --parallel 1 --batch-size 2048 --ubatch-size 512 --n-gpu-layers 99 --cache-type-k f16 --cache-type-v f16 --flash-attn on --jinja --ctx-size 131072 --no-kv-unified --threads "$THREADS" --threads-batch "$THREADS" > /dev/null 2>&1 & - else - [ "$ENGINE" = "skippy" ] && PC="on" || PC="off" - nsys profile -o "$W/nsys-$ENGINE" --trace=cuda,nvtx --force-overwrite=true \ - "$BIN" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache "$PC" --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > /dev/null 2>&1 & - fi - NPID=$! - for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done - kill -0 $NPID 2>/dev/null && python3 - "$PORT" <<'NSYSPY' -import json, sys, time, urllib.request -PORT = int(sys.argv[1]) -msgs = [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Session stable context block. "*220 + " Write one paragraph."}] -body = json.dumps({"model":"m","messages":msgs,"max_tokens":32,"temperature":0,"stream":False}).encode() -t0=time.time() -r=urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}),timeout=300) -out=json.load(r) -print(f" nsys {PORT}: ttft={out.get('choices',[{}])[0].get('created',0)} total={time.time()-t0:.3f}s tokens={out.get('usage',{}).get('completion_tokens',0)}") -NSYSPY - kill $NPID 2>/dev/null || true; sleep 10; kill -9 $NPID 2>/dev/null || true; sleep 5 - done - # Ship nsys reports - for f in "$W"/nsys-*.nsys-rep; do [ -f "$f" ] && cp "$f" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null; done - for f in "$W"/nsys-*.qdrep; do [ -f "$f" ] && cp "$f" "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null; done - - # ---- skippy profile WITHOUT prefix cache: isolates checkpoint export cost ---- - PORT=$((PORT+1)) - "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache off --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --runtime-bundle "$RUNTIME_DIR" > "$W/serve-skippy-nocache.log" 2>&1 & - NP=$! - for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done - kill -0 $NP 2>/dev/null && echo "-- skippy nocache profile:" && python3 "$W/profile.py" "$PORT" "$PROBE_CONVERSATIONS" 256 || echo "-- skippy nocache: SERVER_DIED" - kill $NP 2>/dev/null || true - for w in $(seq 1 12); do kill -0 $NP 2>/dev/null || break; sleep 5; done - kill -9 $NP 2>/dev/null || true - sleep 5 - # ---- prefill chunk sweep: TTFT vs chunk size ---- - echo "-- prefill chunk sweep:" - for CHUNK in 64 256 512 2048; do - PORT=$((PORT+1)) - "$W/repo/target/release/skippy" --output jsonl serve --model-path "$MODEL" --model-id m --bind-addr "127.0.0.1:$PORT" --startup-timeout-secs 900 --batch-size 2048 --microbatch-size 512 --generation-queue-capacity 256 --generation-admission-timeout-secs 1500 --n-gpu-layers 99 --kv-cache-type-k f16 --kv-cache-type-v f16 --flash-attention enabled --speculative-strategy disabled --prefix-cache on --prefix-cache-ram 8GiB --kv-cache-disk off --threads "$THREADS" --threads-batch "$THREADS" --ctx-size 131072 --prefill-chunk-size "$CHUNK" --prefill-chunk-policy fixed --runtime-bundle "$RUNTIME_DIR" > "$W/serve-sweep-$CHUNK.log" 2>&1 & - SWPID=$! - for i in $(seq 1 180); do sleep 5; curl -sf --max-time 5 "http://127.0.0.1:$PORT/v1/models" >/dev/null 2>&1 && break; done - if ! kill -0 $SWPID 2>/dev/null; then - echo " SWEEP chunk=$CHUNK SERVER_DIED" - continue - fi - python3 - "$PORT" "$CHUNK" <<'SWEEPPY' -import json, sys, time, urllib.request -PORT, CHUNK = int(sys.argv[1]), sys.argv[2] -filler = "Session sweep stable context block. " * 220 -msgs = [{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":filler + " Write one paragraph about mountains."}] -body = json.dumps({"model":"m","messages":msgs,"max_tokens":64,"temperature":0,"stream":True}).encode() -ttfts = [] -for trial in range(3): - req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions",data=body,headers={"Content-Type":"application/json"}) - t0 = time.time(); first = None; n = 0 - r = urllib.request.urlopen(req, timeout=120) - for line in r: - if not line.startswith(b"data: "): continue - p = line[6:].strip() - if p == b"[DONE]": break - try: c = json.loads(p) - except Exception: continue - if c.get("choices",[{}])[0].get("delta",{}).get("content"): - if first is None: first = time.time() - n += 1 - if first: ttfts.append(first - t0) -avg = sum(ttfts)/len(ttfts) if ttfts else -1 -print(f" SWEEP chunk={CHUNK} ttft_avg={avg:.3f}s (trials={len(ttfts)})", flush=True) -SWEEPPY - kill $SWPID 2>/dev/null || true - for w in $(seq 1 12); do kill -0 $SWPID 2>/dev/null || break; sleep 5; done - kill -9 $SWPID 2>/dev/null || true - sleep 5 - done - cp "$W"/serve-*.log "$JIANYANG_ARTIFACT_DIR/" 2>/dev/null || true - echo SMOKE_DONE - exit 0 -fi - -# ---- comparison: full provenance-pinned campaign ---- -cd "$W/repo" -echo "== client env" -just agentx-setup > "$W/agentx-setup.log" 2>&1 || { tail -5 "$W/agentx-setup.log"; echo CLIENT_ENV_FAILED; exit 48; } -CLIENT="$W/repo/skippy/evals/agentx/.venv/bin/agentx" -[ -x "$CLIENT" ] || { echo NO_AGENTX_CLIENT; exit 48; } -find "$W/repo/skippy/evals/agentx/.venv/lib" -name '*.pth' -type f 2>/dev/null | while read -r p; do grep -q "^import" "$p" && rm -f "$p" && echo "removed: $p"; done || true - -export HF_HUB_CACHE="$W/hf/hub" -TD="$HF_HUB_CACHE/models--${TOK_REPO//\//--}/snapshots/$TOK_REV" -mkdir -p "$TD" -for f in tokenizer.json tokenizer_config.json special_tokens_map.json config.json generation_config.json; do - [ -s "$TD/$f" ] || curl -sfL "https://huggingface.co/$TOK_REPO/resolve/$TOK_REV/$f" -o "$TD/$f" || true -done - -CORPUS_PATH="$HUB/datasets--${CORPUS_REPO//\//--}/snapshots/$CORPUS_REV/traces.jsonl" -if [ ! -f "$CORPUS_PATH" ]; then - mkdir -p "$(dirname "$CORPUS_PATH")" 2>/dev/null || { mkdir -p "$W/models"; CORPUS_PATH="$W/models/traces.jsonl"; } - curl -fL --retry 4 --max-time 2400 "https://huggingface.co/datasets/$CORPUS_REPO/resolve/$CORPUS_REV/traces.jsonl" -o "$CORPUS_PATH" || { echo CORPUS_FAILED; exit 49; } -fi -printf '%s %s\n' "$CORPUS_SHA" "$CORPUS_PATH" | shasum -a256 -c - - -MANIFEST=$(find "$RUNTIME_DIR" -name manifest.json -print -quit) -DIGEST=$(python3 - "$MANIFEST" <<'PY' -import json,sys -print(json.load(open(sys.argv[1]))["build"]["llama_patch_digest"]) -PY -) -python3 - <&1 | tail -3 -( while sleep 120; do ls "$W/campaign-out" >> "$JIANYANG_ARTIFACT_DIR/live-progress.log" 2>/dev/null; done ) & -OBS=$! -CMP_RC=0 -cargo xtool automation agentx comparison --input "$W/request.pinned.json" --output "$W/campaign-out" 2>&1 | tail -10 || CMP_RC=1 -kill $OBS 2>/dev/null || true -tar czf "$JIANYANG_ARTIFACT_DIR/evidence.tgz" -C "$W" campaign-out request.paths.json request.pinned.json 2>/dev/null || tar czf "$JIANYANG_ARTIFACT_DIR/evidence.tgz" -C "$W" campaign-out -shasum -a256 "$JIANYANG_ARTIFACT_DIR/evidence.tgz" | awk '{print $1" evidence.tgz"}' > "$JIANYANG_ARTIFACT_DIR/evidence.tgz.manifest" -[ "$CMP_RC" = "0" ] && echo CAMPAIGN_OK || { echo "CAMPAIGN_FAILED rc=$CMP_RC"; exit 1; } diff --git a/tools/xtask/Cargo.toml b/tools/xtask/Cargo.toml index 581e65f5cb..bfa0b31d76 100644 --- a/tools/xtask/Cargo.toml +++ b/tools/xtask/Cargo.toml @@ -29,7 +29,6 @@ proc-macro2 = { version = "1", features = ["span-locations"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip", "raw_value"] } sha2 = "0.11" -base64 = "0.22" syn = { version = "2", features = ["full", "visit"] } thiserror = "2" tempfile = "3" diff --git a/tools/xtask/src/automation/agentx/fleet.rs b/tools/xtask/src/automation/agentx/fleet.rs deleted file mode 100644 index 26ede0e7fb..0000000000 --- a/tools/xtask/src/automation/agentx/fleet.rs +++ /dev/null @@ -1,402 +0,0 @@ -//! Fleet fan-out for AgentX benchmarks: one manifest, many machines, everything pinned. -//! -//! `fleet` validates a manifest, pre-flights every kit URL (fresh CDN uploads can take -//! minutes to reach every edge), generates one jy spec per run from the repo-owned -//! worker script, and submits them all. `fleet-status` reports per-job state for a -//! run root; `fleet-harvest` summarizes a completed run. The worker contract and the -//! fleet's hard-won operational rules are documented in -//! `.agents/skills/agentx-fleet-bench/SKILL.md`. -use crate::command::DynResult; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use std::collections::BTreeMap; -use std::path::Path; - -pub(super) const FLEET_USAGE: &str = - "automation agentx {fleet|fleet-status|fleet-harvest} --input PATH [--run-root DIR]"; - -#[derive(Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub(super) struct FleetManifest { - pub campaign: String, - pub product_source_commit: String, - /// Product repository; defaults to the public mesh-llm repository. - #[serde(default = "default_repo_url")] - pub repo_url: String, - pub mode: String, - pub corpus: Option, - pub runs: Vec, -} - -fn default_repo_url() -> String { - "https://github.com/Mesh-LLM/mesh-llm".to_string() -} - -#[derive(Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub(super) struct FleetCorpus { - pub repo: String, - pub rev: String, - pub sha256: String, -} - -#[derive(Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub(super) struct FleetRun { - pub model: String, - pub backend: String, - #[serde(default)] - pub probe: BTreeMap, - /// Model pin overrides; missing fields resolve from the run's model key via - /// the campaign env contract. - #[serde(default)] - pub model_pin: BTreeMap, -} - -fn positive_hex40(value: &str, field: &str) -> DynResult<()> { - if value.len() == 40 && value.bytes().all(|b| b.is_ascii_hexdigit()) { - return Ok(()); - } - Err(format!("{field} requires a full40-hex commit").into()) -} - -fn validate(manifest: &FleetManifest) -> DynResult<()> { - positive_hex40(&manifest.product_source_commit, "product_source_commit")?; - if !matches!(manifest.mode.as_str(), "smoke" | "comparison") { - return Err("mode must be smoke or comparison".into()); - } - if manifest.runs.is_empty() { - return Err("fleet manifest needs at least one run".into()); - } - if manifest.mode == "comparison" && manifest.corpus.is_none() { - return Err("comparison mode requires corpus pins".into()); - } - for run in &manifest.runs { - if !matches!(run.backend.as_str(), "cuda" | "metal") { - return Err(format!("run {} backend must be cuda or metal", run.model).into()); - } - } - Ok(()) -} - -/// Pre-flight: the pinned product commit must exist in the product repository -/// before any job is generated or submitted. -fn commit_exists(repo_url: &str, commit: &str) -> DynResult { - let output = std::process::Command::new("git") - .args(["ls-remote", repo_url]) - .output() - .map_err(|e| format!("git ls-remote {repo_url}: {e}"))?; - let text = String::from_utf8_lossy(&output.stdout); - Ok(text.contains(commit)) -} - -fn worker_script(root: &Path) -> DynResult { - let path = root.join("skippy/evals/agentx/fleet-worker.sh"); - std::fs::read_to_string(&path) - .map_err(|_| format!("fleet worker script missing: {}", path.display()))? - .lines() - // strip the shebang: the worker runs under bash from the spec command - .skip(1) - .collect::>() - .join("\n") - .pipe_ok() -} - -trait PipeOk { - fn pipe_ok(self) -> DynResult; -} - -impl PipeOk for String { - fn pipe_ok(self) -> DynResult { - Ok(self) - } -} - -fn hex64(value: &str) -> bool { - value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit()) -} - -/// Deterministic jy spec for one run. Model pins arrive fully resolved by the -/// caller (manifest overrides on top of the model catalog contract). -fn run_spec( - manifest: &FleetManifest, - run: &FleetRun, - worker_b64: &str, - worker_sha: &str, - pins: &BTreeMap, -) -> DynResult { - for field in [ - "MODEL_REPO", - "MODEL_REV", - "MODEL_FILE", - "MODEL_SHA", - "TOK_REPO", - "TOK_REV", - ] { - if !pins.contains_key(field) { - return Err(format!("run {} missing model pin {field}", run.model).into()); - } - } - let mut env = json!({ - "WORKER_B64": worker_b64, - "WORKER_SHA": worker_sha, - "MODE": manifest.mode, - "REPO_URL": manifest.repo_url, - "BACKEND": run.backend, - "CAMPAIGN": manifest.campaign, - "PRODUCT_COMMIT": manifest.product_source_commit, - }); - let env_obj = env.as_object_mut().unwrap(); - for (key, value) in pins { - env_obj.insert(key.clone(), json!(value)); - } - env_obj.insert("MODEL_KEY".into(), json!(run.model)); - env_obj.insert( - "THREADS".into(), - json!(run.probe.get("threads").copied().unwrap_or(20).to_string()), - ); - if let Some(corpus) = manifest.corpus.as_ref() { - if !hex64(&corpus.sha256) { - return Err("corpus sha256 must be 64-hex".into()); - } - env_obj.insert("CORPUS_REPO".into(), json!(corpus.repo)); - env_obj.insert("CORPUS_REV".into(), json!(corpus.rev)); - env_obj.insert("CORPUS_SHA".into(), json!(corpus.sha256)); - } - let mut probe = json!({ - "PROBE_CONVERSATIONS": run.probe.get("conversations").copied().unwrap_or(4).to_string(), - "PROBE_TURNS": run.probe.get("turns").copied().unwrap_or(4).to_string(), - "PROBE_BLOCK_CHARS": run.probe.get("block_chars").copied().unwrap_or(6300).to_string(), - "PROBE_MAX_TOKENS": run.probe.get("max_tokens").copied().unwrap_or(96).to_string(), - }); - for (key, value) in probe.as_object_mut().unwrap() { - env_obj.insert(key.clone(), json!(value)); - } - // Hardware placement only: the worker's arch and memory guards route the - // rest. Never target fleet nodes by name. - let target_os = if run.backend == "cuda" { - "linux" - } else { - "macos" - }; - Ok(json!({ - "name": format!("{} fleet {} {} ({})", manifest.campaign, run.model, run.backend, manifest.mode), - "priority": 70, - "target": {"executor": "lab", "os": target_os, "num_nodes": 1, "spot": false}, - "labels": {"campaign": manifest.campaign, "phase": manifest.mode, "backend": run.backend, "model": run.model}, - "harness": {"name": "custom", "version": format!("agentx-fleet-{}", manifest.mode), "trace": {"kind": "file", "ref": "sha256:".to_string() + &"0".repeat(64)}, "seed": 0, "warmup_requests": 0, "concurrency": [1], "request_count": 1, "duration_s": 86400, "percentiles": [50], "args": {}}, - "runtime": { - "model_package": {"ref": format!("none:{}", manifest.campaign), "egress": "lab_only"}, - "flags": {"scope": "build"}, - "command": "/bin/bash <<'ENTRY'\nfile=$TMPDIR/worker.sh\nprintf '%s' \"$WORKER_B64\" | base64 -d > \"$file\"\nprintf '%s %s\\n' \"$WORKER_SHA\" \"$file\" | shasum -a256 -c -\nexec /bin/bash \"$file\"\nENTRY", - "env": env, - "volumes": [] - }, - "budget": {"max_duration_s": 86400, "grace_s": 300, "max_usd": 0} - })) -} - -pub(super) fn command(root: &Path, args: &[String]) -> DynResult<()> { - let (verb, input) = match args.first().map(String::as_str) { - Some("fleet") => ( - "fleet", - args.get(1).filter(|f| *f == "--input").and(args.get(2)), - ), - Some("fleet-status") => ( - "fleet-status", - args.get(1).filter(|f| *f == "--run-root").and(args.get(2)), - ), - _ => return Err(FLEET_USAGE.into()), - }; - match (verb, input) { - ("fleet", Some(path)) => submit(root, Path::new(path)), - ("fleet-status", Some(run_root)) => status(Path::new(run_root)), - _ => Err(FLEET_USAGE.into()), - } -} - -fn submit(root: &Path, manifest_path: &Path) -> DynResult<()> { - let manifest: FleetManifest = serde_json::from_slice( - &crate::automation::receipt_files::bounded(manifest_path, 1024 * 1024)?, - )?; - validate(&manifest)?; - let script = worker_script(root)?; - use sha2::{Digest, Sha256}; - let worker_sha = hex(&Sha256::digest(script.as_bytes())); - let worker_b64 = { - use base64::Engine; - base64::engine::general_purpose::STANDARD.encode(script.as_bytes()) - }; - let run_root = root.join("target/agentx-fleet").join(&manifest.campaign); - std::fs::create_dir_all(&run_root)?; - if !commit_exists(&manifest.repo_url, &manifest.product_source_commit)? { - return Err(format!( - "pre-flight failed: commit {} not found in {}", - &manifest.product_source_commit[..12.min(manifest.product_source_commit.len())], - manifest.repo_url - ) - .into()); - } - let mut resolved = Vec::new(); - for run in &manifest.runs { - resolved.push((run, resolve_pins(root, run)?)); - } - let mut submitted = Vec::new(); - for (run, pins) in resolved { - let spec = run_spec(&manifest, run, &worker_b64, &worker_sha, &pins)?; - let path = run_root.join(format!("spec-{}-{}.json", run.model, run.backend)); - std::fs::write(&path, serde_json::to_vec_pretty(&json!({"spec": spec}))?)?; - let output = std::process::Command::new("jy") - .arg("submit") - .arg(&path) - .output() - .map_err(|e| format!("jy submit: {e}"))?; - let text = String::from_utf8_lossy(&output.stdout).to_string(); - let job = text - .lines() - .find(|l| l.starts_with("job")) - .and_then(|l| l.split_whitespace().nth(1)) - .ok_or_else(|| { - format!( - "jy submit rejected {}: {}", - path.display(), - String::from_utf8_lossy(&output.stderr) - ) - })?; - submitted - .push(json!({"model": run.model, "backend": run.backend, "job": job, "spec": path})); - } - let ledger = json!({"campaign": manifest.campaign, "mode": manifest.mode, "runs": submitted}); - std::fs::write( - run_root.join("fleet.json"), - serde_json::to_vec_pretty(&ledger)?, - )?; - println!( - "fleet: {} runs submitted under {}", - submitted.len(), - run_root.display() - ); - Ok(()) -} - -fn status(run_root: &Path) -> DynResult<()> { - let ledger: Value = serde_json::from_slice(&std::fs::read(run_root.join("fleet.json"))?)?; - for run in ledger["runs"].as_array().unwrap_or(&Vec::new()) { - let job = run["job"].as_str().unwrap_or_default(); - let output = std::process::Command::new("jy") - .arg("job") - .arg(job) - .output()?; - let text = String::from_utf8_lossy(&output.stdout).to_string(); - let state = text - .lines() - .find(|l| l.contains("\"status\"")) - .and_then(|l| l.split('"').nth(3)) - .unwrap_or("unknown"); - println!( - "{} {:8} {}", - run["model"].as_str().unwrap_or("?"), - run["backend"].as_str().unwrap_or("?"), - state - ); - } - Ok(()) -} - -fn resolve_pins(root: &Path, run: &FleetRun) -> DynResult> { - // Model pins live in the same shape the campaign specs use, kept in the - // manifest directory as models.json so a manifest is self-contained. - let catalog_path = root.join("skippy/evals/agentx/fleet-models.json"); - let catalog: BTreeMap> = - serde_json::from_slice(&std::fs::read(&catalog_path)?) - .map_err(|e| format!("{}: {e}", catalog_path.display()))?; - let mut pins = catalog.get(&run.model).cloned().unwrap_or_default(); - for (key, value) in &run.model_pin { - pins.insert(key.clone(), value.clone()); - } - Ok(pins) -} - -fn hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn manifest() -> FleetManifest { - serde_json::from_value(json!({ - "campaign": "test-20260101", - "product_source_commit": "e821ec38b1479cc2dd41da40e1b46e90b4a29850", - "mode": "smoke", - "runs": [{"model": "qwen3-4b", "backend": "cuda"}] - })) - .unwrap() - } - - #[test] - fn fleet_manifest_rejects_bad_commit_and_modes() { - let mut bad = manifest(); - bad.product_source_commit = "short".into(); - assert!(validate(&bad).is_err()); - let mut mode = manifest(); - mode.mode = "quick".into(); - assert!(validate(&mode).is_err()); - } - - #[test] - fn fleet_specs_target_hardware_never_node_names() { - let m = manifest(); - let pins = BTreeMap::from([ - ( - "MODEL_REPO".to_string(), - "unsloth/Qwen3-4B-Instruct-2507-GGUF".to_string(), - ), - ( - "MODEL_REV".to_string(), - "a06e946bb6b655725eafa393f4a9745d460374c9".to_string(), - ), - ( - "MODEL_FILE".to_string(), - "Qwen3-4B-Instruct-2507-Q4_K_M.gguf".to_string(), - ), - ("MODEL_SHA".to_string(), "f".repeat(64)), - ( - "TOK_REPO".to_string(), - "Qwen/Qwen3-4B-Instruct-2507".to_string(), - ), - ( - "TOK_REV".to_string(), - "cdbee75f17c01a7cc42f958dc650907174af0554".to_string(), - ), - ]); - let spec = run_spec(&m, &m.runs[0], "dzByaw==", &"c".repeat(64), &pins).unwrap(); - assert_eq!(spec["target"]["os"], "linux"); - assert!( - spec["target"].get("nodes").is_none(), - "hardware targeting only" - ); - assert_eq!(spec["runtime"]["env"]["MODE"], "smoke"); - assert_eq!( - spec["runtime"]["env"]["REPO_URL"], - "https://github.com/Mesh-LLM/mesh-llm" - ); - assert_eq!(spec["runtime"]["env"]["PROBE_TURNS"], "4"); - } - - #[test] - fn comparison_requires_corpus_pins() { - let mut m = manifest(); - m.mode = "comparison".into(); - assert!( - validate(&m).is_err(), - "comparison without corpus pins must fail" - ); - } - - #[test] - fn smoke_manifest_accepts_without_corpus() { - assert!(validate(&manifest()).is_ok()); - } -} diff --git a/tools/xtask/src/automation/agentx/lifecycle.rs b/tools/xtask/src/automation/agentx/lifecycle.rs index f00150ca29..ce9d2751ba 100644 --- a/tools/xtask/src/automation/agentx/lifecycle.rs +++ b/tools/xtask/src/automation/agentx/lifecycle.rs @@ -18,8 +18,6 @@ const LLAMA_KV_UNIFIED_ENV: &str = "AGENTX_LLAMA_KV_UNIFIED"; const SKIPPY_KV_UNIFIED_ENV: &str = "AGENTX_SKIPPY_KV_UNIFIED"; const SKIPPY_MICROBATCH_TOKENS_ENV: &str = "AGENTX_SKIPPY_MICROBATCH_TOKENS"; const SKIPPY_GENERATION_CONCURRENCY_ENV: &str = "AGENTX_SKIPPY_GENERATION_CONCURRENCY"; -const SKIPPY_PREFIX_CACHE_BUDGET_ENV: &str = "AGENTX_SKIPPY_PREFIX_CACHE_BUDGET"; -const SKIPPY_PREFIX_CACHE_RAM_ENV: &str = "AGENTX_SKIPPY_PREFIX_CACHE_RAM"; const BASELINE_MICROBATCH_TOKENS: usize = 512; const TELEMETRY_FILE: &str = "skippy-telemetry.otlp.jsonl"; const BATCH_TOKENS: usize = 2_048; @@ -115,17 +113,6 @@ fn positive_override(name: &str, value: &str) -> DynResult { } } -/// Text-valued env override for IEC byte budgets (`64GiB`) and other raw -/// settings values that are passed through verbatim after presence check. -fn text_env_override(name: &str) -> DynResult> { - match std::env::var(name) { - Ok(value) if !value.trim().is_empty() => Ok(Some(value.trim().to_string())), - Ok(_) => Err(format!("{name} must not be empty").into()), - Err(std::env::VarError::NotPresent) => Ok(None), - Err(error) => Err(format!("{name}: {error}").into()), - } -} - fn positive_env_override(name: &str) -> DynResult> { match std::env::var(name) { Ok(value) => positive_override(name, &value).map(Some), @@ -160,38 +147,10 @@ fn skippy_diagnostic_arguments(generation_concurrency: Option) -> Vec, - ram: Option, -) -> Vec { - let mut arguments = Vec::new(); - if let Some(budget) = budget { - arguments.extend(["--prefix-cache-budget".to_string(), budget]); - } - if let Some(ram) = ram { - arguments.extend(["--prefix-cache-ram".to_string(), ram]); - } - arguments -} - -fn skippy_prefix_cache_budget_override() -> DynResult> { - Ok(skippy_prefix_cache_budget_arguments( - text_env_override(SKIPPY_PREFIX_CACHE_BUDGET_ENV)?, - text_env_override(SKIPPY_PREFIX_CACHE_RAM_ENV)?, - )) -} - fn skippy_overrides() -> DynResult> { let mut arguments = skippy_diagnostic_arguments(positive_env_override(SKIPPY_GENERATION_CONCURRENCY_ENV)?); arguments.extend(skippy_kv_layout_override()?); - arguments.extend(skippy_prefix_cache_budget_override()?); Ok(arguments) } @@ -968,30 +927,6 @@ mod tests { } } - #[test] - fn skippy_prefix_cache_budget_overrides_target_distinct_budgets() { - // The exact-state retention cap and the resident-checkpoint RAM budget - // are different knobs; each env override must reach its own flag. - assert_eq!( - skippy_prefix_cache_budget_arguments(Some("64GiB".into()), None), - ["--prefix-cache-budget".to_string(), "64GiB".to_string()] - ); - assert_eq!( - skippy_prefix_cache_budget_arguments(None, Some("8GiB".into())), - ["--prefix-cache-ram".to_string(), "8GiB".to_string()] - ); - assert_eq!( - skippy_prefix_cache_budget_arguments(Some("unbounded".into()), Some("off".into())), - [ - "--prefix-cache-budget".to_string(), - "unbounded".to_string(), - "--prefix-cache-ram".to_string(), - "off".to_string() - ] - ); - assert!(skippy_prefix_cache_budget_arguments(None, None).is_empty()); - } - #[test] fn llama_cache_budget_control_is_explicit_and_rejects_invalid_values() { assert_eq!(parse_llama_cache_ram_mib("65536").unwrap(), 65536); diff --git a/tools/xtask/src/automation/agentx/mod.rs b/tools/xtask/src/automation/agentx/mod.rs index fe801d2c0a..98beb9ebfb 100644 --- a/tools/xtask/src/automation/agentx/mod.rs +++ b/tools/xtask/src/automation/agentx/mod.rs @@ -11,7 +11,6 @@ mod context_support; mod final_sweep; #[cfg(test)] mod final_sweep_tests; -mod fleet; mod hardware; mod inputs; mod lifecycle; @@ -122,13 +121,6 @@ pub(crate) fn run(args: &[String]) -> DynResult<()> { ) { return final_sweep::command(args); } - if matches!( - args.first().map(String::as_str), - Some("fleet" | "fleet-status") - ) { - let root = std::env::current_dir()?; - return fleet::command(&root, args); - } if args.first().map(String::as_str) != Some("worker") { return Err("AgentX accepts comparison --input JSON --output DIR or mlflow-export; legacy unpinned launch modes are not admitted".into()); } From 012de4ef3ea194941cf0be3a2f427fcd6cbf26dc Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:11:17 +1100 Subject: [PATCH 75/81] fix(skippy): restore the hybrid checkpoint test from its page and recurrent state skippy_sampling_history_granitehybrid_state restored a session from skippy_export_recurrent_state alone. Patch 0017 made that export the recurrent half only, with the attention cells carried by the KV page, so the restored session had no attention cells and the page export failed with "requested token position is not present in the KV cache". The test runs in the Windows Skippy probes job, which had been cancelled on every earlier run. The test now restores the page and the recurrent state together, as the resident cache does, and still requires the restored page and next-token logits to match an uninterrupted prefill exactly. The change is folded into patch 0017; a cold replay of the queue gives the same tree. --- ...esident-prefixes-as-shared-cells-plu.patch | 92 +++++++++++++++++-- 1 file changed, 86 insertions(+), 6 deletions(-) diff --git a/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch b/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch index 03994a56b3..db5f8efa86 100644 --- a/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch +++ b/skippy/llama_cpp/patches/0017-skippy-restore-resident-prefixes-as-shared-cells-plu.patch @@ -62,8 +62,8 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y src/skippy/state_memory.cpp | 21 +- src/skippy/tests/resident_checkpoint_gpu.cpp | 287 ++++++++++++ .../tests/resident_checkpoint_writer.cpp | 126 +++++ - src/skippy/tests/sampling_history.cpp | 387 ++++++++++++++- - 15 files changed, 1326 insertions(+), 487 deletions(-) + src/skippy/tests/sampling_history.cpp | 437 +++++++++++++++-- + 15 files changed, 1337 insertions(+), 526 deletions(-) create mode 100644 src/skippy/resident_prefix.cpp create mode 100644 src/skippy/tests/resident_checkpoint_gpu.cpp create mode 100644 src/skippy/tests/resident_checkpoint_writer.cpp @@ -1766,7 +1766,7 @@ index 000000000..d08029062 + return 0; +} diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 0c81c9d47..4c7c891e1 100644 +index 0c81c9d47..16582f6b2 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -5,26 +5,115 @@ @@ -1917,7 +1917,87 @@ index 0c81c9d47..4c7c891e1 100644 void prefill(skippy_session * session, const std::vector & tokens) { size_t bytes = 0; skippy_error * error = nullptr; -@@ -570,6 +684,174 @@ void state_round_trip(skippy_model * model) { +@@ -465,33 +579,6 @@ std::vector export_page(skippy_session * session, size_t token_count) { + return payload; + } + +-std::vector export_recurrent(skippy_session * session) { +- skippy_error * error = nullptr; +- size_t bytes = 0; +- auto status = skippy_export_recurrent_state(session, nullptr, 0, &bytes, &error); +- CHECK(status == SKIPPY_STATUS_BUFFER_TOO_SMALL || status == SKIPPY_STATUS_OK); +- skippy_error_free(error); +- error = nullptr; +- std::vector payload(bytes); +- status = skippy_export_recurrent_state(session, payload.data(), payload.size(), &bytes, &error); +- ok(status, error); +- payload.resize(bytes); +- return payload; +-} +- +-void restore_recurrent(skippy_session * session, const std::vector & payload, +- const std::vector & prefix) { +- skippy_error * error = nullptr; +- auto status = skippy_import_recurrent_state(session, payload.data(), payload.size(), &error); +- ok(status, error); +- error = nullptr; +- status = skippy_session_set_position(session, prefix.size(), &error); +- ok(status, error); +- error = nullptr; +- status = skippy_session_restore_token_history(session, prefix.data(), prefix.size(), &error); +- ok(status, error); +-} +- + skippy_sampling_config greedy_config() { + skippy_sampling_config config{}; + config.version = 1; +@@ -519,26 +606,25 @@ std::vector decode_logits(skippy_session * session, llama_token token) { + } + + // A declared-exact stage checkpoint must be reconstructible from its export +-// alone. LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY is an alias of +-// LLAMA_STATE_SEQ_FLAGS_SWA_ONLY: it writes the recurrent and sliding-window +-// half of a hybrid memory and nothing from a full-attention KV cache, so a +-// session restored from that half carries no full-attention cells and decodes a +-// different continuation from an uninterrupted prefill. Compare the attention +-// page the restored session exposes with the source's page, and the next-token +-// logits of a restored prefix with those of the same prefix prefilled from +-// scratch. ++// alone. A hybrid stage's checkpoint is the pair the resident cache keeps: the ++// attention page and the recurrent state. The recurrent state holds nothing ++// from a full-attention KV cache, so a session restored from it alone carries ++// no full-attention cells and decodes a different continuation from an ++// uninterrupted prefill. Compare the attention page the restored session ++// exposes with the source's page, and the next-token logits of a restored ++// prefix with those of the same prefix prefilled from scratch. + void state_round_trip(skippy_model * model) { + const std::vector prefix(128, 1); + auto * source = create(model); + prefill(source, prefix); + const auto source_page = export_page(source, prefix.size()); + CHECK(!source_page.empty()); +- const auto recurrent = export_recurrent(source); +- CHECK(!recurrent.empty()); ++ const snapshot checkpoint(source, false); ++ CHECK(!checkpoint.recurrent.empty()); + release(source); + + auto * restored = create(model); +- restore_recurrent(restored, recurrent, prefix); ++ checkpoint.restore(restored, prefix); + const auto restored_page = export_page(restored, prefix.size()); + CHECK(restored_page.size() == source_page.size()); + CHECK(std::memcmp(restored_page.data(), source_page.data(), source_page.size()) == 0); +@@ -551,7 +637,7 @@ void state_round_trip(skippy_model * model) { + const auto cold_logits = decode_logits(cold, suffix.back()); + release(cold); + auto * warm = create(model); +- restore_recurrent(warm, recurrent, prefix); ++ checkpoint.restore(warm, prefix); + prefill(warm, suffix); + const auto warm_logits = decode_logits(warm, suffix.back()); + release(warm); +@@ -570,6 +656,174 @@ void state_round_trip(skippy_model * model) { CHECK(max_delta == 0.0f); } @@ -2092,7 +2172,7 @@ index 0c81c9d47..4c7c891e1 100644 void adapter_contracts(skippy_model * model) { auto * session = create(model); prefill(session, {1, 2}); -@@ -626,24 +908,118 @@ void adapter_contracts(skippy_model * model) { +@@ -626,24 +880,118 @@ void adapter_contracts(skippy_model * model) { release(session); } @@ -2215,7 +2295,7 @@ index 0c81c9d47..4c7c891e1 100644 // A dense stage's page already carries its whole checkpoint, so the // partial side payload is intentionally empty there. CHECK(require_recurrent); -@@ -673,5 +1049,8 @@ int main(int argc, char ** argv) { +@@ -673,5 +1021,8 @@ int main(int argc, char ** argv) { error = nullptr; const auto freed = skippy_model_free(model, &error); ok(freed, error); From f8c9800b0780f536fbbc63fe04df2c64f3c53e2d Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:21:58 +1100 Subject: [PATCH 76/81] fix(skippy): record the patch queue digest after the hybrid checkpoint test fix --- skippy/crates/skippy-api/src/split-certified.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 7706b3ad1b..a3234ae957 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "5659eb387c80f91a21a0760103817ec959a8cc98c531e69110e03e2a93c7d21d" + "patch_queue_sha256": "3a02d72808e96026b3b4e3ccbfed64a795681d3d03af7617d668f2aadcf774af" }, "architectures": [ "afmoe", From 678d162bdc29627a44623a804a1dec6339df042a Mon Sep 17 00:00:00 2001 From: Michael Neale <14976+michaelneale@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:41:27 +1100 Subject: [PATCH 77/81] fix(skippy): recheck model content when file stamps fall inside the timestamp tick Coarse ctime/mtime clocks (ext4 on Linux CI) let a same-length rewrite keep an identical stamp. Stamps younger than 2s now hash before load and rehash in still_matches instead of trusting metadata. --- .../src/runtime_state/model_content.rs | 50 ++++++++++++++++--- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs index c785c78248..d1e6747b92 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -16,8 +16,15 @@ type ObservedFiles = Vec<(String, PathBuf, FileStamp)>; pub(crate) struct VerifiedModelContent { digest: String, files: ObservedFiles, + /// A stamp written within the timestamp-granularity window can hide a + /// same-length rewrite, so such proofs are rechecked by content. + racy: bool, } +/// Coarse filesystem clocks (e.g. ext4 ctime ticks) can leave a rewrite in the +/// same tick with an identical stamp; treat recent stamps as untrusted. +const RACY_STAMP_WINDOW: std::time::Duration = std::time::Duration::from_secs(2); + #[derive(Clone, PartialEq, Eq)] struct FileStamp { bytes: u64, @@ -44,6 +51,29 @@ impl FileStamp { ), } } + + fn is_racy(&self, now: SystemTime) -> bool { + #[cfg(unix)] + let changed = u64::try_from(self.identity.2).ok().map(|secs| { + SystemTime::UNIX_EPOCH + + std::time::Duration::new(secs, self.identity.3.clamp(0, 999_999_999) as u32) + }); + #[cfg(not(unix))] + let changed = None; + [self.modified, self.created, changed] + .into_iter() + .any(|time| match time { + Some(time) => now + .duration_since(time) + .map_or(true, |age| age < RACY_STAMP_WINDOW), + None => true, + }) + } +} + +fn any_racy(files: &ObservedFiles) -> bool { + let now = SystemTime::now(); + files.iter().any(|(_, _, stamp)| stamp.is_racy(now)) } impl VerifiedModelContent { @@ -56,6 +86,12 @@ impl VerifiedModelContent { ) -> Result<(T, Option)> { #[cfg(unix)] let (model, content) = match Self::observe_files(config).ok().flatten() { + // Recent stamps cannot prove the bytes the loader reads, so hash + // before load and recheck content afterwards instead. + Some(files) if any_racy(&files) => { + let content = Self::from_observed(files, &AtomicBool::new(false)).ok(); + (load()?, content) + } Some(files) => { verify_alongside_load(load, |cancelled| Self::from_observed(files, cancelled))? } @@ -87,13 +123,13 @@ impl VerifiedModelContent { capture_files(files).map(Some) } - #[cfg(any(not(unix), test))] fn from_files(files: Vec<(String, PathBuf)>) -> Result { Self::from_observed(capture_files(files)?, &AtomicBool::new(false)) } fn from_observed(files: ObservedFiles, cancelled: &AtomicBool) -> Result { let started = Instant::now(); + let racy = any_racy(&files); let mut verified_bytes = 0_u64; let mut digest = Sha256::new(); digest.update(b"skippy-loaded-model-content-v1\0"); @@ -146,6 +182,7 @@ impl VerifiedModelContent { Ok(Self { digest, files: observed, + racy, }) } @@ -167,14 +204,12 @@ impl VerifiedModelContent { if !unchanged { return false; } - #[cfg(unix)] - { - true + if cfg!(unix) && !self.racy { + return true; } - #[cfg(not(unix))] { - // Size and last-write timestamps are not a strong file identity on - // these platforms. Recheck actual content after model open and at + // Off Unix, and for stamps inside the racy window, size and + // timestamps are not a strong file identity. Recheck actual content after model open and at // backend construction rather than trusting preserved timestamps. Self::from_files(files).is_ok_and(|current| current.digest == self.digest) } @@ -408,6 +443,7 @@ mod tests { Ok(VerifiedModelContent { digest: "proof".into(), files: Vec::new(), + racy: false, }) }, ) From e6037b08eff292325c1d8366e9820276f4a750f3 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 20 Nov 2026 17:03:58 +1100 Subject: [PATCH 78/81] perf(skippy): defer batch synchronization to export time for CPU/GPU overlap (#3114) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What this changes Moves `skippy_synchronize_context_if_pending()` from immediately after `llama_decode()` to just before the export/sampling loop that actually consumes GPU results. The CPU returns to the scheduler and prepares the next chunk while the GPU still executes the current one. ## Why The nsys CUDA timelines (PR #3098) showed GPU kernels run at identical speed (~233 ms) in both skippy and llama.cpp during prefill of a 1571-token prompt, but skippy spends 502 ms on CPU vs llama's 110 ms — the GPU sits idle waiting. The immediate sync after every `llama_decode()` call was the pipeline stall. ## Expected impact ~200-300 ms TTFT recovery on the ~388 ms gap. This is a one-line deferral — the sync still happens before results are consumed, just not before the CPU has done useful work. ## Measurement Stacked on #3098. Fleet benchmark measuring TTFT before/after will be attached. --------- Co-authored-by: James Dumay Co-authored-by: Michael Neale <14976+michaelneale@users.noreply.github.com> Co-authored-by: Melkor --- .../skippy-api/src/split-certified.json | 2 +- .../src/frontend/generation/queue.rs | 10 + .../src/runtime_state/lane_lifecycle.rs | 215 ++++++++++++++- .../lane_lifecycle/tests/generation_warmup.rs | 77 ++++++ ...ize-admitted-stages-from-live-graphs.patch | 26 +- ...cover-live-graph-and-state-contracts.patch | 247 +++++++++++++++++- ...efer-batch-synchronization-to-export.patch | 57 ++++ ...-reserving-the-sched-on-sampler-deta.patch | 63 +++++ skippy/scripts/build-llama.sh | 1 + 9 files changed, 673 insertions(+), 25 deletions(-) create mode 100644 skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch create mode 100644 skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index a3234ae957..52501ebc89 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "3a02d72808e96026b3b4e3ccbfed64a795681d3d03af7617d668f2aadcf774af" + "patch_queue_sha256": "4e600c9baec470f3a7d19da3223535e5609c5ab458f54d65bec06167763da7c5" }, "architectures": [ "afmoe", diff --git a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs index 22886d5687..9902b84081 100644 --- a/skippy/crates/skippy-serving/src/frontend/generation/queue.rs +++ b/skippy/crates/skippy-serving/src/frontend/generation/queue.rs @@ -811,6 +811,16 @@ pub(in crate::frontend) fn prewarm_generation_sessions( let timer = PhaseTimer::start(); let mut runtime = lock_runtime(runtime); let generation_graph_warmed = runtime.warmup_generation_graph()?; + // The one-token warmup above does not reserve the graphs real traffic + // uses: the first full prefill ubatch and the first concurrent decode + // wave each grow the reservation mid-request. Warm the serving shapes + // now so no request pays the graph growth. + let warmup_prefill_tokens = config + .n_ubatch + .or(config.n_batch) + .unwrap_or(512) + .min(config.ctx_size.saturating_sub(64)) as usize; + runtime.warmup_serving_shapes(warmup_prefill_tokens)?; let sessions = runtime.prewarm_idle_sessions(generation_concurrency)?; let mut attrs = lifecycle_attrs(config); attrs.insert( diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 02a92a2098..affe513f64 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs @@ -68,19 +68,7 @@ impl RuntimeState { } pub(crate) fn warmup_generation_graph(&mut self) -> Result { - // Prewarming invokes decode_step. Encode-only models cannot decode, - // and encoder-decoder models must encode a source first. - if self.model.workload_info()?.kind != ModelWorkload::CausalGeneration { - return Ok(false); - } - if self.model.input_activation_boundary().is_some() - || self.model.output_activation_boundary().is_some() - { - return Ok(false); - } - // DiffusionGemma runs non-causally with no KV memory, so a decode - // step has no graph to warm and the reset would fail. - if self.serves_system_one() { + if !self.can_warm_generation_graph() { return Ok(false); } let token_id = self @@ -109,6 +97,207 @@ impl RuntimeState { Ok(true) } + /// Whether [`Self::warmup_generation_graph`] can run for this runtime. + fn can_warm_generation_graph(&self) -> bool { + // Prewarming invokes decode_step. Encode-only models cannot decode, + // and encoder-decoder models must encode a source first. + if !matches!( + self.model.workload_info().map(|info| info.kind), + Ok(ModelWorkload::CausalGeneration) + ) { + return false; + } + if self.model.input_activation_boundary().is_some() + || self.model.output_activation_boundary().is_some() + { + return false; + } + // DiffusionGemma runs non-causally with no KV memory, so a decode + // step has no graph to warm and the reset would fail. + !self.serves_system_one() + } + + /// Reserve the compute graphs serving will actually use before the first + /// request pays for them. [`Self::warmup_generation_graph`] exercises a + /// one-token single-sequence decode; the first real prefill and the first + /// concurrent decode wave each need a larger graph, and the native + /// runtime's lazy graph reservation charges that growth to the request + /// that triggers it (a 314 ms `sched_reserve` on a GB10 spark for the + /// first full ubatch). Warm both serving shapes at startup instead: one + /// single-session prefill capped to the loaded batch limit, then one + /// one-token decode wave within that limit. Best-effort: a model that cannot run the + /// larger shapes still serves, keeping the lazy reservation. + pub(crate) fn warmup_serving_shapes(&mut self, prefill_tokens: usize) -> Result<()> { + if !self.can_warm_generation_graph() || prefill_tokens == 0 { + return Ok(()); + } + let token_id = self + .model + .tokenize("", true)? + .into_iter() + .next() + .unwrap_or(0); + self.warmup_prefill_shape(token_id, prefill_tokens); + self.warmup_concurrent_decode_shape(token_id); + Ok(()) + } + + fn warmup_prefill_shape(&mut self, token_id: i32, prefill_tokens: usize) { + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let mut lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(error) => { + tracing::warn!(?error, "serving prefill warmup could not borrow a lane"); + return; + } + }, + }; + let warmed = (|| { + // The native context clamps configured limits during loading. + let tokens = vec![token_id; prefill_tokens.min(lane.session.batch_size()?)]; + let request = IterationBatchRequest { + session: &mut lane.session, + token_ids: &tokens, + positions: &[], + sampling: None, + input: None, + // Real prefill chunks sample their final row: the graph the + // reservation must cover includes the output head, which a + // consumerless warmup iteration omits entirely. + sample_last: true, + phase: IterationBatchPhase::Prefill, + }; + StageSession::iteration_batch_sampled(&mut [request]).map(|_| ()) + })(); + let result = warmed.and_then(|_| lane.session.reset()); + if let Err(error) = self.finish_generation_warmup(lane, result, idle_index.is_some()) { + tracing::warn!( + ?error, + "serving prefill warmup failed; keeping lazy reservation" + ); + } + } + + fn warmup_concurrent_decode_shape(&mut self, token_id: i32) { + let mut lanes = Vec::new(); + let mut wave_limit = self.lane_count as usize; + while lanes.len() < wave_limit { + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(_) => break, + }, + }; + match lane.session.batch_size() { + Ok(batch_size) => wave_limit = wave_limit.min(batch_size), + Err(error) => { + let _ = self.finish_generation_warmup(lane, Err(error), false); + break; + } + } + lanes.push((lane, idle_index.is_some())); + } + if lanes.is_empty() { + return; + } + let mut requests = Vec::with_capacity(lanes.len()); + let warmup_sampling = SamplingConfig { + enabled: true, + temperature: 0.0, + ..SamplingConfig::default() + }; + // An empty metadata string clears chat sampling instead of + // configuring it (the native entry's early-out), so the attach the + // warmup exists to provoke never happened. A minimal grammar-free + // metadata document reaches the real configure path. + const WARMUP_SAMPLING_METADATA: &str = r#"{"grammar":""}"#; + for (lane, _) in lanes.iter_mut() { + // Real requests configure chat sampling through the frontend + // before their first iteration; that configuration is what + // attaches the backend sampler and grows the reservation. Walk + // the same entry here so the sampler-aware reservation is built + // at startup instead of on the first request. + if let Err(error) = lane.session.configure_chat_sampling( + WARMUP_SAMPLING_METADATA, + 0, + Some(&warmup_sampling), + ) { + tracing::warn!(?error, "serving warmup could not configure chat sampling"); + } + requests.push(IterationBatchRequest { + session: &mut lane.session, + token_ids: std::slice::from_ref(&token_id), + positions: &[], + // Real decode steps sample every iteration; warm the shape + // that includes the sampler's logits row, and attach the + // samplers so the sampler-aware graph reservation happens + // here rather than on the first request. + sampling: Some(&warmup_sampling), + input: None, + sample_last: true, + phase: IterationBatchPhase::Decode, + }); + } + let warmed = StageSession::iteration_batch_sampled(&mut requests).map(|_| ()); + if let Err(error) = &warmed { + tracing::warn!( + ?error, + "serving decode-wave warmup failed; keeping lazy reservation" + ); + } + for (mut lane, borrowed) in lanes { + // Only successfully warmed and reset borrowed lanes are reusable. + let result = lane.session.reset(); + if let Err(error) = + self.finish_generation_warmup(lane, result, borrowed && warmed.is_ok()) + { + tracing::warn!(?error, "serving decode-wave warmup cleanup failed"); + } + } + // Converge the sampler-aware reservation: sampling attaches happen + // after an iteration's decode, so the warmup so far can end with + // the re-reserve armed (or never consumed) and the reservation + // still sampler-less; the first request would then pay a + // worst-case graph re-reserve. One decode with a sampler attached + // guarantees the reservation is rebuilt sampler-aware (or confirmed + // already covering) before traffic arrives. + let idle_index = self + .idle_sessions + .iter() + .position(|idle| idle.resident_prefix.is_none()); + let mut lane = match idle_index { + Some(index) => self.idle_sessions.swap_remove(index), + None => match self.create_lane_session() { + Ok(lane) => lane, + Err(error) => { + tracing::warn!(?error, "sampler-aware warmup could not borrow a lane"); + return; + } + }, + }; + let converged = lane + .session + .configure_chat_sampling(WARMUP_SAMPLING_METADATA, 0, Some(&warmup_sampling)) + .and_then(|_| lane.session.decode_step(token_id)) + .and_then(|_| lane.session.reset()); + if let Err(error) = self.finish_generation_warmup(lane, converged, idle_index.is_some()) { + tracing::warn!( + ?error, + "sampler-aware warmup failed; keeping lazy reservation" + ); + } + } + fn finish_generation_warmup( &mut self, lane: RuntimeLaneSession, diff --git a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs index e7d68d4954..7c95628379 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs @@ -2,11 +2,19 @@ use super::*; fn fixture(lanes: u32) -> Result>> { + fixture_with_batch(lanes, None) +} + +fn fixture_with_batch(lanes: u32, batch: Option<(u32, u32)>) -> Result>> { let path = std::env::var_os("SKIPPY_WARMUP_STAGE_CONFIG") .context("set SKIPPY_WARMUP_STAGE_CONFIG to a full causal-model stage config")?; let mut config: StageConfig = serde_json::from_slice(&std::fs::read(path)?)?; config.lane_count = lanes; config.cache_idle_slots = None; + if let Some((n_batch, n_ubatch)) = batch { + config.n_batch = Some(n_batch); + config.n_ubatch = Some(n_ubatch); + } crate::runtime_state::load_runtime(&config)?.context("fixture must load a native model") } @@ -47,6 +55,74 @@ fn full_idle_pool_warms_repeatedly_and_all_lanes_still_decode() -> Result<()> { Ok(()) } +#[test] +#[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] +fn serving_shape_warmup_keeps_every_lane_usable() -> Result<()> { + for lanes in [1, 4] { + let runtime = fixture(lanes)?; + let mut runtime = runtime.lock().unwrap(); + runtime.prewarm_idle_sessions(lanes as usize)?; + runtime.warmup_serving_shapes(64)?; + // The shape warmup borrows and releases lanes; the pool must be + // whole again and every lane must still decode. + assert_eq!(runtime.idle_sessions.len(), lanes as usize); + assert!( + runtime + .idle_sessions + .iter() + .all(|lane| lane.session.token_count() == 0) + ); + let token = runtime.model.tokenize("Hello", true)?[0]; + let prediction = runtime + .session("shape-warmup-request")? + .decode_step(token)?; + assert!(prediction >= 0); + } + Ok(()) +} + +#[test] +#[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] +fn serving_shape_warmup_respects_loaded_batch_capacity() -> Result<()> { + // Cover clamped prefill and a decode wave at the batch limit. The native + // loader cannot construct a context with more lanes than batch tokens. + for (lanes, n_batch, n_ubatch) in [(4, 64, 512), (4, 4, 4)] { + let runtime = fixture_with_batch(lanes, Some((n_batch, n_ubatch)))?; + let mut runtime = runtime.lock().unwrap(); + runtime.prewarm_idle_sessions(lanes as usize)?; + assert_eq!( + runtime.idle_sessions[0].session.batch_size()?, + n_batch as usize + ); + for _ in 0..2 { + runtime.warmup_serving_shapes(n_ubatch as usize)?; + assert_eq!(runtime.idle_sessions.len(), lanes as usize); + assert!(runtime.free_lane_indices.is_empty()); + assert!( + runtime + .idle_sessions + .iter() + .all(|lane| lane.session.token_count() == 0) + ); + } + let token = runtime.model.tokenize("Hello", true)?[0]; + let mut predictions = Vec::new(); + for index in 0..lanes { + predictions.push( + runtime + .session(&format!("bounded-{index}"))? + .decode_step(token)?, + ); + } + assert!( + predictions + .iter() + .all(|prediction| *prediction == predictions[0]) + ); + } + Ok(()) +} + #[test] #[ignore = "requires SKIPPY_WARMUP_STAGE_CONFIG and a local causal GGUF"] fn temporary_warmup_releases_capacity_with_idle_pool_disabled() -> Result<()> { @@ -55,6 +131,7 @@ fn temporary_warmup_releases_capacity_with_idle_pool_disabled() -> Result<()> { runtime.max_idle_sessions = Some(0); for _ in 0..3 { assert!(runtime.warmup_generation_graph()?); + runtime.warmup_serving_shapes(64)?; assert!(runtime.idle_sessions.is_empty()); assert_eq!(runtime.next_lane_index, 1); assert_eq!(runtime.free_lane_indices, [0]); diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 03e358678c..e4cff0e14b 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -1,8 +1,9 @@ -From 1fc84889eba64be3be623ac2dadb8ccf82e53fe3 Mon Sep 17 00:00:00 2001 +From 48b4b40f4ae12d1afc0a62bcc99fcfc7727da4b3 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 -Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs +Subject: [PATCH] feat(skippy): realize admitted stages from live graphs +Co-authored-by: Melkor --- common/common.cpp | 109 --- common/common.h | 20 +- @@ -23,7 +24,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/llama-memory-hybrid-idx.cpp | 10 + src/llama-memory-hybrid-idx.h | 4 + src/skippy/abi.cpp | 59 ++ - src/skippy/activation.cpp | 1028 ++++++++++++++++++++ + src/skippy/activation.cpp | 1028 +++++++++++++++++++ src/skippy/activation_internal.h | 88 ++ src/skippy/activation_layout.cpp | 164 ++++ src/skippy/block_boundaries.cpp | 64 ++ @@ -50,7 +51,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/model_lifecycle.cpp | 155 +++ src/skippy/model_load_config.cpp | 213 ++++ src/skippy/model_load_config_internal.h | 35 + - src/skippy/model_loading.cpp | 1189 +++++++++++++++++++++++ + src/skippy/model_loading.cpp | 1189 ++++++++++++++++++++++ src/skippy/model_loading_internal.h | 38 + src/skippy/model_package.cpp | 782 +++++++++++++++ src/skippy/model_source.cpp | 463 +++++++++ @@ -73,7 +74,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/stage_realization.h | 21 + src/skippy/stage_slice_plan.cpp | 907 +++++++++++++++++ src/skippy/stage_slice_plan.h | 136 +++ - src/skippy/state.cpp | 1189 +++++++++++++++++++++++ + src/skippy/state.cpp | 1195 +++++++++++++++++++++++ src/skippy/state_effects.cpp | 450 +++++++++ src/skippy/state_effects.h | 74 ++ src/skippy/state_memory.cpp | 116 +++ @@ -83,7 +84,7 @@ Subject: [PATCH 02/32] feat(skippy): realize admitted stages from live graphs src/skippy/workloads.cpp | 373 +++++++ src/skippy/workloads_internal.h | 8 + tests/test-batch-alloc.cpp | 21 + - 79 files changed, 16496 insertions(+), 407 deletions(-) + 79 files changed, 16502 insertions(+), 407 deletions(-) create mode 100644 common/log-terminal.cpp create mode 100644 common/regex-escape.cpp create mode 100644 common/sampling-config.cpp @@ -15213,10 +15214,10 @@ index 000000000..1cb24c7cb + std::string & error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp new file mode 100644 -index 000000000..f035ea13f +index 000000000..d4a5c9673 --- /dev/null +++ b/src/skippy/state.cpp -@@ -0,0 +1,1189 @@ +@@ -0,0 +1,1195 @@ +#include "skippy/state.h" +#include "skippy/state_memory.h" +#include "skippy/errors.h" @@ -15822,6 +15823,9 @@ index 000000000..f035ea13f + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session, descriptor, and payload are required"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } ++ // Imports can write host-visible KV buffers before any backend submission. ++ session->ctx->synchronize(); ++ skippy_mark_context_synchronized(session->stage_model); + std::string error; + bool ok = false; + bool invalid_argument = false; @@ -15885,6 +15889,9 @@ index 000000000..f035ea13f + return SKIPPY_STATUS_INVALID_ARGUMENT; + } + ++ // Fence before either cache mutation or composite-import rollback. ++ session->ctx->synchronize(); ++ skippy_mark_context_synchronized(session->stage_model); + std::string error; + bool ok = false; + bool unsupported = false; @@ -17958,3 +17965,6 @@ index c41e91d61..eee60d81d 100644 t.test("token_batch_explicit_fields", [&](testing & t) { llama_token token[3] = { 5, 6, 7 }; llama_pos pos[3] = { 3, 4, 5 }; +-- +2.54.0 (Apple Git-157) + diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 67abef0157..4a36fdd188 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -1,9 +1,12 @@ -From bf3f7c50c6f91dec75704e4c79bbe91f8f4542bb Mon Sep 17 00:00:00 2001 +From 5d84a67de94d53a20831950c3189ccbee0e1dc0c Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:43 +1100 -Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts +Subject: [PATCH] test(skippy): cover live graph and state contracts +Co-authored-by: Melkor --- + src/CMakeLists.txt | 9 + + src/skippy/tests/async_state.cpp | 208 ++ .../tests/cast_destination_regression.h | 27 + src/skippy/tests/embedding_input_regression.h | 91 + src/skippy/tests/graph_build_inputs.cpp | 948 ++++++++++ @@ -42,7 +45,8 @@ Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts tests/test-skippy-rerank-template.cpp | 34 + tests/test-skippy-sampling-suppress.cpp | 90 + ...st-skippy-verify-checkpoint-retirement.cpp | 26 + - 38 files changed, 10272 insertions(+), 30 deletions(-) + 40 files changed, 10489 insertions(+), 30 deletions(-) + create mode 100644 src/skippy/tests/async_state.cpp create mode 100644 src/skippy/tests/cast_destination_regression.h create mode 100644 src/skippy/tests/embedding_input_regression.h create mode 100644 src/skippy/tests/graph_build_inputs.cpp @@ -76,6 +80,240 @@ Subject: [PATCH 06/32] test(skippy): cover live graph and state contracts create mode 100644 tests/test-skippy-sampling-suppress.cpp create mode 100644 tests/test-skippy-verify-checkpoint-retirement.cpp +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 2bc7d6f6e..dc8465589 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -270,6 +270,15 @@ if (LLAMA_STAGE_BUILD_TESTS) + set_tests_properties(skippy_runtime_event_native_model_load_production PROPERTIES + FIXTURES_REQUIRED skippy-model-loader-fixtures) + ++ add_executable(skippy-async-state-test skippy/tests/async_state.cpp) ++ target_include_directories(skippy-async-state-test PRIVATE .) ++ target_compile_features(skippy-async-state-test PRIVATE cxx_std_17) ++ target_link_libraries(skippy-async-state-test PRIVATE llama) ++ add_test(NAME skippy_async_state_contracts COMMAND skippy-async-state-test ++ "${SKIPPY_MODEL_FIXTURE_DIR}/gemma-dense.gguf") ++ set_tests_properties(skippy_async_state_contracts PROPERTIES ++ FIXTURES_REQUIRED skippy-model-loader-fixtures) ++ + add_executable(skippy-noalloc-graph-planning + skippy/tests/noalloc_graph_planning.cpp) + target_include_directories(skippy-noalloc-graph-planning PRIVATE .) +diff --git a/src/skippy/tests/async_state.cpp b/src/skippy/tests/async_state.cpp +new file mode 100644 +index 000000000..d74c28c8d +--- /dev/null ++++ b/src/skippy/tests/async_state.cpp +@@ -0,0 +1,208 @@ ++#include "../runtime_support.h" ++#include "../runtime_types.h" ++#include "../selected_logits.h" ++#include "skippy.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#define CHECK(condition) \ ++ do { \ ++ if (!(condition)) { \ ++ std::fprintf(stderr, "CHECK failed: %s (%s:%d)\n", #condition, __FILE__, __LINE__); \ ++ std::exit(1); \ ++ } \ ++ } while (0) ++ ++namespace { ++ ++void queue_prefill(skippy_session * session) { ++ const llama_token tokens[] = { 0, 1 }; ++ skippy_iteration_request request{}; ++ request.session = session; ++ request.token_ids = tokens; ++ request.token_count = 2; ++ size_t sampled = 0; ++ skippy_error * error = nullptr; ++ CHECK(skippy_iteration_batch_sampled(&request, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, &sampled, ++ &error) == SKIPPY_STATUS_OK); ++ CHECK(sampled == 0); ++ CHECK(session->stage_model->context_work_pending.load()); ++} ++ ++void test_import_error_fences(skippy_session * source, skippy_session * fresh) { ++ skippy_kv_page_desc page{}; ++ page.codec = UINT32_MAX; ++ const uint8_t payload = 0; ++ skippy_error * error = nullptr; ++ queue_prefill(source); ++ CHECK(skippy_import_kv_page(source, &page, &payload, 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ skippy_error_free(error); ++ error = nullptr; ++ ++ // A failed import has no trailing fence; it must drain the shared context ++ // before entering the mutation/rollback path, even on another lane. ++ queue_prefill(source); ++ skippy_cachegen_record_v1 record{}; ++ CHECK(skippy_import_cachegen_kv_page_v1(fresh, &page, &record, 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ skippy_error_free(error); ++} ++ ++void test_plain_restore_parity(skippy_session * source, skippy_session * target) { ++ skippy_error * error = nullptr; ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ queue_prefill(source); ++ skippy_kv_page_desc page{}; ++ size_t bytes = 0; ++ const int layers = source->stage_model->model->hparams.n_layer(); ++ CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, nullptr, 0, &bytes, &error) == ++ SKIPPY_STATUS_BUFFER_TOO_SMALL); ++ skippy_error_free(error); ++ error = nullptr; ++ CHECK(bytes > 0); ++ std::vector payload(bytes); ++ CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, payload.data(), payload.size(), &bytes, &error) == ++ SKIPPY_STATUS_OK); ++ ++ const int vocab = llama_vocab_n_tokens(llama_model_get_vocab(source->stage_model->model)); ++ const int selected = std::min(vocab, static_cast(SKIPPY_MAX_SELECTED_TOKENS)); ++ std::vector ids(selected); ++ for (int i = 0; i < selected; ++i) { ++ ids[i] = selected == 1 ? 0 : static_cast(i) * (vocab - 1) / (selected - 1); ++ } ++ std::vector reference(selected); ++ for (int attempt = 0; attempt < 9; ++attempt) { ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_reset(target, &error) == SKIPPY_STATUS_OK); ++ queue_prefill(source); ++ if (attempt == 0) { ++ source->ctx->synchronize(); ++ skippy_mark_context_synchronized(source->stage_model); ++ } ++ CHECK(skippy_import_kv_page(target, &page, payload.data(), payload.size(), &error) == SKIPPY_STATUS_OK); ++ CHECK(!source->stage_model->context_work_pending.load()); ++ std::vector scores(selected); ++ skippy_token_score_request readout{ ids.data(), ids.size(), scores.data() }; ++ const llama_token token = 2; ++ skippy_iteration_request request{}; ++ request.session = target; ++ request.token_ids = &token; ++ request.token_count = 1; ++ request.readout = &readout; ++ size_t sampled = 0; ++ CHECK(skippy_iteration_batch_sampled(&request, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, ++ &sampled, &error) == SKIPPY_STATUS_OK); ++ CHECK(sampled == 0); ++ if (attempt == 0) { ++ reference = scores; ++ } ++ for (int i = 0; i < selected; ++i) { ++ CHECK(std::isfinite(scores[i])); ++ CHECK(std::fabs(scores[i] - reference[i]) <= 1e-5f); ++ } ++ } ++ CHECK(skippy_session_reset(source, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_reset(target, &error) == SKIPPY_STATUS_OK); ++} ++ ++void decode_attached_samplers(skippy_session * first, skippy_session * second, llama_pos position) { ++ llama_batch batch = llama_batch_init(2, 0, 1); ++ batch.n_tokens = 2; ++ for (int i = 0; i < 2; ++i) { ++ batch.token[i] = 1; ++ batch.pos[i] = position; ++ batch.n_seq_id[i] = 1; ++ batch.seq_id[i][0] = i == 0 ? first->seq_id : second->seq_id; ++ batch.logits[i] = 1; ++ } ++ CHECK(llama_decode(first->ctx, batch) == 0); ++ first->ctx->synchronize(); ++ CHECK(llama_get_sampled_token_ith(first->ctx, 0) != LLAMA_TOKEN_NULL); ++ CHECK(llama_get_sampled_token_ith(first->ctx, 1) != LLAMA_TOKEN_NULL); ++ llama_batch_free(batch); ++} ++ ++void test_sampler_reservations(skippy_session * first, skippy_session * second) { ++ skippy_sampling_config sampling{}; ++ sampling.version = 1; ++ sampling.flags = SKIPPY_SAMPLING_FLAG_ENABLED; ++ sampling.repeat_penalty = 1.0f; ++ sampling.reasoning_budget_tokens = -1; ++ skippy_error * error = nullptr; ++ CHECK(skippy_session_configure_chat_sampling(first, &sampling, "{}", 0, &error) == SKIPPY_STATUS_OK); ++ CHECK(first->sampling_backend_enabled); ++ first->ctx->sched_reserve(); ++ uint64_t reserved = first->ctx->get_sched_reserve_count(); ++ ++ first->ctx->set_embeddings(true); ++ llama_sampler * shape_chain = llama_sampler_chain_init(llama_sampler_chain_default_params()); ++ llama_sampler_chain_add(shape_chain, llama_sampler_init_dist(42)); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, shape_chain)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ first->ctx->set_embeddings(false); ++ first->ctx->sched_reserve(); ++ reserved = first->ctx->get_sched_reserve_count(); ++ ++ CHECK(skippy_session_configure_chat_sampling(second, &sampling, "{}", 0, &error) == SKIPPY_STATUS_OK); ++ CHECK(second->sampling_backend_enabled); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ reserved = first->ctx->get_sched_reserve_count(); ++ ++ decode_attached_samplers(first, second, 0); ++ llama_sampler * replacement = llama_sampler_chain_init(llama_sampler_chain_default_params()); ++ llama_sampler_chain_add(replacement, llama_sampler_init_top_k(20)); ++ llama_sampler_chain_add(replacement, llama_sampler_init_dist(88)); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, replacement)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() > reserved); ++ decode_attached_samplers(first, second, 1); ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, nullptr)); ++ first->ctx->sched_reserve(); ++ llama_sampler_free(replacement); ++ llama_sampler_free(shape_chain); ++} ++ ++} // namespace ++ ++int main(int argc, char ** argv) { ++ CHECK(argc >= 2 && argc <= 4); ++ const char * mode = argc == 4 ? argv[3] : "all"; ++ CHECK(std::strcmp(mode, "all") == 0 || std::strcmp(mode, "imports") == 0 || std::strcmp(mode, "restore") == 0 || ++ std::strcmp(mode, "samplers") == 0); ++ skippy_runtime_config config = skippy_runtime_config_default(); ++ config.lane_count = 2; ++ config.n_batch = 64; ++ config.n_ubatch = 64; ++ config.selected_backend_device = argc >= 3 ? argv[2] : "CPU"; ++ config.n_gpu_layers = std::strcmp(config.selected_backend_device, "CPU") == 0 ? 0 : 99; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ CHECK(skippy_model_open(argv[1], &config, &model, &error) == SKIPPY_STATUS_OK); ++ skippy_session * first = nullptr; ++ skippy_session * second = nullptr; ++ CHECK(skippy_session_create(model, &first, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_create(model, &second, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "imports") == 0) { ++ test_import_error_fences(first, second); ++ } ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "restore") == 0) { ++ test_plain_restore_parity(first, second); ++ } ++ CHECK(skippy_session_reset(first, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0 || std::strcmp(mode, "samplers") == 0) { ++ test_sampler_reservations(first, second); ++ } ++ CHECK(skippy_session_free(first, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_session_free(second, &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_model_free(model, &error) == SKIPPY_STATUS_OK); ++ return 0; ++} diff --git a/src/skippy/tests/cast_destination_regression.h b/src/skippy/tests/cast_destination_regression.h new file mode 100644 index 000000000..84da82c91 @@ -10926,3 +11164,6 @@ index 000000000..d09acccb4 + if (skippy_retire_verify_checkpoint_exact(checkpoints, 10, 3)) return 6; + return 0; +} +-- +2.54.0 (Apple Git-157) + diff --git a/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch b/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch new file mode 100644 index 0000000000..720f774e3b --- /dev/null +++ b/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch @@ -0,0 +1,57 @@ +From 177290c7b51e720a90f97a830c6d9d10c3c59117 Mon Sep 17 00:00:00 2001 +From: James Dumay +Date: Tue, 17 Nov 2026 12:15:00 +1100 +Subject: [PATCH] perf(skippy): synchronize batch iterations only when results + are consumed + +The batch execution path synchronized the CUDA context immediately +after llama_decode, forcing the CPU to idle while the GPU finished. +Move the sync to the export loop and skip it entirely for iterations +that consume no GPU results: prefill chunks that neither sample their +last token, run a causal readout, nor export activation frames return +with the context still pending, so the scheduler prepares and the +backend encodes the next chunk while the GPU executes this one. +Command-queue order sequences the chunks' KV writes and reads. +--- + src/skippy/execution-batch.cpp | 18 +++++++++++++++++- + 1 file changed, 17 insertions(+), 1 deletion(-) + +diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp +index 83c290ee2..46b0d1a27 100644 +--- a/src/skippy/execution-batch.cpp ++++ b/src/skippy/execution-batch.cpp +@@ -464,7 +464,6 @@ enum skippy_status skippy_iteration_batch_sampled( + return SKIPPY_STATUS_RUNTIME_ERROR; + } + skippy_mark_context_work_pending(first->stage_model); +- skippy_synchronize_context_if_pending(first->stage_model); + + // exports, readouts and sampling, request by request + skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); +@@ -472,6 +471,23 @@ enum skippy_status skippy_iteration_batch_sampled( + // once every request's outputs are recorded + std::vector samples; + std::vector sample_request_indexes; ++ // Synchronize only when this iteration consumes GPU results: a sampled ++ // last token, a causal readout, or a batched activation export. Prefill ++ // chunks without any of those return with the context still pending, so ++ // the scheduler prepares and the backend encodes the next chunk while ++ // the GPU still executes this one; command-queue order sequences the ++ // chunks' KV writes and reads. The Rust sizing protocol always passes a ++ // non-null descriptor array, so gate on the sessions that actually emit ++ // activation frames rather than on the array pointer. ++ const bool consumes_gpu_results = std::any_of( ++ requests, requests + request_count, ++ [](const skippy_iteration_request & request) { ++ return request.sample_last || request.readout != nullptr || ++ skippy_emits_activation_frame(request.session); ++ }); ++ if (consumes_gpu_results) { ++ skippy_synchronize_context_if_pending(first->stage_model); ++ } + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; + status = skippy_copy_batched_exports( +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch b/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch new file mode 100644 index 0000000000..fbefbde429 --- /dev/null +++ b/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch @@ -0,0 +1,63 @@ +From f42a1b0b76dd941b65d5e68224721ac0aff22e8a Mon Sep 17 00:00:00 2001 +From: James Dumay +Date: Tue, 17 Nov 2026 18:35:00 +1100 +Subject: [PATCH] perf(llama): stop re-reserving the sched on sampler detach + +Detaching a sampler only shrinks the graph and does not require a fresh +reservation. Attaching or replacing a chain can grow the graph, so retain +reservation on attachment and preserve any outstanding shape-change reserve. + +Co-authored-by: Melkor +--- + src/llama-context.cpp | 14 ++++++++------ + 1 file changed, 8 insertions(+), 6 deletions(-) + +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index 5ed43df0e..64840c0cc 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -1712,7 +1712,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + warned = true; + } + if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a ++ // detach must not force the next request to re-reserve. + } + sampling.samplers.erase(seq_id); + return false; +@@ -1731,6 +1732,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers[seq_id] = sampler; + ++ // Each attached chain can grow the graph, including a replacement. ++ // Preserve any reservation already required by a shape change. + sched_need_reserve = true; + + return true; +@@ -1739,10 +1742,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + if (sampler && !can_offload) { + LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id); + +- if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; +- } +- ++ // Detaching only shrinks what the reservation must cover; a detach ++ // must not force the next request to re-reserve. + sampling.samplers.erase(seq_id); + + return false; +@@ -1750,7 +1751,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers.erase(seq_id); + +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a detach must ++ // not force the next request to re-reserve. + + return true; + } +-- +2.54.0 (Apple Git-157) + diff --git a/skippy/scripts/build-llama.sh b/skippy/scripts/build-llama.sh index 80c9400aad..e5ee629b22 100755 --- a/skippy/scripts/build-llama.sh +++ b/skippy/scripts/build-llama.sh @@ -528,6 +528,7 @@ if [[ "$LLAMA_STAGE_WORKLOAD_ORACLE" == "ON" ]]; then fi if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then BUILD_TARGETS+=( + skippy-async-state-test skippy-backend-sample-capacity skippy-graph-build-inputs skippy-hardware-application-probe From 4e851c21fdf14483f1e7392d27945ee535191ea4 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Fri, 20 Nov 2026 18:26:31 +1100 Subject: [PATCH 79/81] fix(skippy): address exact-state retention and runtime review findings Evict superseded checkpoints before other conversations, honor explicit byte ceilings while checkpoints are leased, size the recorder for admitted captures, and retain verified model content after rehashing. Fold native synchronization fixes into their owning patches and assert that sampler detachment leaves the reservation count unchanged. --- .../skippy-api/src/split-certified.json | 2 +- .../src/kv_integration/config.rs | 741 +----------------- .../config/exact_state_retention.rs | 136 ++++ .../config/reserved_admission_harness.rs | 496 ++++++++++++ .../kv_integration/config/runtime_identity.rs | 2 +- .../config/tests/exact_state_retention.rs | 213 +++++ .../src/kv_integration/exact_state.rs | 13 +- .../skippy-serving/src/kv_integration/mod.rs | 3 +- .../skippy-serving/src/runtime_state.rs | 3 +- .../src/runtime_state/model_content.rs | 72 +- ...ize-admitted-stages-from-live-graphs.patch | 30 +- ...rate-live-stage-planning-and-executi.patch | 133 ++-- ...cover-live-graph-and-state-contracts.patch | 14 +- ...-selected-token-scores-in-causal-bat.patch | 40 +- ...tive-trace-spans-and-GPU-command-tim.patch | 99 ++- ...mple-a-batch-s-requests-concurrently.patch | 34 +- ...efer-batch-synchronization-to-export.patch | 57 -- ...-reserving-the-sched-on-sampler-deta.patch | 63 -- 18 files changed, 1128 insertions(+), 1023 deletions(-) create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/reserved_admission_harness.rs create mode 100644 skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs delete mode 100644 skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch delete mode 100644 skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 52501ebc89..82e6b9cbcd 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "4e600c9baec470f3a7d19da3223535e5609c5ab458f54d65bec06167763da7c5" + "patch_queue_sha256": "d34cb3cb339a60f56d067cad7299ee6e9b042331076b5fc2afd5789462bc922a" }, "architectures": [ "afmoe", diff --git a/skippy/crates/skippy-serving/src/kv_integration/config.rs b/skippy/crates/skippy-serving/src/kv_integration/config.rs index e780cbfc5f..d269f56ee3 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config.rs @@ -19,31 +19,26 @@ use super::{ output_tokens::OutputTokenCache, }; -use super::cache_payload::{durable_cache_payload, effective_cache_payload}; +use super::{ + cache_payload::{durable_cache_payload, effective_cache_payload}, + exact_state::exact_state_admission_total_for_lanes, +}; pub(super) mod durable_spill; mod exact_state_limits; +mod exact_state_retention; mod resident_policy; mod runtime_identity; use durable_spill::{ DurableRecordTarget, PendingDurableSpill, spill_exact_record_to_l3, start_durable_spill_worker, }; use exact_state_limits::exact_state_byte_limits; +use exact_state_retention::enforce_exact_state_limits; // Recurrent and hybrid payloads share the native n_ctx cell pool across // sequence lanes, so their exact-state catalog must remain deliberately small. const RECURRENT_CACHE_MAX_ENTRIES: usize = 16; -// Exact-state snapshots are indivisible and carry architecture-specific state -// (recurrent and convolution buffers) that `estimate_stage_cache_max_bytes` -// cannot see, because that estimate is derived from attention KV metadata -// alone. A single snapshot therefore routinely exceeds the soft cap. Keep this -// many snapshots (subject to the configured entry limit) before the soft cap -// evicts anything: falling to one entry -// turns the catalog into a single-entry cache, where two concurrent sessions -// on the same stage evict each other on every request. -const EXACT_STATE_MIN_RETAINED_ENTRIES: usize = 4; - // Operator override for the limit above, in bytes, for workers whose memory // headroom does not match the attention-derived estimate. The last indivisible // snapshot may exceed it. Zero disables the limit. @@ -221,8 +216,11 @@ impl KvStageIntegration { ); let radix = Arc::new(Mutex::new(UnifiedRadixCache::new())); let exact_blobs = Arc::new(Mutex::new(CacheBlobStore::default())); + let admission_total_cap = exact_state_admission_total_for_lanes(config.lane_count); + // All admitted captures can reach the queue before the recorder receives one. + let record_queue_capacity = EXACT_STATE_RECORD_CAPACITY.max(admission_total_cap); let (exact_state_record_tx, exact_state_record_rx) = - std::sync::mpsc::sync_channel::(EXACT_STATE_RECORD_CAPACITY); + std::sync::mpsc::sync_channel::(record_queue_capacity); let worker_radix = radix.clone(); let worker_exact_blobs = exact_blobs.clone(); let worker_l3 = l3.clone(); @@ -247,10 +245,6 @@ impl KvStageIntegration { let worker_exact_state_records_pending = exact_state_records_pending.clone(); let admission_outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let admission_best_effort_outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let admission_total_cap = - crate::kv_integration::exact_state::exact_state_admission_total_for_lanes( - config.lane_count, - ); #[cfg(test)] let exact_state_worker_received = Arc::new(std::sync::atomic::AtomicUsize::new(0)); #[cfg(test)] @@ -788,7 +782,10 @@ fn store_exact_radix_record_with_codec( released.push(replaced.payload); } while radix.stats().recurrent_entries > max_entries { - let Some(evicted) = radix.evict_lru_recurrent() else { + let Some(evicted) = radix + .evict_lru_superseded_recurrent() + .or_else(|| radix.evict_lru_recurrent()) + else { break; }; released.push(evicted.value.payload); @@ -813,51 +810,7 @@ fn store_exact_radix_record_with_codec( payload.release_from(&mut blobs)?; } } - // Exact snapshots are indivisible, and the soft cap is estimated from - // attention KV metadata that cannot include architecture-specific - // recurrent state, so one snapshot can legitimately exceed it. Hold a - // working set of conversations past the soft cap (never more than the - // configured entry limit) so concurrent sessions on a stage stop evicting - // each other. The floor counts each conversation's latest continuation: - // a checkpoint that a longer retained checkpoint extends is evicted first. - let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); - evict_exact_entries_over(radix, blobs, limits.soft_bytes, retention_floor)?; - // Zero means unbounded: no hard pass at all. - if limits.hard_bytes > 0 { - // An explicit operator budget is a strict ceiling: only one - // indivisible snapshot may exceed it. The attention-derived default - // stretches to hold the working set, since it cannot see hybrid - // recurrent state and would otherwise collapse the catalog. - let (hard_limit, hard_floor) = if limits.hard_is_explicit { - (limits.hard_bytes, 1) - } else { - let floor_bytes = logical_bytes - .max(1) - .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); - (limits.hard_bytes.max(floor_bytes), retention_floor) - }; - evict_exact_entries_over(radix, blobs, hard_limit, hard_floor)?; - let retained = blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .physical_bytes(); - if retained > limits.hard_bytes && exact_state_over_limit_warning_due() { - // Observable signal that the retained working set sits above the - // hard limit, e.g. the attention-derived estimate undercounts this - // stage's snapshots. Set an explicit exact-state budget when this - // repeats and memory must stay bounded. - let _ = skippy_events::diagnostics::emit( - skippy_events::diagnostics::ServingDiagnostic::Warning { - message: "exact-state catalog retained more than its hard byte limit" - .to_string(), - context: Some(format!( - "retained_bytes={retained} soft_bytes={} hard_bytes={} explicit={} floor_entries={retention_floor}", - limits.soft_bytes, limits.hard_bytes, limits.hard_is_explicit - )), - }, - ); - } - } + enforce_exact_state_limits(radix, blobs, limits, max_entries, logical_bytes)?; #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); @@ -933,68 +886,6 @@ fn cachegen_descriptor_is_qualified(desc: &RuntimeKvPageDesc) -> bool { ) } -/// At most one over-limit warning per minute per process. -fn exact_state_over_limit_warning_due() -> bool { - use std::sync::atomic::{AtomicU64, Ordering}; - static LAST_WARNED_SECS: AtomicU64 = AtomicU64::new(0); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |elapsed| elapsed.as_secs()); - let last = LAST_WARNED_SECS.load(Ordering::Relaxed); - (last == 0 || now.saturating_sub(last) >= 60) - && LAST_WARNED_SECS - .compare_exchange(last, now.max(1), Ordering::Relaxed, Ordering::Relaxed) - .is_ok() -} - -/// Evicts exact entries while the catalog holds more than `limit_bytes`. -/// Superseded checkpoints (a strict prefix of another retained checkpoint) -/// go first; then least-recently-used conversations go while more than -/// `min_retained_entries` conversations remain. A zero limit means the -/// catalog has no byte ceiling and nothing is evicted. -fn evict_exact_entries_over( - radix: &Mutex>, - blobs: &Mutex, - limit_bytes: u64, - min_retained_entries: usize, -) -> Result { - if limit_bytes == 0 { - return Ok(0); - } - let floor = min_retained_entries.max(1); - let mut evicted_total = 0usize; - loop { - let over_bytes = blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .physical_bytes() - > limit_bytes; - if !over_bytes { - break; - } - let evicted = { - let mut radix = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - radix.evict_lru_superseded_recurrent().or_else(|| { - (radix.recurrent_leaf_entries() > floor) - .then(|| radix.evict_lru_recurrent()) - .flatten() - }) - }; - let Some(evicted) = evicted else { - break; - }; - evicted_total += 1; - evicted.value.payload.release_from( - &mut blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner), - )?; - } - Ok(evicted_total) -} - /// Either kill-switch variable resolving to `off` disables the cache, so an /// explicit `SKIPPY_KV_CACHE=on` cannot mask `SKIPPY_PREFIX_CACHE=off`. fn cache_disabled_by_env(kv_cache: Option<&str>, prefix_cache: Option<&str>) -> bool { @@ -1076,6 +967,7 @@ mod tests { mod cache_admission; mod durable_spill; + mod exact_state_retention; mod runtime_admission; fn limits(soft_bytes: u64, hard_bytes: u64) -> ExactStateByteLimits { @@ -1323,150 +1215,6 @@ mod tests { ); } - #[test] - fn exact_state_retention_floor_survives_a_hard_cap_blind_to_recurrent_state() { - // Regression: the byte limits are derived from attention KV metadata, - // so hybrid snapshots (recurrent state the estimate cannot see) can - // push the retained working set past the hard cap. The retention floor - // must keep every concurrent session's entry; collapsing to a single - // entry made sessions evict each other on every request. - let radix = Mutex::new(UnifiedRadixCache::new()); - let blobs = Mutex::new(CacheBlobStore::new(4)); - let budget = StorageBudget::new(); - // Each snapshot is 32 bytes; four of them (128) exceed the hard cap - // of 80 even though each individually fits the 8x headroom. - let oversized_for_attention_estimate = limits(10, 80); - for index in 0..4 { - store_exact_radix_record( - &radix, - &blobs, - 512, - oversized_for_attention_estimate, - None, - None, - pending( - &format!("session-{index}"), - &[1, index + 2], - &distinct_payload(index as u8, 32), - &budget, - ), - ) - .unwrap(); - } - // Distinct blocks, so the retained set really is past the hard cap and - // the pre-floor policy would have evicted down to one entry. - assert!(blobs.lock().unwrap().physical_bytes() > 80); - let mut radix = radix.lock().unwrap(); - assert_eq!(radix.stats().recurrent_entries, 4); - for index in 0..4 { - assert!( - radix.lookup_recurrent("model", &[1, index + 2]).is_some(), - "session {index} must retain its exact-state entry" - ); - } - } - - /// Payload bytes that dedupe into distinct 4-byte blocks per `seed`. - fn distinct_payload(seed: u8, len: usize) -> Vec { - (0..len) - .map(|offset| seed.wrapping_mul(64).wrapping_add(offset as u8)) - .collect() - } - - fn store_sessions( - radix: &Mutex>, - blobs: &Mutex, - limits: ExactStateByteLimits, - sessions: &[(&str, &[i32], u8)], - ) { - let budget = StorageBudget::new(); - for (page, tokens, seed) in sessions { - store_exact_radix_record( - radix, - blobs, - 512, - limits, - None, - None, - pending(page, tokens, &distinct_payload(*seed, 32), &budget), - ) - .unwrap(); - } - } - - #[test] - fn explicit_exact_budget_stays_a_strict_ceiling_past_the_retention_floor() { - let radix = Mutex::new(UnifiedRadixCache::new()); - let blobs = Mutex::new(CacheBlobStore::new(4)); - let explicit_ceiling = ExactStateByteLimits { - soft_bytes: 10, - hard_bytes: 40, - hard_is_explicit: true, - }; - store_sessions( - &radix, - &blobs, - explicit_ceiling, - &[ - ("a", &[1, 2], 0), - ("b", &[1, 3], 1), - ("c", &[1, 4], 2), - ("d", &[1, 5], 3), - ], - ); - // One indivisible 32-byte snapshot fits the ceiling; a second does not. - assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 1); - assert!(blobs.lock().unwrap().physical_bytes() <= 40); - } - - #[test] - fn unbounded_byte_limits_keep_every_entry_the_entry_limit_allows() { - let radix = Mutex::new(UnifiedRadixCache::new()); - let blobs = Mutex::new(CacheBlobStore::new(4)); - store_sessions( - &radix, - &blobs, - limits(0, 0), - &[ - ("a", &[1, 2], 0), - ("b", &[1, 3], 1), - ("c", &[1, 4], 2), - ("d", &[1, 5], 3), - ("e", &[1, 6], 4), - ], - ); - assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 5); - } - - #[test] - fn retention_floor_keeps_each_sessions_latest_continuation() { - let radix = Mutex::new(UnifiedRadixCache::new()); - let blobs = Mutex::new(CacheBlobStore::new(4)); - // Session A stores a prefill and a post-decode checkpoint between the - // other sessions' prefills. Five snapshots exceed the derived hard - // cap; the superseded prefill must go, not another session's only one. - store_sessions( - &radix, - &blobs, - limits(10, 80), - &[ - ("a-prefill", &[1, 2], 0), - ("b", &[1, 3], 1), - ("a-decode", &[1, 2, 9, 9], 2), - ("c", &[1, 4], 3), - ("d", &[1, 5], 4), - ], - ); - let mut radix = radix.lock().unwrap(); - assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); - for tokens in [&[1, 2, 9, 9][..], &[1, 3], &[1, 4], &[1, 5]] { - assert!( - radix.lookup_recurrent("model", tokens).is_some(), - "latest continuation {tokens:?} must survive" - ); - } - } - #[test] fn selected_l3_fill_promotes_to_l2_on_the_record_worker_path() { let radix = Mutex::new(UnifiedRadixCache::new()); @@ -1886,459 +1634,4 @@ mod tests { } #[cfg(test)] -mod reserved_admission_harness { - use super::*; - use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; - use crate::kv_integration::{ExactStateExtra, ExactStateRecordAdmission}; - use crate::runtime_state::RuntimeState; - use skippy_cache::ExactStatePayload; - use skippy_protocol::MessageBase; - use std::sync::atomic::Ordering as AtomicOrdering; - - const NAMESPACE: &str = "reserved-admission-test"; - const SESSION: &str = "harness-session"; - const WAIT: std::time::Duration = std::time::Duration::from_secs(30); - - fn harness_config() -> StageConfig { - StageConfig { - stage_id: "stage-0".to_string(), - model_id: NAMESPACE.to_string(), - kv_cache: Some(StageKvCacheConfig { - exact_max_bytes: None, - mode: StageKvCacheMode::LookupRecord, - max_entries: 8, - max_bytes: 0, - l2_max_bytes: 0, - codec: skippy_protocol::StageKvCacheCodec::Native, - min_tokens: 1, - shared_prefix_stride_tokens: 1, - shared_prefix_record_limit: 0, - prefill_admission: Default::default(), - retention: Default::default(), - }), - ..StageConfig::default() - } - } - - fn harness() -> (Arc, StageConfig) { - let config = harness_config(); - let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) - .expect("kv integration init") - .expect("kv integration must be enabled for LookupRecord/KvRecurrent"); - (Arc::new(kv), config) - } - - fn message_base() -> MessageBase { - MessageBase { - schema_version: skippy_protocol::SCHEMA_VERSION, - run_id: NAMESPACE.to_string(), - request_id: "harness-request".to_string(), - session_id: SESSION.to_string(), - stage_id: "stage-0".to_string(), - stage_index: 0, - topology_id: NAMESPACE.to_string(), - model_id: Some(NAMESPACE.to_string()), - tokenizer_id: None, - chat_template_id: None, - seq: None, - } - } - - fn identity( - kv: &KvStageIntegration, - config: &StageConfig, - token_ids: &[i32], - ) -> crate::kv_integration::PrefillKvIdentity { - kv.prefill_identity(config, &message_base(), 0, token_ids) - } - - fn record( - page_id: &str, - token_ids: Vec, - admission_credit: ExactStateAdmissionCredit, - ) -> PendingExactStateRecord { - PendingExactStateRecord { - page_id: page_id.to_string(), - payload: ExactStatePayload::full_state(vec![1, 2, 3]), - extra: ExactStateExtra::default(), - namespace: NAMESPACE.to_string(), - token_ids, - l3_fill_claim: None, - write_through_l3: true, - l2_promotion_digest: None, - l3_cost: None, - admission_credit, - } - } - - fn acquire( - kv: &KvStageIntegration, - class: CaptureAdmission, - ) -> Option { - ExactStateAdmissionCredit::acquire( - &kv.admission_outstanding, - &kv.admission_best_effort_outstanding, - crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, - class, - ) - } - - fn outstanding(kv: &KvStageIntegration) -> usize { - kv.admission_outstanding.load(AtomicOrdering::Acquire) - } - - fn best_effort_outstanding(kv: &KvStageIntegration) -> usize { - kv.admission_best_effort_outstanding - .load(AtomicOrdering::Acquire) - } - - fn stored(kv: &KvStageIntegration, token_ids: &[i32]) -> bool { - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .recurrent_exact(NAMESPACE, token_ids) - .is_some() - } - - /// Reserved-credit delivery end-to-end under an EXPLICITLY paused - /// recorder worker (no radix contention): the BestEffort payload is - /// received worker-side and paused BEFORE storage, the Continuation - /// payload is actually ENQUEUED behind it, both classes decline overflow, - /// and unpausing stores BOTH identities and drains every real credit; the - /// budget then admits and stores a recovery record. - #[test] - fn reserved_credits_deliver_continuation_payloads_and_recover_after_drain() { - let (kv, _config) = harness(); - kv.exact_state_worker_pause - .store(true, AtomicOrdering::Release); - - let be1 = acquire(&kv, CaptureAdmission::BestEffort).expect("first BestEffort admitted"); - assert_eq!( - kv.enqueue_exact_state_record(record("be1", vec![1, 2, 3], be1)), - ExactStateRecordAdmission::Queued, - ); - kv.wait_for_exact_state_worker_received(1, WAIT) - .expect("worker received the BestEffort record before storage"); - assert_eq!(outstanding(&kv), 1, "credit held by the paused worker"); - assert!( - !stored(&kv, &[1, 2, 3]), - "paused worker must not have stored yet" - ); - - assert!( - acquire(&kv, CaptureAdmission::BestEffort).is_none(), - "second BestEffort declined at the reserved cap" - ); - assert_eq!(best_effort_outstanding(&kv), 1); - - let pd1 = acquire(&kv, CaptureAdmission::Continuation) - .expect("Continuation admitted into the reserved share"); - assert_eq!( - kv.enqueue_exact_state_record(record("pd1", vec![4, 5, 6], pd1)), - ExactStateRecordAdmission::Queued, - "the Continuation payload must be enqueued, never dropped by the harness" - ); - assert_eq!(outstanding(&kv), 2); - assert!( - acquire(&kv, CaptureAdmission::Continuation).is_none(), - "total budget exhausted" - ); - - kv.exact_state_worker_pause - .store(false, AtomicOrdering::Release); - kv.wait_for_exact_state_recording(WAIT) - .expect("recorder drained both records without drops or panics"); - assert_eq!( - outstanding(&kv), - 0, - "credits released by real worker completion" - ); - assert_eq!(best_effort_outstanding(&kv), 0); - assert!(stored(&kv, &[1, 2, 3]), "BestEffort identity stored"); - assert!(stored(&kv, &[4, 5, 6]), "Continuation identity stored"); - - let recovered = - acquire(&kv, CaptureAdmission::Continuation).expect("budget recovers after the drain"); - assert_eq!( - kv.enqueue_exact_state_record(record("recovered", vec![7, 8], recovered)), - ExactStateRecordAdmission::Queued, - ); - kv.wait_for_exact_state_recording(WAIT) - .expect("recovered record stored"); - assert_eq!(outstanding(&kv), 0); - assert!(stored(&kv, &[7, 8]), "recovered identity stored"); - } - - /// Unhealthy recorder releases real credits on BOTH release paths: the - /// enqueue-level WorkerStopped drop, and the record_exact_state - /// try_begin_record decline that happens after acquisition. - #[test] - fn unhealthy_worker_releases_credits_on_both_release_paths() { - let (kv, config) = harness(); - kv.exact_state_record_worker_healthy - .store(false, AtomicOrdering::Release); - - let credit = acquire(&kv, CaptureAdmission::BestEffort) - .expect("budget admits before the health gate"); - assert_eq!( - kv.enqueue_exact_state_record(record("stopped", vec![1], credit)), - ExactStateRecordAdmission::WorkerStopped, - ); - assert_eq!( - outstanding(&kv), - 0, - "enqueue-level WorkerStopped released the real credit" - ); - - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let begin_record = crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD - .load(AtomicOrdering::Acquire); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!( - matches!(result, Ok(None)), - "unhealthy worker must decline recording" - ); - assert_eq!( - crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD - .load(AtomicOrdering::Acquire), - begin_record + 1, - "the decline happened at try_begin_record, i.e. after acquisition" - ); - assert_eq!( - outstanding(&kv), - 0, - "record_exact_state released the credit on the try_begin_record decline" - ); - } - - /// record_exact_state releases its real credit when the radix lock is - /// busy: the capture is skipped without waiting and the inflight page is - /// released. - /// A sliding-window cache can reuse rows below the boundary before the - /// session ends, so its stage copies them with the recurrent state. - #[test] - fn a_sliding_window_stage_does_not_defer_its_kv_copy() { - let (kv, _) = harness(); - assert_eq!( - kv.exact_state_payload(), - Some(StagePrefixCachePayload::KvRecurrent) - ); - let mut runtime = RuntimeState::new_modelless_for_test(1); - assert!(kv.defers_kv_copy(&mut runtime, SESSION, 3)); - - runtime.sliding_window_kv_for_test = true; - assert!(!kv.defers_kv_copy(&mut runtime, SESSION, 3)); - } - - #[test] - fn record_exact_state_releases_credit_when_radix_is_busy() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let radix_guard = kv.radix.lock().unwrap(); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - drop(radix_guard); - assert!( - matches!(result, Ok(None)), - "busy radix skips without waiting" - ); - assert_eq!(outstanding(&kv), 0, "credit released on the busy skip"); - assert!( - kv.inflight_records.lock().unwrap().is_empty(), - "inflight page released on the busy skip" - ); - } - - /// retained_exact_identity requires the EXACT radix node: a retained - /// shorter entry must not certify a longer identity, and a longer entry - /// must not certify its own prefix. - #[test] - fn retained_exact_identity_requires_the_exact_radix_node() { - let (kv, config) = harness(); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - chat_identity.namespace.clone(), - &chat_identity.token_ids, - 32, - RadixExactEntry::new( - "exact".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("seeding the radix must succeed"); - - assert!( - kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3]), - "the exact node is retained" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2]), - "a shorter query must not be certified by the longer retained entry" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3, 4]), - "a longer identity must not be certified by a retained shorter prefix" - ); - assert!( - !kv.retained_exact_identity(&chat_identity.namespace, &[9, 9, 9]), - "an unrelated identity is absent" - ); - } - - /// record_exact_state releases its real credit when the identity is - /// already recorded. - #[test] - fn record_exact_state_releases_credit_when_already_recorded() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - chat_identity.namespace.clone(), - &chat_identity.token_ids, - 32, - RadixExactEntry::new( - "pre-existing".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("pre-seeding the radix must succeed"); - let result = kv.record_exact_state( - &mut runtime, - SESSION, - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!( - matches!(result, Ok(None)), - "already-recorded identity skips" - ); - assert_eq!( - outstanding(&kv), - 0, - "credit released on the already-recorded skip" - ); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } - - fn seed_exact_state( - kv: &KvStageIntegration, - identity: &crate::kv_integration::PrefillKvIdentity, - ) { - kv.radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert_recurrent( - identity.namespace.clone(), - &identity.token_ids, - 32, - RadixExactEntry::new( - "pre-existing".to_string(), - ExactStatePayload::full_state(vec![9]), - ExactStateExtra::default(), - true, - ), - ) - .expect("pre-seeding the radix must succeed"); - } - - fn record_at_session_end( - kv: &Arc, - runtime: &mut RuntimeState, - identity: &crate::kv_integration::PrefillKvIdentity, - ) -> anyhow::Result { - kv.record_exact_state_at_session_end( - runtime, - SESSION, - identity, - CaptureAdmission::BestEffort, - None, - true, - ) - } - - /// A deferred capture of a checkpoint the cache already holds copies - /// nothing at registration. (The modelless runtime fails any export, so - /// reaching one would return an error.) - #[test] - fn a_deferred_capture_of_a_cached_checkpoint_skips_at_registration() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - seed_exact_state(&kv, &chat_identity); - - let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); - - assert!( - matches!( - captured, - Ok(crate::kv_integration::SessionEndCapture::Skipped) - ), - "{captured:?}" - ); - assert_eq!(outstanding(&kv), 0); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } - - /// A miss, and a radix too busy to say, both go on to copy the - /// recurrent state; session-end admission checks the radix again. - #[test] - fn a_deferred_capture_goes_ahead_on_a_miss_or_a_busy_radix() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - - assert!( - record_at_session_end(&kv, &mut runtime, &chat_identity).is_err(), - "a miss reaches the recurrent export" - ); - - seed_exact_state(&kv, &chat_identity); - let radix_guard = kv.radix.lock().unwrap(); - let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); - drop(radix_guard); - assert!( - captured.is_err(), - "a busy radix reaches the recurrent export" - ); - assert_eq!(outstanding(&kv), 0); - } - - /// record_exact_state releases its real credit when the payload export - /// fails (unknown session here), and nothing is enqueued. - #[test] - fn record_exact_state_releases_credit_when_export_fails() { - let (kv, config) = harness(); - let mut runtime = RuntimeState::new_modelless_for_test(1); - let chat_identity = identity(&kv, &config, &[1, 2, 3]); - let result = kv.record_exact_state( - &mut runtime, - "missing-session", - &chat_identity, - CaptureAdmission::BestEffort, - ); - assert!(result.is_err(), "exporting an unknown session must fail"); - assert_eq!(outstanding(&kv), 0, "credit released when the export fails"); - assert!(kv.inflight_records.lock().unwrap().is_empty()); - } -} +mod reserved_admission_harness; diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs new file mode 100644 index 0000000000..00a72a1357 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs @@ -0,0 +1,136 @@ +//! Byte-pressure eviction for the exact-state catalog. +use std::sync::{Mutex, PoisonError}; + +use anyhow::Result; +use skippy_cache::{CacheBlobStore, UnifiedRadixCache}; + +use super::{ExactStateByteLimits, RadixExactEntry}; +use crate::kv_integration::RadixResidentEntry; + +// Exact-state snapshots are indivisible and carry architecture-specific state +// (recurrent and convolution buffers) that `estimate_stage_cache_max_bytes` +// cannot see, because that estimate is derived from attention KV metadata +// alone. A single snapshot therefore routinely exceeds the soft cap. Keep this +// many snapshots (subject to the configured entry limit) before the soft cap +// evicts anything: falling to one entry +// turns the catalog into a single-entry cache, where two concurrent sessions +// on the same stage evict each other on every request. +const EXACT_STATE_MIN_RETAINED_ENTRIES: usize = 4; + +pub(super) fn enforce_exact_state_limits( + radix: &Mutex>, + blobs: &Mutex, + limits: ExactStateByteLimits, + max_entries: usize, + logical_bytes: u64, +) -> Result<()> { + // Exact snapshots are indivisible, and the soft cap is estimated from + // attention KV metadata that cannot include architecture-specific + // recurrent state, so one snapshot can legitimately exceed it. Hold a + // working set of conversations past the soft cap (never more than the + // configured entry limit) so concurrent sessions on a stage stop evicting + // each other. The floor counts each conversation's latest continuation: + // a checkpoint that a longer retained checkpoint extends is evicted first. + let retention_floor = EXACT_STATE_MIN_RETAINED_ENTRIES.min(max_entries); + let conversations = RetentionFloor::Conversations(retention_floor.max(1)); + evict_exact_entries_over(radix, blobs, limits.soft_bytes, conversations)?; + // Zero means unbounded: no hard pass at all. + if limits.hard_bytes > 0 { + // An explicit operator budget is a strict ceiling: only one + // indivisible snapshot may exceed it. The attention-derived default + // stretches to hold the working set, since it cannot see hybrid + // recurrent state and would otherwise collapse the catalog. + let (hard_limit, hard_floor) = if limits.hard_is_explicit { + (limits.hard_bytes, RetentionFloor::SingleSnapshot) + } else { + let floor_bytes = logical_bytes + .max(1) + .saturating_mul(u64::try_from(retention_floor).unwrap_or(u64::MAX)); + (limits.hard_bytes.max(floor_bytes), conversations) + }; + evict_exact_entries_over(radix, blobs, hard_limit, hard_floor)?; + let retained = blobs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .physical_bytes(); + if retained > limits.hard_bytes && exact_state_over_limit_warning_due() { + // Observable signal that the retained working set sits above the + // hard limit, e.g. the attention-derived estimate undercounts this + // stage's snapshots. Set an explicit exact-state budget when this + // repeats and memory must stay bounded. + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "exact-state catalog retained more than its hard byte limit" + .to_string(), + context: Some(format!( + "retained_bytes={retained} soft_bytes={} hard_bytes={} explicit={} floor_entries={retention_floor}", + limits.soft_bytes, limits.hard_bytes, limits.hard_is_explicit + )), + }, + ); + } + } + Ok(()) +} + +/// At most one over-limit warning per minute per process. +fn exact_state_over_limit_warning_due() -> bool { + use std::sync::atomic::{AtomicU64, Ordering}; + static LAST_WARNED_SECS: AtomicU64 = AtomicU64::new(0); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let last = LAST_WARNED_SECS.load(Ordering::Relaxed); + (last == 0 || now.saturating_sub(last) >= 60) + && LAST_WARNED_SECS + .compare_exchange(last, now.max(1), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() +} + +#[derive(Clone, Copy)] +enum RetentionFloor { + Conversations(usize), + SingleSnapshot, +} + +/// Evict superseded checkpoints first, then evict by recency above the floor. +fn evict_exact_entries_over( + radix: &Mutex>, + blobs: &Mutex, + limit_bytes: u64, + floor: RetentionFloor, +) -> Result<()> { + if limit_bytes == 0 { + return Ok(()); + } + loop { + let over_bytes = blobs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .physical_bytes() + > limit_bytes; + if !over_bytes { + break; + } + let evicted = { + let mut radix = radix.lock().unwrap_or_else(PoisonError::into_inner); + radix.evict_lru_superseded_recurrent().or_else(|| { + let above_floor = match floor { + RetentionFloor::Conversations(minimum) => { + radix.recurrent_leaf_entries() > minimum + } + RetentionFloor::SingleSnapshot => radix.stats().recurrent_entries > 1, + }; + above_floor.then(|| radix.evict_lru_recurrent()).flatten() + }) + }; + let Some(evicted) = evicted else { + break; + }; + evicted + .value + .payload + .release_from(&mut blobs.lock().unwrap_or_else(PoisonError::into_inner))?; + } + Ok(()) +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/reserved_admission_harness.rs b/skippy/crates/skippy-serving/src/kv_integration/config/reserved_admission_harness.rs new file mode 100644 index 0000000000..cd77a534c1 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/reserved_admission_harness.rs @@ -0,0 +1,496 @@ +use super::*; +use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; +use crate::kv_integration::{ExactStateExtra, ExactStateRecordAdmission}; +use crate::runtime_state::RuntimeState; +use skippy_cache::ExactStatePayload; +use skippy_protocol::MessageBase; +use std::sync::atomic::Ordering as AtomicOrdering; + +const NAMESPACE: &str = "reserved-admission-test"; +const SESSION: &str = "harness-session"; +const WAIT: std::time::Duration = std::time::Duration::from_secs(30); + +fn harness_config() -> StageConfig { + StageConfig { + stage_id: "stage-0".to_string(), + model_id: NAMESPACE.to_string(), + lane_count: 1, + kv_cache: Some(StageKvCacheConfig { + exact_max_bytes: None, + mode: StageKvCacheMode::LookupRecord, + max_entries: 8, + max_bytes: 0, + l2_max_bytes: 0, + codec: skippy_protocol::StageKvCacheCodec::Native, + min_tokens: 1, + shared_prefix_stride_tokens: 1, + shared_prefix_record_limit: 0, + prefill_admission: Default::default(), + retention: Default::default(), + }), + ..StageConfig::default() + } +} + +fn harness() -> (Arc, StageConfig) { + let config = harness_config(); + let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) + .expect("kv integration init") + .expect("kv integration must be enabled for LookupRecord/KvRecurrent"); + (Arc::new(kv), config) +} + +fn message_base() -> MessageBase { + MessageBase { + schema_version: skippy_protocol::SCHEMA_VERSION, + run_id: NAMESPACE.to_string(), + request_id: "harness-request".to_string(), + session_id: SESSION.to_string(), + stage_id: "stage-0".to_string(), + stage_index: 0, + topology_id: NAMESPACE.to_string(), + model_id: Some(NAMESPACE.to_string()), + tokenizer_id: None, + chat_template_id: None, + seq: None, + } +} + +fn identity( + kv: &KvStageIntegration, + config: &StageConfig, + token_ids: &[i32], +) -> crate::kv_integration::PrefillKvIdentity { + kv.prefill_identity(config, &message_base(), 0, token_ids) +} + +fn record( + page_id: &str, + token_ids: Vec, + admission_credit: ExactStateAdmissionCredit, +) -> PendingExactStateRecord { + PendingExactStateRecord { + page_id: page_id.to_string(), + payload: ExactStatePayload::full_state(vec![1, 2, 3]), + extra: ExactStateExtra::default(), + namespace: NAMESPACE.to_string(), + token_ids, + l3_fill_claim: None, + write_through_l3: true, + l2_promotion_digest: None, + l3_cost: None, + admission_credit, + } +} + +fn acquire(kv: &KvStageIntegration, class: CaptureAdmission) -> Option { + ExactStateAdmissionCredit::acquire( + &kv.admission_outstanding, + &kv.admission_best_effort_outstanding, + kv.admission_total_cap, + class, + ) +} + +fn outstanding(kv: &KvStageIntegration) -> usize { + kv.admission_outstanding.load(AtomicOrdering::Acquire) +} + +fn best_effort_outstanding(kv: &KvStageIntegration) -> usize { + kv.admission_best_effort_outstanding + .load(AtomicOrdering::Acquire) +} + +fn stored(kv: &KvStageIntegration, token_ids: &[i32]) -> bool { + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .recurrent_exact(NAMESPACE, token_ids) + .is_some() +} + +#[test] +fn lane_scaled_recorder_can_queue_the_reserved_continuation() { + use std::sync::atomic::AtomicBool; + + struct ResumeRecorder<'a>(&'a AtomicBool); + impl Drop for ResumeRecorder<'_> { + fn drop(&mut self) { + self.0.store(false, AtomicOrdering::Release); + } + } + + let lanes = 9; + let mut config = harness_config(); + config.lane_count = lanes; + config.kv_cache.as_mut().unwrap().max_entries = 16; + let kv = KvStageIntegration::from_test_state(&config, ModelStateKind::Recurrent) + .unwrap() + .unwrap(); + kv.exact_state_worker_pause + .store(true, AtomicOrdering::Release); + let resume = ResumeRecorder(&kv.exact_state_worker_pause); + + for lane in 0..lanes { + let credit = acquire(&kv, CaptureAdmission::BestEffort).expect("lane capture admitted"); + assert_eq!( + kv.enqueue_exact_state_record(record( + &format!("lane-{lane}"), + vec![i32::try_from(lane).unwrap()], + credit, + )), + ExactStateRecordAdmission::Queued, + ); + if lane == 0 { + kv.wait_for_exact_state_worker_received(1, WAIT).unwrap(); + } + } + let credit = acquire(&kv, CaptureAdmission::Continuation).expect("reserved capture admitted"); + let continuation = vec![20]; + assert_eq!( + kv.enqueue_exact_state_record(record("continuation", continuation.clone(), credit)), + ExactStateRecordAdmission::Queued, + ); + + drop(resume); + kv.wait_for_exact_state_recording(WAIT).unwrap(); + assert!(stored(&kv, &continuation)); +} + +/// Reserved-credit delivery end-to-end under an EXPLICITLY paused +/// recorder worker (no radix contention): the BestEffort payload is +/// received worker-side and paused BEFORE storage, the Continuation +/// payload is actually ENQUEUED behind it, both classes decline overflow, +/// and unpausing stores BOTH identities and drains every real credit; the +/// budget then admits and stores a recovery record. +#[test] +fn reserved_credits_deliver_continuation_payloads_and_recover_after_drain() { + let (kv, _config) = harness(); + kv.exact_state_worker_pause + .store(true, AtomicOrdering::Release); + + let be1 = acquire(&kv, CaptureAdmission::BestEffort).expect("first BestEffort admitted"); + assert_eq!( + kv.enqueue_exact_state_record(record("be1", vec![1, 2, 3], be1)), + ExactStateRecordAdmission::Queued, + ); + kv.wait_for_exact_state_worker_received(1, WAIT) + .expect("worker received the BestEffort record before storage"); + assert_eq!(outstanding(&kv), 1, "credit held by the paused worker"); + assert!( + !stored(&kv, &[1, 2, 3]), + "paused worker must not have stored yet" + ); + + assert!( + acquire(&kv, CaptureAdmission::BestEffort).is_none(), + "second BestEffort declined at the reserved cap" + ); + assert_eq!(best_effort_outstanding(&kv), 1); + + let pd1 = acquire(&kv, CaptureAdmission::Continuation) + .expect("Continuation admitted into the reserved share"); + assert_eq!( + kv.enqueue_exact_state_record(record("pd1", vec![4, 5, 6], pd1)), + ExactStateRecordAdmission::Queued, + "the Continuation payload must be enqueued, never dropped by the harness" + ); + assert_eq!(outstanding(&kv), 2); + assert!( + acquire(&kv, CaptureAdmission::Continuation).is_none(), + "total budget exhausted" + ); + + kv.exact_state_worker_pause + .store(false, AtomicOrdering::Release); + kv.wait_for_exact_state_recording(WAIT) + .expect("recorder drained both records without drops or panics"); + assert_eq!( + outstanding(&kv), + 0, + "credits released by real worker completion" + ); + assert_eq!(best_effort_outstanding(&kv), 0); + assert!(stored(&kv, &[1, 2, 3]), "BestEffort identity stored"); + assert!(stored(&kv, &[4, 5, 6]), "Continuation identity stored"); + + let recovered = + acquire(&kv, CaptureAdmission::Continuation).expect("budget recovers after the drain"); + assert_eq!( + kv.enqueue_exact_state_record(record("recovered", vec![7, 8], recovered)), + ExactStateRecordAdmission::Queued, + ); + kv.wait_for_exact_state_recording(WAIT) + .expect("recovered record stored"); + assert_eq!(outstanding(&kv), 0); + assert!(stored(&kv, &[7, 8]), "recovered identity stored"); +} + +/// Unhealthy recorder releases real credits on BOTH release paths: the +/// enqueue-level WorkerStopped drop, and the record_exact_state +/// try_begin_record decline that happens after acquisition. +#[test] +fn unhealthy_worker_releases_credits_on_both_release_paths() { + let (kv, config) = harness(); + kv.exact_state_record_worker_healthy + .store(false, AtomicOrdering::Release); + + let credit = + acquire(&kv, CaptureAdmission::BestEffort).expect("budget admits before the health gate"); + assert_eq!( + kv.enqueue_exact_state_record(record("stopped", vec![1], credit)), + ExactStateRecordAdmission::WorkerStopped, + ); + assert_eq!( + outstanding(&kv), + 0, + "enqueue-level WorkerStopped released the real credit" + ); + + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let begin_record = + crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD.load(AtomicOrdering::Acquire); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!( + matches!(result, Ok(None)), + "unhealthy worker must decline recording" + ); + assert_eq!( + crate::frontend::capture_trace::POST_DECODE_NONE_BEGIN_RECORD.load(AtomicOrdering::Acquire), + begin_record + 1, + "the decline happened at try_begin_record, i.e. after acquisition" + ); + assert_eq!( + outstanding(&kv), + 0, + "record_exact_state released the credit on the try_begin_record decline" + ); +} + +/// record_exact_state releases its real credit when the radix lock is +/// busy: the capture is skipped without waiting and the inflight page is +/// released. +/// A sliding-window cache can reuse rows below the boundary before the +/// session ends, so its stage copies them with the recurrent state. +#[test] +fn a_sliding_window_stage_does_not_defer_its_kv_copy() { + let (kv, _) = harness(); + assert_eq!( + kv.exact_state_payload(), + Some(StagePrefixCachePayload::KvRecurrent) + ); + let mut runtime = RuntimeState::new_modelless_for_test(1); + assert!(kv.defers_kv_copy(&mut runtime, SESSION, 3)); + + runtime.sliding_window_kv_for_test = true; + assert!(!kv.defers_kv_copy(&mut runtime, SESSION, 3)); +} + +#[test] +fn record_exact_state_releases_credit_when_radix_is_busy() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let radix_guard = kv.radix.lock().unwrap(); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + drop(radix_guard); + assert!( + matches!(result, Ok(None)), + "busy radix skips without waiting" + ); + assert_eq!(outstanding(&kv), 0, "credit released on the busy skip"); + assert!( + kv.inflight_records.lock().unwrap().is_empty(), + "inflight page released on the busy skip" + ); +} + +/// retained_exact_identity requires the EXACT radix node: a retained +/// shorter entry must not certify a longer identity, and a longer entry +/// must not certify its own prefix. +#[test] +fn retained_exact_identity_requires_the_exact_radix_node() { + let (kv, config) = harness(); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + chat_identity.namespace.clone(), + &chat_identity.token_ids, + 32, + RadixExactEntry::new( + "exact".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("seeding the radix must succeed"); + + assert!( + kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3]), + "the exact node is retained" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2]), + "a shorter query must not be certified by the longer retained entry" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[1, 2, 3, 4]), + "a longer identity must not be certified by a retained shorter prefix" + ); + assert!( + !kv.retained_exact_identity(&chat_identity.namespace, &[9, 9, 9]), + "an unrelated identity is absent" + ); +} + +/// record_exact_state releases its real credit when the identity is +/// already recorded. +#[test] +fn record_exact_state_releases_credit_when_already_recorded() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + chat_identity.namespace.clone(), + &chat_identity.token_ids, + 32, + RadixExactEntry::new( + "pre-existing".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("pre-seeding the radix must succeed"); + let result = kv.record_exact_state( + &mut runtime, + SESSION, + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!( + matches!(result, Ok(None)), + "already-recorded identity skips" + ); + assert_eq!( + outstanding(&kv), + 0, + "credit released on the already-recorded skip" + ); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} + +fn seed_exact_state(kv: &KvStageIntegration, identity: &crate::kv_integration::PrefillKvIdentity) { + kv.radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert_recurrent( + identity.namespace.clone(), + &identity.token_ids, + 32, + RadixExactEntry::new( + "pre-existing".to_string(), + ExactStatePayload::full_state(vec![9]), + ExactStateExtra::default(), + true, + ), + ) + .expect("pre-seeding the radix must succeed"); +} + +fn record_at_session_end( + kv: &Arc, + runtime: &mut RuntimeState, + identity: &crate::kv_integration::PrefillKvIdentity, +) -> anyhow::Result { + kv.record_exact_state_at_session_end( + runtime, + SESSION, + identity, + CaptureAdmission::BestEffort, + None, + true, + ) +} + +/// A deferred capture of a checkpoint the cache already holds copies +/// nothing at registration. (The modelless runtime fails any export, so +/// reaching one would return an error.) +#[test] +fn a_deferred_capture_of_a_cached_checkpoint_skips_at_registration() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + seed_exact_state(&kv, &chat_identity); + + let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); + + assert!( + matches!( + captured, + Ok(crate::kv_integration::SessionEndCapture::Skipped) + ), + "{captured:?}" + ); + assert_eq!(outstanding(&kv), 0); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} + +/// A miss, and a radix too busy to say, both go on to copy the +/// recurrent state; session-end admission checks the radix again. +#[test] +fn a_deferred_capture_goes_ahead_on_a_miss_or_a_busy_radix() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + + assert!( + record_at_session_end(&kv, &mut runtime, &chat_identity).is_err(), + "a miss reaches the recurrent export" + ); + + seed_exact_state(&kv, &chat_identity); + let radix_guard = kv.radix.lock().unwrap(); + let captured = record_at_session_end(&kv, &mut runtime, &chat_identity); + drop(radix_guard); + assert!( + captured.is_err(), + "a busy radix reaches the recurrent export" + ); + assert_eq!(outstanding(&kv), 0); +} + +/// record_exact_state releases its real credit when the payload export +/// fails (unknown session here), and nothing is enqueued. +#[test] +fn record_exact_state_releases_credit_when_export_fails() { + let (kv, config) = harness(); + let mut runtime = RuntimeState::new_modelless_for_test(1); + let chat_identity = identity(&kv, &config, &[1, 2, 3]); + let result = kv.record_exact_state( + &mut runtime, + "missing-session", + &chat_identity, + CaptureAdmission::BestEffort, + ); + assert!(result.is_err(), "exporting an unknown session must fail"); + assert_eq!(outstanding(&kv), 0, "credit released when the export fails"); + assert!(kv.inflight_records.lock().unwrap().is_empty()); +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs index 540cbcede7..487f0bc9ac 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs @@ -22,7 +22,7 @@ impl KvStageIntegration { // Verification stays outside the runtime lock. Unix can reuse the // load-time digest through a strong file fingerprint; other platforms // recheck bytes when equivalent identity/change-time evidence is absent. - let content = content.filter(|proof| proof.still_matches(config)); + let content = content.and_then(|proof| proof.revalidate(config)); Self::from_loaded_model_with_l3(config, kind, memory, content, || Ok(manager), observer) } diff --git a/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs b/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs new file mode 100644 index 0000000000..2e890d61b2 --- /dev/null +++ b/skippy/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs @@ -0,0 +1,213 @@ +use super::*; +use crate::kv_integration::RadixResidentEntry; + +#[test] +fn exact_state_retention_floor_survives_a_hard_cap_blind_to_recurrent_state() { + // Regression: the byte limits are derived from attention KV metadata, + // so hybrid snapshots (recurrent state the estimate cannot see) can + // push the retained working set past the hard cap. The retention floor + // must keep every concurrent session's entry; collapsing to a single + // entry made sessions evict each other on every request. + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + // Each snapshot is 32 bytes; four of them (128) exceed the hard cap + // of 80 even though each individually fits the 8x headroom. + let oversized_for_attention_estimate = limits(10, 80); + for index in 0..4 { + store_exact_radix_record( + &radix, + &blobs, + 512, + oversized_for_attention_estimate, + None, + None, + pending( + &format!("session-{index}"), + &[1, index + 2], + &distinct_payload(index as u8, 32), + &budget, + ), + ) + .unwrap(); + } + // Distinct blocks, so the retained set really is past the hard cap and + // the pre-floor policy would have evicted down to one entry. + assert!(blobs.lock().unwrap().physical_bytes() > 80); + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 4); + for index in 0..4 { + assert!( + radix.lookup_recurrent("model", &[1, index + 2]).is_some(), + "session {index} must retain its exact-state entry" + ); + } +} + +/// Payload bytes that dedupe into distinct 4-byte blocks per `seed`. +fn distinct_payload(seed: u8, len: usize) -> Vec { + (0..len) + .map(|offset| seed.wrapping_mul(64).wrapping_add(offset as u8)) + .collect() +} + +fn store_sessions( + radix: &Mutex>, + blobs: &Mutex, + limits: ExactStateByteLimits, + sessions: &[(&str, &[i32], u8)], +) { + let budget = StorageBudget::new(); + for (page, tokens, seed) in sessions { + store_exact_radix_record( + radix, + blobs, + 512, + limits, + None, + None, + pending(page, tokens, &distinct_payload(*seed, 32), &budget), + ) + .unwrap(); + } +} + +#[test] +fn explicit_exact_budget_stays_a_strict_ceiling_past_the_retention_floor() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let explicit_ceiling = ExactStateByteLimits { + soft_bytes: 10, + hard_bytes: 40, + hard_is_explicit: true, + }; + store_sessions( + &radix, + &blobs, + explicit_ceiling, + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ], + ); + // One indivisible 32-byte snapshot fits the ceiling; a second does not. + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 1); + assert!(blobs.lock().unwrap().physical_bytes() <= 40); +} + +#[test] +fn explicit_exact_budget_evicts_a_continuation_when_its_parent_is_leased() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let explicit_ceiling = ExactStateByteLimits { + soft_bytes: 10, + hard_bytes: 40, + hard_is_explicit: true, + }; + let checkpoint = [1, 2]; + let continuation = [1, 2, 3]; + store_sessions(&radix, &blobs, explicit_ceiling, &[("a", &checkpoint, 0)]); + radix + .lock() + .unwrap() + .acquire_recurrent("model", &checkpoint) + .unwrap(); + store_sessions( + &radix, + &blobs, + explicit_ceiling, + &[("a-continued", &continuation, 1)], + ); + + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 1); + assert!(radix.recurrent_exact("model", &continuation).is_none()); + assert!(radix.release_recurrent("model", &checkpoint)); + assert_eq!(blobs.lock().unwrap().physical_bytes(), 32); +} + +#[test] +fn unbounded_byte_limits_keep_every_entry_the_entry_limit_allows() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + store_sessions( + &radix, + &blobs, + limits(0, 0), + &[ + ("a", &[1, 2], 0), + ("b", &[1, 3], 1), + ("c", &[1, 4], 2), + ("d", &[1, 5], 3), + ("e", &[1, 6], 4), + ], + ); + assert_eq!(radix.lock().unwrap().stats().recurrent_entries, 5); +} + +#[test] +fn retention_floor_keeps_each_sessions_latest_continuation() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + // Session A stores a prefill and a post-decode checkpoint between the + // other sessions' prefills. Five snapshots exceed the derived hard + // cap; the superseded prefill must go, not another session's only one. + store_sessions( + &radix, + &blobs, + limits(10, 80), + &[ + ("a-prefill", &[1, 2], 0), + ("b", &[1, 3], 1), + ("a-decode", &[1, 2, 9, 9], 2), + ("c", &[1, 4], 3), + ("d", &[1, 5], 4), + ], + ); + let mut radix = radix.lock().unwrap(); + assert!(radix.lookup_recurrent("model", &[1, 2]).is_none()); + for tokens in [&[1, 2, 9, 9][..], &[1, 3], &[1, 4], &[1, 5]] { + assert!( + radix.lookup_recurrent("model", tokens).is_some(), + "latest continuation {tokens:?} must survive" + ); + } +} + +#[test] +fn entry_limit_prefers_superseded_checkpoints_to_other_conversations() { + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + let limits = limits(0, 0); + let store = |page, tokens, seed| { + store_exact_radix_record( + &radix, + &blobs, + 4, + limits, + None, + None, + pending(page, tokens, &distinct_payload(seed, 32), &budget), + ) + .unwrap(); + }; + store("a-prefill", &[1, 2], 0); + store("b", &[1, 3], 1); + store("c", &[1, 4], 2); + store("d", &[1, 5], 3); + radix + .lock() + .unwrap() + .lookup_recurrent("model", &[1, 2]) + .unwrap(); + store("a-continued", &[1, 2, 9], 4); + + let mut radix = radix.lock().unwrap(); + assert!(radix.recurrent_exact("model", &[1, 2]).is_none()); + for tokens in [&[1, 2, 9][..], &[1, 3], &[1, 4], &[1, 5]] { + assert!(radix.recurrent_exact("model", tokens).is_some()); + } +} diff --git a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs index 18fdddd6d5..037acee7e3 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -83,20 +83,17 @@ pub(crate) enum SessionEndCapture { Deferred, } -/// Total in-flight exact-state payloads per stage — exporting, queued in the -/// recorder channel, or held by the recorder worker. Sized as channel -/// capacity (1) plus one worker-held record. +/// Minimum in-flight exact-state payload slots per stage, including exports, +/// queued records, and the record held by the worker. pub const EXACT_STATE_ADMISSION_TOTAL: usize = 2; /// Slots reserved for [`CaptureAdmission::Continuation`]: BestEffort captures /// can never occupy more than `TOTAL - RESERVED` slots, so a continuation /// boundary always finds a slot unless the whole budget is exhausted. pub const EXACT_STATE_ADMISSION_RESERVED: usize = 1; -/// Per-stage total admission slots. The single-stream floor is the legacy -/// constant (channel capacity plus one worker-held record); a stage serving -/// `lane_count` concurrent lanes admits one in-flight payload per lane plus -/// the recorder's own headroom, because a capture declined under admission -/// loses that session's exchange permanently — the next turn re-prefills it. +/// Per-stage admission slots, with one in-flight payload per lane plus one +/// slot reserved for continuations. The recorder channel can hold the entire +/// admitted set even when the worker holds no record. /// Concurrent multi-turn sessions measured on the fleet starved at the floor: /// whichever session completed first held the only best-effort slot and every /// other lane's record was declined for the whole wave. diff --git a/skippy/crates/skippy-serving/src/kv_integration/mod.rs b/skippy/crates/skippy-serving/src/kv_integration/mod.rs index 2bbab6da94..dbeb1390b6 100644 --- a/skippy/crates/skippy-serving/src/kv_integration/mod.rs +++ b/skippy/crates/skippy-serving/src/kv_integration/mod.rs @@ -273,8 +273,7 @@ pub enum StagePrefixCachePayload { FullState, } -/// Entry backstop on the record queue. The binding limit is -/// [`EXACT_STATE_RECORD_QUEUE_BYTES`]; this only caps bookkeeping. +/// Baseline serving recorder queue capacity and fixed durable spill queue capacity. pub(crate) const EXACT_STATE_RECORD_CAPACITY: usize = 8; /// Payload bytes the record queue may hold. A record that does not fit is diff --git a/skippy/crates/skippy-serving/src/runtime_state.rs b/skippy/crates/skippy-serving/src/runtime_state.rs index f928553eeb..17a83be2fb 100644 --- a/skippy/crates/skippy-serving/src/runtime_state.rs +++ b/skippy/crates/skippy-serving/src/runtime_state.rs @@ -433,10 +433,9 @@ fn runtime_from_verified_model( config: &StageConfig, model: StageModel, observer: Option>, - content: Option, + content: Option>, ) -> Result>> { // Verification and its post-open file checks finished outside this lock. - let content = content.map(Arc::new); let runtime = runtime_from_loaded_model(config, model, observer)?; panic_recovery::lock_runtime(&runtime).verified_model_content = content; Ok(runtime) diff --git a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs index d1e6747b92..2234bda697 100644 --- a/skippy/crates/skippy-serving/src/runtime_state/model_content.rs +++ b/skippy/crates/skippy-serving/src/runtime_state/model_content.rs @@ -6,7 +6,10 @@ use std::{ fs::{File, Metadata}, io::{BufReader, Read}, path::{Path, PathBuf}, - sync::atomic::{AtomicBool, Ordering}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, time::{Instant, SystemTime}, }; @@ -83,7 +86,7 @@ impl VerifiedModelContent { pub(crate) fn verify_during_load( config: &StageConfig, load: impl FnOnce() -> Result, - ) -> Result<(T, Option)> { + ) -> Result<(T, Option>)> { #[cfg(unix)] let (model, content) = match Self::observe_files(config).ok().flatten() { // Recent stamps cannot prove the bytes the loader reads, so hash @@ -102,7 +105,10 @@ impl VerifiedModelContent { let content = Self::observe(config).ok().flatten(); (load()?, content) }; - Ok((model, content.filter(|proof| proof.still_matches(config)))) + Ok(( + model, + content.and_then(|proof| Arc::new(proof).revalidate(config)), + )) } #[cfg(any(not(unix), test))] @@ -123,6 +129,7 @@ impl VerifiedModelContent { capture_files(files).map(Some) } + #[cfg(test)] fn from_files(files: Vec<(String, PathBuf)>) -> Result { Self::from_observed(capture_files(files)?, &AtomicBool::new(false)) } @@ -186,33 +193,18 @@ impl VerifiedModelContent { }) } - /// Reject a proof if model input selection or bytes changed while opening. - pub(crate) fn still_matches(&self, config: &StageConfig) -> bool { - let Ok(files) = source_files(config) else { - return false; - }; - let unchanged = files.len() == self.files.len() - && files.iter().zip(&self.files).all( - |((name, path), (expected_name, expected_path, stamp))| { - name == expected_name - && path == expected_path - && std::fs::metadata(path).is_ok_and(|metadata| { - metadata.is_file() && FileStamp::read(&metadata) == *stamp - }) - }, - ); - if !unchanged { - return false; + /// Reuse strong file stamps or refresh the proof by hashing the same inputs. + pub(crate) fn revalidate(self: Arc, config: &StageConfig) -> Option> { + let files = capture_files(source_files(config).ok()?).ok()?; + if files != self.files { + return None; } if cfg!(unix) && !self.racy { - return true; - } - { - // Off Unix, and for stamps inside the racy window, size and - // timestamps are not a strong file identity. Recheck actual content after model open and at - // backend construction rather than trusting preserved timestamps. - Self::from_files(files).is_ok_and(|current| current.digest == self.digest) + return Some(self); } + // Recent or missing timestamps and non-Unix stamps require a digest check. + let refreshed = Self::from_observed(files, &AtomicBool::new(false)).ok()?; + (refreshed.digest == self.digest).then(|| Arc::new(refreshed)) } pub(crate) fn bind(&self, identity: &str) -> String { @@ -485,8 +477,9 @@ mod tests { source_model_sha256: Some("ab".repeat(32)), ..StageConfig::default() }; - let first = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); - assert!(first.still_matches(&config)); + let first = + Arc::new(VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap()); + assert!(first.clone().revalidate(&config).is_some()); let modified = model.metadata().unwrap().modified().unwrap(); std::fs::write(&model, b"other weights").unwrap(); File::options() @@ -495,7 +488,7 @@ mod tests { .unwrap() .set_times(std::fs::FileTimes::new().set_modified(modified)) .unwrap(); - assert!(!first.still_matches(&config)); + assert!(first.clone().revalidate(&config).is_none()); let second = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); assert_ne!(first.bind("same namespace"), second.bind("same namespace")); config.model_path = Some( @@ -504,7 +497,24 @@ mod tests { .to_string_lossy() .into_owned(), ); - assert!(!second.still_matches(&config)); + assert!(Arc::new(second).revalidate(&config).is_none()); + } + + #[test] + fn revalidation_keeps_the_refreshed_proof_when_it_rehashes() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("model.gguf"); + std::fs::write(&path, b"weights").unwrap(); + let config = StageConfig { + model_path: Some(path.to_string_lossy().into_owned()), + ..StageConfig::default() + }; + let mut proof = VerifiedModelContent::from_files(source_files(&config).unwrap()).unwrap(); + proof.racy = true; + let proof = Arc::new(proof); + let refreshed = proof.clone().revalidate(&config).unwrap(); + assert!(!Arc::ptr_eq(&refreshed, &proof)); + assert_eq!(refreshed.digest, proof.digest); } #[test] diff --git a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index e4cff0e14b..271cd5093a 100644 --- a/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/skippy/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -1,4 +1,4 @@ -From 48b4b40f4ae12d1afc0a62bcc99fcfc7727da4b3 Mon Sep 17 00:00:00 2001 +From bdf3bfa0cce61bfb5fbd467c1f2c3788fbf11422 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 Subject: [PATCH] feat(skippy): realize admitted stages from live graphs @@ -38,7 +38,7 @@ Co-authored-by: Melkor stage_model); -+ skippy_synchronize_context_if_pending(first->stage_model); + + size_t sampled_index = 0; ++ // Synchronize only when this iteration consumes GPU results: a sampled ++ // last token or a batched activation export. Prefill ++ // chunks without any of those return with the context still pending, so ++ // the scheduler prepares and the backend encodes the next chunk while ++ // the GPU still executes this one; command-queue order sequences the ++ // chunks' KV writes and reads. The Rust sizing protocol always passes a ++ // non-null descriptor array, so gate on the sessions that actually emit ++ // activation frames rather than on the array pointer. ++ const bool consumes_gpu_results = std::any_of( ++ requests, requests + request_count, ++ [](const skippy_iteration_request & request) { ++ return request.sample_last || ++ skippy_emits_activation_frame(request.session); ++ }); ++ if (consumes_gpu_results) { ++ skippy_synchronize_context_if_pending(first->stage_model); ++ } + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; + status = skippy_copy_batched_exports( @@ -17966,5 +17982,5 @@ index c41e91d61..eee60d81d 100644 llama_token token[3] = { 5, 6, 7 }; llama_pos pos[3] = { 3, 4, 5 }; -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index 984f82f56c..218a251ddd 100644 --- a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -1,8 +1,7 @@ -From b9ec689e4254c785289de4dbabf440d34f8e9fd4 Mon Sep 17 00:00:00 2001 +From d2883abb63c556f8b3807a85c3d9dec546286f9a Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 -Subject: [PATCH 03/32] feat(llama): integrate live stage planning and - execution +Subject: [PATCH] feat(llama): integrate live stage planning and execution Graph node-budget migration debt: @@ -20,12 +19,13 @@ the owning model builders supply that bound, retain the shared LoRA and sampler additions, and test reserved ubatch sizes and stage boundaries against actual node counts on CPU, Metal and CUDA. Remove the architecture branches only after those bounds cover their current allowances and parity/reservation tests pass. +Co-authored-by: Melkor --- include/llama.h | 7 + src/llama-arch.cpp | 22 + src/llama-arch.h | 2 + - src/llama-context.cpp | 573 +++++++++-- + src/llama-context.cpp | 587 +++++++++-- src/llama-context.h | 99 +- src/llama-ext.h | 6 + src/llama-graph.h | 6 + @@ -47,7 +47,7 @@ those bounds cover their current allowances and parity/reservation tests pass. src/llama-quant.cpp | 12 +- src/llama.cpp | 91 +- src/skippy-verify-checkpoint.h | 24 + - 25 files changed, 3066 insertions(+), 338 deletions(-) + 25 files changed, 3074 insertions(+), 344 deletions(-) create mode 100644 src/skippy-verify-checkpoint.h diff --git a/include/llama.h b/include/llama.h @@ -139,7 +139,7 @@ index 3b8f45d26..cd34e36a9 100644 LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, LLM_KV_ATTENTION_INDEXER_TYPES, diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index d597273a2..082b3229c 100644 +index d597273a2..cd9a017fa 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -13,10 +13,16 @@ @@ -473,7 +473,49 @@ index d597273a2..082b3229c 100644 if (sampler && model.split_mode() == LLAMA_SPLIT_MODE_TENSOR) { static bool warned = false; if (!warned) { -@@ -1779,6 +1870,7 @@ void llama_context::set_adapters_lora(llama_adapter_lora ** adapters, size_t n_a +@@ -1721,7 +1812,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + warned = true; + } + if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a ++ // detach must not force the next request to re-reserve. + } + sampling.samplers.erase(seq_id); + return false; +@@ -1740,6 +1832,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers[seq_id] = sampler; + ++ // Each attached chain can grow the graph, including a replacement. ++ // Preserve any reservation already required by a shape change. + sched_need_reserve = true; + + return true; +@@ -1748,10 +1842,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + if (sampler && !can_offload) { + LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id); + +- if (sampling.samplers.count(seq_id) > 0) { +- sched_need_reserve = true; +- } +- ++ // Detaching only shrinks what the reservation must cover; a detach ++ // must not force the next request to re-reserve. + sampling.samplers.erase(seq_id); + + return false; +@@ -1759,7 +1851,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { + + sampling.samplers.erase(seq_id); + +- sched_need_reserve = true; ++ // Detaching only shrinks what the reservation must cover; a detach must ++ // not force the next request to re-reserve. + + return true; + } +@@ -1779,6 +1872,7 @@ void llama_context::set_adapters_lora(llama_adapter_lora ** adapters, size_t n_a } } @@ -481,7 +523,7 @@ index d597273a2..082b3229c 100644 sched_need_reserve = true; } -@@ -1818,12 +1910,18 @@ bool llama_context::set_adapter_cvec( +@@ -1818,12 +1912,18 @@ bool llama_context::set_adapter_cvec( bool res = cvec->apply(model, data, len, n_embd, il_start, il_end); @@ -501,7 +543,7 @@ index d597273a2..082b3229c 100644 if (mctx && !mctx->apply()) { LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); ret = GGML_STATUS_FAILED; -@@ -1835,7 +1933,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1835,7 +1935,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll // the new graph parameters // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters @@ -510,7 +552,7 @@ index d597273a2..082b3229c 100644 if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); -@@ -1867,6 +1965,16 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1867,6 +1967,16 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return nullptr; } @@ -527,7 +569,7 @@ index d597273a2..082b3229c 100644 if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) { LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__); ret = GGML_STATUS_ALLOC_FAILED; -@@ -1881,7 +1989,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1881,7 +1991,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll //const auto t_start_us = ggml_time_us(); // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated @@ -536,7 +578,7 @@ index d597273a2..082b3229c 100644 //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); } -@@ -1899,6 +2007,12 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll +@@ -1899,6 +2009,12 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll } int llama_context::encode(const llama_batch_ext & batch_inp) { @@ -549,7 +591,7 @@ index d597273a2..082b3229c 100644 if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; -@@ -1936,6 +2050,10 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1936,6 +2052,10 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens"); @@ -560,7 +602,7 @@ index d597273a2..082b3229c 100644 // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed if (!embd_seq.empty()) { -@@ -1943,11 +2061,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1943,11 +2063,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } embd_seq.clear(); @@ -573,7 +615,7 @@ index d597273a2..082b3229c 100644 n_queued_tokens += n_tokens; -@@ -1974,7 +2088,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1974,7 +2090,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { cparams.causal_attn = false; ggml_status status; @@ -582,7 +624,7 @@ index d597273a2..082b3229c 100644 cparams.causal_attn = causal_attn_org; -@@ -2094,6 +2208,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -2094,6 +2210,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return 0; } @@ -607,7 +649,7 @@ index d597273a2..082b3229c 100644 template static void copy_tensor_async_rows( const std::vector & tensors, -@@ -2147,9 +2279,15 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); @@ -679,7 +721,7 @@ index d597273a2..082b3229c 100644 llama_memory_context_ptr mctx; -@@ -2284,7 +2422,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2284,7 +2424,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (!did_optimize) { did_optimize = true; @@ -688,7 +730,7 @@ index d597273a2..082b3229c 100644 LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens()); continue; -@@ -2312,11 +2450,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2312,11 +2452,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -2; }; @@ -700,7 +742,7 @@ index d597273a2..082b3229c 100644 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2375,7 +2508,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2375,7 +2510,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_status status; @@ -714,7 +756,7 @@ index d597273a2..082b3229c 100644 if (!res) { // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module -@@ -2513,9 +2651,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2513,9 +2653,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { const uint32_t n_embd = hparams.n_embd_out(); float * embd_nextn_out = embd_nextn.data + offset*n_embd; @@ -738,7 +780,7 @@ index d597273a2..082b3229c 100644 extract_all_idxs = extract_all_idxs || !masked; } } -@@ -2527,7 +2678,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2527,7 +2680,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { embd_batch_idxs.insert(embd_batch_idxs.end(), batch_idxs.begin(), batch_idxs.end()); } @@ -749,7 +791,7 @@ index d597273a2..082b3229c 100644 const auto stride = n_vocab; // async copy the sampling data from the backend to the host -@@ -2539,6 +2692,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2539,6 +2694,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { n_outputs_prev += n_outputs; n_tokens_prev += ubatch.n_tokens; @@ -760,7 +802,7 @@ index d597273a2..082b3229c 100644 } while (mctx->next()); if (layer_inp_dev && ev_layer_inp_written) { -@@ -2824,9 +2981,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -2824,9 +2983,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -773,7 +815,7 @@ index d597273a2..082b3229c 100644 for (size_t s = 0; s < output_swaps.size(); ++s) { const uint64_t i0 = output_swaps[s].i0; -@@ -2839,6 +2996,7 @@ void llama_context::output_reorder() { +@@ -2839,6 +2998,7 @@ void llama_context::output_reorder() { } if (embd.size > 0) { @@ -781,7 +823,7 @@ index d597273a2..082b3229c 100644 for (uint64_t k = 0; k < n_embd_out; k++) { std::swap(embd.data[i0*n_embd_out + k], embd.data[i1*n_embd_out + k]); } -@@ -2909,6 +3067,8 @@ void llama_context::output_reorder() { +@@ -2909,6 +3069,8 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { @@ -790,7 +832,7 @@ index d597273a2..082b3229c 100644 uint32_t res; if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || model.arch == LLM_ARCH_HRM_TEXT) { -@@ -2936,10 +3096,13 @@ uint32_t llama_context::graph_max_nodes() const { +@@ -2936,10 +3098,13 @@ uint32_t llama_context::graph_max_nodes() const { // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft res = std::max(1024u, 12u*model.n_tensors()); } else { @@ -808,7 +850,7 @@ index d597273a2..082b3229c 100644 } // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling -@@ -2979,7 +3142,6 @@ static void ubatch_prepare_reserve( +@@ -2979,7 +3144,6 @@ static void ubatch_prepare_reserve( } } @@ -816,7 +858,7 @@ index d597273a2..082b3229c 100644 std::vector sampler_seqs; std::vector has_sampler(n_seqs, false); for (const auto & entry : samplers) { -@@ -2987,40 +3149,83 @@ static void ubatch_prepare_reserve( +@@ -2987,40 +3151,83 @@ static void ubatch_prepare_reserve( if (seq_id < 0 || (uint32_t) seq_id >= n_seqs) { continue; } @@ -907,7 +949,7 @@ index d597273a2..082b3229c 100644 LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); -@@ -3045,16 +3250,40 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3045,16 +3252,40 @@ ggml_cgraph * llama_context::graph_reserve( llama_batch_allocr balloc(model.hparams.n_pos_per_embd()); llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs); @@ -949,7 +991,7 @@ index d597273a2..082b3229c 100644 // check the graph before scheduling: cross-backend copies break the producer chain that the check follows if (!hadamard_verified && gf && (!model.hdmd.rot.empty() || !model.hdmd.inv.empty())) { -@@ -3063,6 +3292,130 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3063,6 +3294,130 @@ ggml_cgraph * llama_context::graph_reserve( } this->n_input_tensors = llama_graph_n_input_tensors(gf); @@ -1080,7 +1122,7 @@ index d597273a2..082b3229c 100644 this->n_outputs = save_n_outputs; // initialize scheduler with the specified graph -@@ -3085,7 +3438,18 @@ llm_graph_params llama_context::graph_params( +@@ -3085,7 +3440,18 @@ llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, const llama_memory_context_i * mctx, @@ -1100,7 +1142,7 @@ index d597273a2..082b3229c 100644 return { /*.model =*/ &model, /*.hparams =*/ model.hparams, -@@ -3106,6 +3470,9 @@ llm_graph_params llama_context::graph_params( +@@ -3106,6 +3472,9 @@ llm_graph_params llama_context::graph_params( /*.h_nextn_dev =*/ cparams.embeddings_nextn_dev ? h_nextn_dev : nullptr, /*.h_nextn_src =*/ supports_state_row() ? cparams.ctx_state_src->get_h_nextn_dev() : nullptr, /*.samplers =*/ sampling.samplers, @@ -1110,7 +1152,7 @@ index d597273a2..082b3229c 100644 /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, -@@ -4325,7 +4692,8 @@ void llama_context::opt_epoch_iter( +@@ -4325,7 +4694,8 @@ void llama_context::opt_epoch_iter( auto * res = get_gf_res_prev(); @@ -1120,7 +1162,7 @@ index d597273a2..082b3229c 100644 // the optimizer graph is allocated outside sched, so the next decode must rebuild gf_res_prev_active = nullptr; -@@ -4431,7 +4799,7 @@ llama_context_params llama_context_default_params() { +@@ -4431,7 +4801,7 @@ llama_context_params llama_context_default_params() { /*.n_seq_max =*/ 1, /*.n_rs_seq =*/ 0, /*.n_outputs_max =*/ 0, @@ -1129,7 +1171,7 @@ index d597273a2..082b3229c 100644 /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS, /*.ctx_type =*/ LLAMA_CONTEXT_TYPE_DEFAULT, -@@ -4469,9 +4837,10 @@ llama_context_params llama_context_default_params() { +@@ -4469,9 +4839,10 @@ llama_context_params llama_context_default_params() { return result; } @@ -1143,7 +1185,7 @@ index d597273a2..082b3229c 100644 if (!model) { LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__); return nullptr; -@@ -4491,6 +4860,10 @@ llama_context * llama_init_from_model( +@@ -4491,6 +4862,10 @@ llama_context * llama_init_from_model( LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__); params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; } @@ -1154,7 +1196,7 @@ index d597273a2..082b3229c 100644 if (model->split_mode() == LLAMA_SPLIT_MODE_TENSOR) { if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) { -@@ -4590,15 +4963,14 @@ llama_context * llama_init_from_model( +@@ -4590,15 +4965,14 @@ llama_context * llama_init_from_model( model->hparams.pooling_type, params.pooling_type); } @@ -1172,7 +1214,7 @@ index d597273a2..082b3229c 100644 const auto & cparams = ctx->get_cparams(); if (cparams.rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN && cparams.rope_freq_scale != model->hparams.rope_freq_scale_train) { -@@ -4615,6 +4987,12 @@ llama_context * llama_init_from_model( +@@ -4615,6 +4989,12 @@ llama_context * llama_init_from_model( return nullptr; } @@ -1185,7 +1227,7 @@ index d597273a2..082b3229c 100644 // deprecated llama_context * llama_new_context_with_model( llama_model * model, -@@ -4861,7 +5239,8 @@ struct ggml_cgraph * llama_graph_reserve( +@@ -4861,7 +5241,8 @@ struct ggml_cgraph * llama_graph_reserve( if (memory) { mctx = memory->init_full(); } @@ -1195,7 +1237,7 @@ index d597273a2..082b3229c 100644 } // llama adapter API -@@ -5113,13 +5492,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla +@@ -5113,13 +5494,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla // compat: llama_batch -> llama_batch_ext -> encode/decode int llama_context::encode(const llama_batch & batch_inp) { @@ -1225,7 +1267,7 @@ index d597273a2..082b3229c 100644 } /// -@@ -5138,7 +5529,11 @@ int32_t llama_encode( +@@ -5138,7 +5531,11 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { @@ -5369,3 +5411,6 @@ index 000000000..8793000c1 + checkpoints.erase(it); + return true; +} +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 4a36fdd188..a45d5f2dbd 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -1,4 +1,4 @@ -From 5d84a67de94d53a20831950c3189ccbee0e1dc0c Mon Sep 17 00:00:00 2001 +From 45535949e6a2493bf66107ac3e1d8ae2e7043e69 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:43 +1100 Subject: [PATCH] test(skippy): cover live graph and state contracts @@ -6,7 +6,7 @@ Subject: [PATCH] test(skippy): cover live graph and state contracts Co-authored-by: Melkor --- src/CMakeLists.txt | 9 + - src/skippy/tests/async_state.cpp | 208 ++ + src/skippy/tests/async_state.cpp | 210 +++ .../tests/cast_destination_regression.h | 27 + src/skippy/tests/embedding_input_regression.h | 91 + src/skippy/tests/graph_build_inputs.cpp | 948 ++++++++++ @@ -45,7 +45,7 @@ Co-authored-by: Melkor ctx->sched_reserve(); + CHECK(first->ctx->get_sched_reserve_count() > reserved); + decode_attached_samplers(first, second, 1); ++ const uint64_t reserved_before_detach = first->ctx->get_sched_reserve_count(); + CHECK(llama_set_sampler(first->ctx, first->seq_id, nullptr)); + first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() == reserved_before_detach); + llama_sampler_free(replacement); + llama_sampler_free(shape_chain); +} @@ -11165,5 +11167,5 @@ index 000000000..d09acccb4 + return 0; +} -- -2.54.0 (Apple Git-157) +2.56.0 diff --git a/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch b/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch index 0d58d5379f..68feb16786 100644 --- a/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch +++ b/skippy/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch @@ -1,19 +1,18 @@ -From 20bd1020fa04e7f55bdf30fa2201abbd20a53213 Mon Sep 17 00:00:00 2001 +From 4762ecd45539dcd02163ecc3111ff665db043fbd Mon Sep 17 00:00:00 2001 From: IvGolovach <20299097+IvGolovach@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:00:00 -0700 -Subject: [PATCH 10/32] feat(skippy): read selected token scores in causal - batches +Subject: [PATCH] feat(skippy): read selected token scores in causal batches Keep full vocabulary logits on the terminal worker and read bounded conditional log probabilities before another iteration can replace them. Readouts do not invoke samplers or advance generation history. --- include/skippy/execution.h | 19 ++++++++++ - src/CMakeLists.txt | 4 +++ - src/skippy/execution-batch.cpp | 52 +++++++++++++++++++++++++++- - src/skippy/selected_logits.h | 43 +++++++++++++++++++++++ + src/CMakeLists.txt | 4 ++ + src/skippy/execution-batch.cpp | 56 ++++++++++++++++++++++++++-- + src/skippy/selected_logits.h | 43 +++++++++++++++++++++ src/skippy/tests/selected_logits.cpp | 25 +++++++++++++ - 5 files changed, 142 insertions(+), 1 deletion(-) + 5 files changed, 144 insertions(+), 3 deletions(-) create mode 100644 src/skippy/selected_logits.h create mode 100644 src/skippy/tests/selected_logits.cpp @@ -55,7 +54,7 @@ index 7098677d8..bf9fb497c 100644 /** diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 2bc7d6f6e..05108ad38 100644 +index dc8465589..a2cd419b3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -168,6 +168,10 @@ endif() @@ -70,7 +69,7 @@ index 2bc7d6f6e..05108ad38 100644 skippy/tests/hardware_application_probe.cpp) target_include_directories(skippy-hardware-application-probe PRIVATE .) diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 2b9593e0c..86ea1ed55 100644 +index 31a65905b..07ccf0b7a 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -5,6 +5,7 @@ @@ -150,7 +149,25 @@ index 2b9593e0c..86ea1ed55 100644 for (int32_t axis = 0; axis < n_pos_per_embd; ++axis) { const size_t destination = static_cast(axis)*total_tokens + flat; if (request.positions != nullptr) { -@@ -429,6 +469,16 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -415,7 +455,7 @@ enum skippy_status skippy_iteration_batch_sampled( + + size_t sampled_index = 0; + // Synchronize only when this iteration consumes GPU results: a sampled +- // last token or a batched activation export. Prefill ++ // last token, a causal readout, or a batched activation export. Prefill + // chunks without any of those return with the context still pending, so + // the scheduler prepares and the backend encodes the next chunk while + // the GPU still executes this one; command-queue order sequences the +@@ -425,7 +465,7 @@ enum skippy_status skippy_iteration_batch_sampled( + const bool consumes_gpu_results = std::any_of( + requests, requests + request_count, + [](const skippy_iteration_request & request) { +- return request.sample_last || ++ return request.sample_last || request.readout != nullptr || + skippy_emits_activation_frame(request.session); + }); + if (consumes_gpu_results) { +@@ -445,6 +485,16 @@ enum skippy_status skippy_iteration_batch_sampled( request.session->sampling_backend_row_invalid = false; request.session->n_past += static_cast(request.token_count); skippy_record_tokens(request.session, request.token_ids, request.token_count); @@ -247,3 +264,6 @@ index 000000000..d33237d1a + if (skippy_selected_log_probabilities(inf.data(), inf.size(), selected.data() + 1, 1, result.data())) return 8; + return 0; +} +-- +2.56.0 + diff --git a/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch index fed63180f3..284199d0a0 100644 --- a/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch +++ b/skippy/llama_cpp/patches/0019-skippy-report-native-trace-spans-and-GPU-command-tim.patch @@ -1,8 +1,7 @@ -From cf937afd998fce2d584ed5ed092205deded25a01 Mon Sep 17 00:00:00 2001 +From a922d83e220feb2a4f00fd7d8b9837c131aee5b7 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 2 Nov 2026 09:00:00 +1100 -Subject: [PATCH 19/32] skippy: report native trace spans and GPU command - timing +Subject: [PATCH] skippy: report native trace spans and GPU command timing skippy/tracing.h reports where time goes inside a native call, for a caller that already times the call itself. skippy_set_native_span_callback @@ -463,7 +462,7 @@ index e12c55a39..f89c8ebe6 100644 [cmd_buf commit]; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index 8c21125d5..7c42724af 100644 +index 9ab481093..db9889c79 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -5,6 +5,7 @@ @@ -511,7 +510,7 @@ index 8c21125d5..7c42724af 100644 if (!dev->library) { GGML_LOG_ERROR("%s: error: failed to create library\n", __func__); } -@@ -2305,6 +2314,8 @@ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { +@@ -2323,6 +2332,8 @@ static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { return true; } @@ -520,7 +519,7 @@ index 8c21125d5..7c42724af 100644 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { MTLResidencySetDescriptor * desc = [[MTLResidencySetDescriptor alloc] init]; -@@ -2364,6 +2375,10 @@ static void * ggml_metal_host_malloc(size_t n) { +@@ -2382,6 +2393,10 @@ static void * ggml_metal_host_malloc(size_t n) { } ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared) { @@ -531,7 +530,7 @@ index 8c21125d5..7c42724af 100644 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); res->dev = dev; -@@ -2434,6 +2449,10 @@ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, +@@ -2452,6 +2467,10 @@ ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, } ggml_metal_buffer_t ggml_metal_buffer_map(ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size) { @@ -542,7 +541,7 @@ index 8c21125d5..7c42724af 100644 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); res->dev = dev; -@@ -2588,6 +2607,9 @@ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * +@@ -2606,6 +2625,9 @@ void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * return; } @@ -552,7 +551,7 @@ index 8c21125d5..7c42724af 100644 @autoreleasepool { // src void * data_ptr = (void *)(uintptr_t) data; // "const cast" the src data -@@ -2644,6 +2666,8 @@ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_ten +@@ -2662,6 +2684,8 @@ void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_ten return; } @@ -1461,7 +1460,7 @@ index 000000000..e9e57357c + +#endif // SKIPPY_TRACING_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 75cb30503..6e4e9023b 100644 +index 211edbe3b..0e0970876 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -64,6 +64,7 @@ add_library(llama @@ -1473,7 +1472,7 @@ index 75cb30503..6e4e9023b 100644 skippy/graph_dependencies.cpp skippy/graph_identity.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index e460d2250..b3ec732f9 100644 +index 7cdb0c1f0..545f4eb5b 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -17,6 +17,7 @@ @@ -1484,7 +1483,7 @@ index e460d2250..b3ec732f9 100644 #include #include -@@ -499,6 +500,7 @@ llama_context::llama_context( +@@ -494,6 +495,7 @@ llama_context::llama_context( } if (!hparams.vocab_only) { @@ -1492,7 +1491,7 @@ index e460d2250..b3ec732f9 100644 // GPU backends for (const auto & dev : model.devices) { ggml_backend_t backend = ggml_backend_dev_init(dev.dev, nullptr); -@@ -580,6 +582,8 @@ llama_context::llama_context( +@@ -575,6 +577,8 @@ llama_context::llama_context( /*.no_alloc =*/ model.no_alloc(), }; @@ -1501,7 +1500,7 @@ index e460d2250..b3ec732f9 100644 memory.reset(model.create_memory(params_mem, cparams, graph_build_inputs.selection)); } -@@ -852,6 +856,8 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ +@@ -845,6 +849,8 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ return; } @@ -1510,7 +1509,7 @@ index e460d2250..b3ec732f9 100644 sched_need_reserve = false; ++sched_reserve_count; -@@ -1010,7 +1016,11 @@ void llama_context::synchronize() { +@@ -1014,7 +1020,11 @@ void llama_context::synchronize() { return; } @@ -1523,7 +1522,7 @@ index e460d2250..b3ec732f9 100644 // FIXME: if multiple single tokens are evaluated without a synchronization, // the stats will be added to the prompt evaluation stats -@@ -1138,6 +1148,8 @@ bool llama_context::memory_update( +@@ -1132,6 +1142,8 @@ bool llama_context::memory_update( } } @@ -1532,7 +1531,7 @@ index e460d2250..b3ec732f9 100644 // reset the previous graph results to make sure that they won't be reused // TODO: make mctx->apply() report if a graph reserve is needed, then reset graph results only if the memory module reset the scheduler for (auto & res : gf_res_prev) { -@@ -1790,7 +1802,13 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1926,7 +1938,13 @@ llm_graph_result * llama_context::process_ubatch( llama_memory_context_i * mctx, ggml_status & ret, const skippy_graph_build_inputs & graph_build_inputs) { @@ -1547,7 +1546,7 @@ index e460d2250..b3ec732f9 100644 LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__); ret = GGML_STATUS_FAILED; return nullptr; -@@ -1805,6 +1823,7 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1941,6 +1959,7 @@ llm_graph_result * llama_context::process_ubatch( if (!graph_reuse_disable && gf_res_prev_active == res && res->can_reuse(gparams)) { //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); @@ -1555,7 +1554,7 @@ index e460d2250..b3ec732f9 100644 // with pipeline parallelism, the previous graph_compute_async may still be running // on the GPU. we must synchronize before set_inputs to avoid overwriting input tensors -@@ -1823,7 +1842,10 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1959,7 +1978,10 @@ llm_graph_result * llama_context::process_ubatch( //const auto t_start_us = ggml_time_us(); @@ -1566,7 +1565,7 @@ index e460d2250..b3ec732f9 100644 //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); -@@ -1843,11 +1865,13 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1979,11 +2001,13 @@ llm_graph_result * llama_context::process_ubatch( return nullptr; } @@ -1580,7 +1579,7 @@ index e460d2250..b3ec732f9 100644 gf_res_prev_active = res; } -@@ -1857,12 +1881,16 @@ llm_graph_result * llama_context::process_ubatch( +@@ -1993,12 +2017,16 @@ llm_graph_result * llama_context::process_ubatch( //const auto t_start_us = ggml_time_us(); // FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated @@ -1597,7 +1596,7 @@ index e460d2250..b3ec732f9 100644 if (status != GGML_STATUS_SUCCESS) { LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status); ret = status; -@@ -2159,6 +2187,8 @@ int llama_context::decode( +@@ -2295,6 +2323,8 @@ int llama_context::decode( return encode(batch_inp, graph_build_inputs); } @@ -1606,7 +1605,7 @@ index e460d2250..b3ec732f9 100644 if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; -@@ -2219,12 +2249,14 @@ int llama_context::decode( +@@ -2361,12 +2391,14 @@ int llama_context::decode( } } @@ -1621,7 +1620,7 @@ index e460d2250..b3ec732f9 100644 const uint32_t n_tokens_all = balloc->get_n_tokens(); const uint32_t n_outputs_all = balloc->get_n_outputs(); -@@ -2265,6 +2297,8 @@ int llama_context::decode( +@@ -2407,6 +2439,8 @@ int llama_context::decode( llama_memory_context_ptr mctx; @@ -1630,7 +1629,7 @@ index e460d2250..b3ec732f9 100644 while (true) { mctx = memory->init_batch(*balloc, cparams.n_ubatch, embd_all); if (!mctx) { -@@ -2308,11 +2342,15 @@ int llama_context::decode( +@@ -2450,11 +2484,15 @@ int llama_context::decode( break; } @@ -1646,7 +1645,7 @@ index e460d2250..b3ec732f9 100644 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2399,6 +2437,9 @@ int llama_context::decode( +@@ -2557,6 +2595,9 @@ int llama_context::decode( // ggml_graph_dump_dot(gf, NULL, "llama.dot"); //} @@ -1656,7 +1655,7 @@ index e460d2250..b3ec732f9 100644 auto * t_logits = res->get_logits(); auto * t_embd = cparams.embeddings ? res->get_embd() : nullptr; auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr; -@@ -2537,10 +2578,13 @@ int llama_context::decode( +@@ -2696,10 +2737,13 @@ int llama_context::decode( copy_tensor_async_rows(res->t_candidates, sampling.candidates, stride, n_outputs_prev, sched.get(), &sampling.candidates_count); } @@ -1670,7 +1669,7 @@ index e460d2250..b3ec732f9 100644 ggml_backend_sched_synchronize(sched.get()); } } while (mctx->next()); -@@ -3106,6 +3150,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3273,6 +3317,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); @@ -1679,7 +1678,7 @@ index e460d2250..b3ec732f9 100644 if (n_tokens % n_seqs != 0) { n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs); -@@ -4121,6 +4167,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl +@@ -4288,6 +4334,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl } size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) { @@ -1687,7 +1686,7 @@ index e460d2250..b3ec732f9 100644 std::unique_ptr io; if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { io = std::make_unique(dst, size, mem_storage[seq_id]); -@@ -4140,6 +4187,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz +@@ -4307,6 +4354,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz } size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) { @@ -1696,7 +1695,7 @@ index e460d2250..b3ec732f9 100644 if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { // create a temporary io to read the magic and the src seq_id diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index fd12f9966..fe7101445 100644 +index b8fdbd578..2f4662742 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1,4 +1,5 @@ @@ -1705,7 +1704,7 @@ index fd12f9966..fe7101445 100644 #include "llama-impl.h" #include "llama-io.h" -@@ -452,6 +453,7 @@ void llama_kv_cache::init_rotation(const char * name_tag) { +@@ -457,6 +458,7 @@ void llama_kv_cache::init_rotation(const char * name_tag) { } void llama_kv_cache::clear(bool data) { @@ -1713,7 +1712,7 @@ index fd12f9966..fe7101445 100644 for (uint32_t s = 0; s < n_stream; ++s) { v_cells[s].reset(); v_heads[s] = 0; -@@ -465,6 +467,7 @@ void llama_kv_cache::clear(bool data) { +@@ -470,6 +472,7 @@ void llama_kv_cache::clear(bool data) { } bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { @@ -1721,7 +1720,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return true; -@@ -567,6 +570,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { +@@ -572,6 +575,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { } void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { @@ -1729,7 +1728,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -659,6 +663,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll +@@ -664,6 +668,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll } void llama_kv_cache::seq_keep(llama_seq_id seq_id) { @@ -1737,7 +1736,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -686,6 +691,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { +@@ -691,6 +696,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { } void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { @@ -1745,7 +1744,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -1636,6 +1642,7 @@ bool llama_kv_cache::stage_export_kv_page( +@@ -1651,6 +1657,7 @@ bool llama_kv_cache::stage_export_kv_page( size_t output_capacity, size_t * out_bytes, std::string & error) const { @@ -1753,7 +1752,7 @@ index fd12f9966..fe7101445 100644 if (out_desc == nullptr || out_bytes == nullptr) { error = "out_desc and out_bytes are required"; return false; -@@ -1878,6 +1885,7 @@ bool llama_kv_cache::stage_import_kv_page( +@@ -1893,6 +1900,7 @@ bool llama_kv_cache::stage_import_kv_page( size_t input_bytes, std::string & error, bool validate_only) { @@ -1761,7 +1760,7 @@ index fd12f9966..fe7101445 100644 if (input == nullptr) { error = "input payload is required"; return false; -@@ -3527,6 +3535,7 @@ ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_co +@@ -3574,6 +3582,7 @@ ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_co } void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const { @@ -1769,7 +1768,7 @@ index fd12f9966..fe7101445 100644 // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; -@@ -3599,6 +3608,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla +@@ -3646,6 +3655,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla } void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { @@ -1844,7 +1843,7 @@ index b7570d445..c488e921c 100644 uint32_t cell_count; diff --git a/src/llama-model.cpp b/src/llama-model.cpp -index 8ded67e17..f93cbad04 100644 +index 143c1f895..0f4d15e68 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1,4 +1,5 @@ @@ -1853,7 +1852,7 @@ index 8ded67e17..f93cbad04 100644 #include "llama-arch.h" #include "llama-ext.h" -@@ -2193,11 +2194,13 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { +@@ -2203,11 +2204,13 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } // load tensor data @@ -2021,7 +2020,7 @@ index 7167e5f7a..885b602e9 100644 int32_t rc = 0; const bool decoded = skippy_contain_native_failure( diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 40faff815..a31540652 100644 +index 7d7973520..2d34652b9 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -6,6 +6,7 @@ @@ -2049,15 +2048,15 @@ index 40faff815..a31540652 100644 int32_t decode_rc = 0; if (!skippy_contain_native_failure( out_error, [&] { decode_rc = first->ctx->decode(batch, graph_inputs); })) { -@@ -461,6 +465,8 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -460,6 +464,8 @@ enum skippy_status skippy_iteration_batch_sampled( + } skippy_mark_context_work_pending(first->stage_model); - skippy_synchronize_context_if_pending(first->stage_model); + // exports, readouts and sampling, request by request + skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); size_t sampled_index = 0; - for (size_t request_index = 0; request_index < request_count; ++request_index) { - const auto & request = requests[request_index]; + // Synchronize only when this iteration consumes GPU results: a sampled + // last token, a causal readout, or a batched activation export. Prefill diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp index bbc1c2d42..a4bf2a475 100644 --- a/src/skippy/model_loading.cpp @@ -2539,7 +2538,7 @@ index 000000000..9aa48e08c + } +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index b8b159025..638e84e37 100644 +index 7c55e2c5f..ce3fe92ac 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -185,6 +185,9 @@ llama_build_and_test(test-skippy-rerank-template.cpp) @@ -2552,7 +2551,7 @@ index b8b159025..638e84e37 100644 llama_build_and_test(test-skippy-cachegen-import.cpp) llama_build_and_test(test-skippy-sampling-suppress.cpp) llama_build_and_test(test-skippy-kv-page-export.cpp) -@@ -330,6 +333,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) +@@ -344,6 +347,7 @@ llama_build_and_test(test-chat-template.cpp LABEL behavior) if (GGML_METAL) llama_build_and_test(test-skippy-cachegen-metal.cpp) @@ -3034,5 +3033,5 @@ index 000000000..804c2f7e0 + return 0; +} -- -2.43.0 +2.56.0 diff --git a/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch index 11f828c08b..3b34a2b0eb 100644 --- a/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch +++ b/skippy/llama_cpp/patches/0020-skippy-sample-a-batch-s-requests-concurrently.patch @@ -1,7 +1,7 @@ -From 53c13a8bef39b480fb887be77cbed4602cadb63f Mon Sep 17 00:00:00 2001 +From 316ea6dea9b1b29b384fa6b7382dae0c20db8bb8 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 5 Nov 2026 01:00:00 +1100 -Subject: [PATCH 20/32] skippy: sample a batch's requests concurrently +Subject: [PATCH] skippy: sample a batch's requests concurrently An iteration's sampled requests waited for one another: after the batch's outputs were recorded, each request ran its sampler chain in turn on the @@ -48,7 +48,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 src/skippy/tests/concurrent_sampling.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 6e4e9023b..7eee0656e 100644 +index 0e0970876..7da1090f3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -82,6 +82,7 @@ add_library(llama @@ -59,7 +59,7 @@ index 6e4e9023b..7eee0656e 100644 skippy/sampling_config.cpp skippy/chat_sampling.cpp skippy/sampling_vocab.cpp -@@ -493,6 +494,17 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -502,6 +503,17 @@ if (LLAMA_STAGE_BUILD_TESTS) endfunction() add_skippy_sampling_history_state_tests(granitehybrid skippy-noalloc-granite-hybrid-fixture recurrent) @@ -78,10 +78,10 @@ index 6e4e9023b..7eee0656e 100644 NAME skippy_generate_qwen3_fixture COMMAND skippy-model-fixture-generator diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index b3ec732f9..d9068d348 100644 +index 545f4eb5b..8b751f7e4 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -1011,8 +1011,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ +@@ -1015,8 +1015,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ __func__, (t_end_us - t_start_us)/1000.0, ggml_backend_sched_get_n_copies(sched.get())); } @@ -109,7 +109,7 @@ index b3ec732f9..d9068d348 100644 return; } -@@ -2860,6 +2878,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -3031,6 +3049,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -120,7 +120,7 @@ index b3ec732f9..d9068d348 100644 const uint64_t n_embd = model.hparams.n_embd; const uint64_t n_embd_out = model.hparams.n_embd_out(); diff --git a/src/llama-context.h b/src/llama-context.h -index f8884668f..919813ac8 100644 +index d699a1088..020f55b78 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -66,6 +66,36 @@ struct llama_memory_buffer { @@ -171,10 +171,10 @@ index f8884668f..919813ac8 100644 const llama_cparams & get_cparams() const; const skippy_graph_build_inputs & get_graph_build_inputs() const; diff --git a/src/llama-graph.h b/src/llama-graph.h -index 2622c5878..54fd815ef 100644 +index 0e4431fe6..6364da9f8 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h -@@ -1674,7 +1674,7 @@ struct llm_graph_context { +@@ -1689,7 +1689,7 @@ struct llm_graph_context { int32_t state_size, int32_t n_seqs, skippy_state_kind kind, int il, @@ -307,7 +307,7 @@ index 000000000..0c253ca71 +// same time, one thread each; the rest sample first, on this thread. +std::vector skippy_sample_requests(const std::vector & requests); diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index a31540652..83c290ee2 100644 +index 2d34652b9..46b0d1a27 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -1,5 +1,6 @@ @@ -317,7 +317,7 @@ index a31540652..83c290ee2 100644 #include "skippy/errors.h" #include "skippy/graph_build_inputs.h" #include "skippy/runtime_support.h" -@@ -467,7 +468,10 @@ enum skippy_status skippy_iteration_batch_sampled( +@@ -466,7 +467,10 @@ enum skippy_status skippy_iteration_batch_sampled( // exports, readouts and sampling, request by request skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); @@ -326,10 +326,10 @@ index a31540652..83c290ee2 100644 + // once every request's outputs are recorded + std::vector samples; + std::vector sample_request_indexes; - for (size_t request_index = 0; request_index < request_count; ++request_index) { - const auto & request = requests[request_index]; - status = skippy_copy_batched_exports( -@@ -495,16 +499,19 @@ enum skippy_status skippy_iteration_batch_sampled( + // Synchronize only when this iteration consumes GPU results: a sampled + // last token, a causal readout, or a batched activation export. Prefill + // chunks without any of those return with the context still pending, so +@@ -511,16 +515,19 @@ enum skippy_status skippy_iteration_batch_sampled( if (request.sample_last && request_logits) { // Logits are indexed by the original batch row; llama.cpp handles // sparse output-row translation internally. @@ -617,5 +617,5 @@ index 000000000..0e19dbce5 + return 0; +} -- -2.43.0 +2.56.0 diff --git a/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch b/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch deleted file mode 100644 index 720f774e3b..0000000000 --- a/skippy/llama_cpp/patches/0040-perf-defer-batch-synchronization-to-export.patch +++ /dev/null @@ -1,57 +0,0 @@ -From 177290c7b51e720a90f97a830c6d9d10c3c59117 Mon Sep 17 00:00:00 2001 -From: James Dumay -Date: Tue, 17 Nov 2026 12:15:00 +1100 -Subject: [PATCH] perf(skippy): synchronize batch iterations only when results - are consumed - -The batch execution path synchronized the CUDA context immediately -after llama_decode, forcing the CPU to idle while the GPU finished. -Move the sync to the export loop and skip it entirely for iterations -that consume no GPU results: prefill chunks that neither sample their -last token, run a causal readout, nor export activation frames return -with the context still pending, so the scheduler prepares and the -backend encodes the next chunk while the GPU executes this one. -Command-queue order sequences the chunks' KV writes and reads. ---- - src/skippy/execution-batch.cpp | 18 +++++++++++++++++- - 1 file changed, 17 insertions(+), 1 deletion(-) - -diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 83c290ee2..46b0d1a27 100644 ---- a/src/skippy/execution-batch.cpp -+++ b/src/skippy/execution-batch.cpp -@@ -464,7 +464,6 @@ enum skippy_status skippy_iteration_batch_sampled( - return SKIPPY_STATUS_RUNTIME_ERROR; - } - skippy_mark_context_work_pending(first->stage_model); -- skippy_synchronize_context_if_pending(first->stage_model); - - // exports, readouts and sampling, request by request - skippy_trace::scope outputs_trace("skippy.batch_outputs", "requests", static_cast(request_count)); -@@ -472,6 +471,23 @@ enum skippy_status skippy_iteration_batch_sampled( - // once every request's outputs are recorded - std::vector samples; - std::vector sample_request_indexes; -+ // Synchronize only when this iteration consumes GPU results: a sampled -+ // last token, a causal readout, or a batched activation export. Prefill -+ // chunks without any of those return with the context still pending, so -+ // the scheduler prepares and the backend encodes the next chunk while -+ // the GPU still executes this one; command-queue order sequences the -+ // chunks' KV writes and reads. The Rust sizing protocol always passes a -+ // non-null descriptor array, so gate on the sessions that actually emit -+ // activation frames rather than on the array pointer. -+ const bool consumes_gpu_results = std::any_of( -+ requests, requests + request_count, -+ [](const skippy_iteration_request & request) { -+ return request.sample_last || request.readout != nullptr || -+ skippy_emits_activation_frame(request.session); -+ }); -+ if (consumes_gpu_results) { -+ skippy_synchronize_context_if_pending(first->stage_model); -+ } - for (size_t request_index = 0; request_index < request_count; ++request_index) { - const auto & request = requests[request_index]; - status = skippy_copy_batched_exports( --- -2.56.0 - diff --git a/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch b/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch deleted file mode 100644 index fbefbde429..0000000000 --- a/skippy/llama_cpp/patches/0041-llama-stop-re-reserving-the-sched-on-sampler-deta.patch +++ /dev/null @@ -1,63 +0,0 @@ -From f42a1b0b76dd941b65d5e68224721ac0aff22e8a Mon Sep 17 00:00:00 2001 -From: James Dumay -Date: Tue, 17 Nov 2026 18:35:00 +1100 -Subject: [PATCH] perf(llama): stop re-reserving the sched on sampler detach - -Detaching a sampler only shrinks the graph and does not require a fresh -reservation. Attaching or replacing a chain can grow the graph, so retain -reservation on attachment and preserve any outstanding shape-change reserve. - -Co-authored-by: Melkor ---- - src/llama-context.cpp | 14 ++++++++------ - 1 file changed, 8 insertions(+), 6 deletions(-) - -diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 5ed43df0e..64840c0cc 100644 ---- a/src/llama-context.cpp -+++ b/src/llama-context.cpp -@@ -1712,7 +1712,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { - warned = true; - } - if (sampling.samplers.count(seq_id) > 0) { -- sched_need_reserve = true; -+ // Detaching only shrinks what the reservation must cover; a -+ // detach must not force the next request to re-reserve. - } - sampling.samplers.erase(seq_id); - return false; -@@ -1731,6 +1732,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { - - sampling.samplers[seq_id] = sampler; - -+ // Each attached chain can grow the graph, including a replacement. -+ // Preserve any reservation already required by a shape change. - sched_need_reserve = true; - - return true; -@@ -1739,10 +1742,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { - if (sampler && !can_offload) { - LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id); - -- if (sampling.samplers.count(seq_id) > 0) { -- sched_need_reserve = true; -- } -- -+ // Detaching only shrinks what the reservation must cover; a detach -+ // must not force the next request to re-reserve. - sampling.samplers.erase(seq_id); - - return false; -@@ -1750,7 +1751,8 @@ bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { - - sampling.samplers.erase(seq_id); - -- sched_need_reserve = true; -+ // Detaching only shrinks what the reservation must cover; a detach must -+ // not force the next request to re-reserve. - - return true; - } --- -2.54.0 (Apple Git-157) - From e9c35dbe95763d85196fcbbed018e955250115ef Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 21 Nov 2026 06:51:09 +1100 Subject: [PATCH 80/81] Stabilize inference and cancellation tests on slow Windows runners --- .../src/mesh/native_inference/tests.rs | 12 +-- .../src/frontend/tests/generation.rs | 82 ++++++++++--------- 2 files changed, 50 insertions(+), 44 deletions(-) diff --git a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs index 124a0af931..fae31a5ac8 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/mesh/native_inference/tests.rs @@ -720,13 +720,15 @@ async fn dropped_native_stream_cancels_local_and_remote_generation_under_backpre /// Both the consumer and the provider must keep it alive: the window is per /// chunk, not per request, wherever the chunk is produced. async fn slow_generation_survives_the_window(remote: bool) { - let window = Duration::from_millis(150); - let chunks = 15usize; + // Allow for scheduling and QUIC setup on shared CI runners. The paced + // fixture still takes at least 1.5 inactivity windows to deliver all chunks. + let window = Duration::from_secs(2); + let chunks = 12; let (provider, _, _) = serving_node(Some(vec!["high".into()])).await; provider.set_native_stream_idle(window); let backend = Arc::new(RecordingBackend { pacing: Some(Pacing::Slow { - every: Duration::from_millis(20), + every: window / 8, chunks, }), ..Default::default() @@ -752,11 +754,11 @@ async fn slow_generation_survives_the_window(remote: bool) { .await .unwrap(); let mut seen = 0usize; - while let Some(chunk) = tokio::time::timeout(Duration::from_secs(5), stream.next_chunk()) + while let Some(chunk) = tokio::time::timeout(Duration::from_secs(30), stream.next_chunk()) .await .unwrap_or_else(|error| panic!("slow stream stalled (remote={remote}): {error}")) { - chunk.unwrap(); + chunk.unwrap_or_else(|error| panic!("slow stream failed (remote={remote}): {error:#}")); seen += 1; } let elapsed = started.elapsed(); diff --git a/skippy/crates/skippy-serving/src/frontend/tests/generation.rs b/skippy/crates/skippy-serving/src/frontend/tests/generation.rs index 9265c47549..8f7c4c400d 100644 --- a/skippy/crates/skippy-serving/src/frontend/tests/generation.rs +++ b/skippy/crates/skippy-serving/src/frontend/tests/generation.rs @@ -1,7 +1,6 @@ use super::*; use crate::frontend::generation::run_blocking_generation_worker; use skippy_inference_api::chat::ChatCompletionRequest; -use std::sync::atomic::AtomicBool; fn assert_generation_rate_limit(error: InferenceError, message_fragment: &str) { assert_eq!(error.status(), StatusCode::TOO_MANY_REQUESTS); @@ -203,65 +202,70 @@ fn queued_arrival_cannot_be_overtaken_when_a_lane_opens() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn cancelled_worker_stops_before_the_next_request_acquires_the_only_lane() { + use tokio::sync::oneshot; + + struct CancelOnDrop(InferenceRequestContext); + impl Drop for CancelOnDrop { + fn drop(&mut self) { + self.0.cancel(); + } + } + + let wait = Duration::from_secs(30); let generation_limit = Arc::new(Semaphore::new(1)); let queue_depth = Arc::new(AtomicUsize::new(0)); let first_permit = acquire_generation_permit_with_queue( generation_limit.clone(), queue_depth.clone(), 1, - Duration::from_secs(1), + wait, ) .await .unwrap(); - let first_context = InferenceRequestContext::new(); - let worker_started = Arc::new(AtomicBool::new(false)); - let worker_stopped = Arc::new(AtomicBool::new(false)); - let started = worker_started.clone(); - let stopped = worker_stopped.clone(); + let first_context = CancelOnDrop(InferenceRequestContext::new()); + let (started, worker_started) = oneshot::channel(); + let (cancelled, worker_cancelled) = oneshot::channel(); + let (finish, worker_finish) = oneshot::channel(); let first_worker = tokio::spawn(run_blocking_generation_worker( first_permit, - first_context.clone(), + first_context.0.clone(), move |cancellation| { - started.store(true, Ordering::Release); - while !cancellation.is_cancelled() { - std::thread::sleep(Duration::from_millis(1)); - } - stopped.store(true, Ordering::Release); + tokio::runtime::Handle::current().block_on(async move { + let _ = started.send(()); + // A failed assertion must not strand a blocking worker at runtime shutdown. + tokio::time::timeout(wait, async { + cancellation.cancelled().await; + let _ = cancelled.send(()); + let _ = worker_finish.await; + }) + .await + .expect("worker must receive cancellation and permission to finish"); + }); }, )); - tokio::time::timeout(Duration::from_millis(100), async { - while !worker_started.load(Ordering::Acquire) { - tokio::task::yield_now().await; - } - }) - .await - .expect("first generation worker started"); - - let second_limit = generation_limit.clone(); - let second_queue_depth = queue_depth.clone(); - let second = tokio::spawn(async move { - let permit = acquire_generation_permit_with_queue( - second_limit, - second_queue_depth, - 1, - Duration::from_secs(1), - ) + tokio::time::timeout(wait, worker_started) .await + .expect("first generation worker started") .unwrap(); - assert!( - worker_stopped.load(Ordering::Acquire), - "the first worker must stop before its permit is released" - ); - drop(permit); - }); + let second = + acquire_generation_permit_with_queue(generation_limit.clone(), queue_depth, 1, wait); + tokio::pin!(second); + assert!(futures_util::poll!(second.as_mut()).is_pending()); - first_context.cancel(); - tokio::time::timeout(Duration::from_millis(200), second) + first_context.0.cancel(); + tokio::time::timeout(wait, worker_cancelled) .await - .expect("second request acquired the lane promptly") + .expect("first worker observed cancellation") .unwrap(); + assert!( + futures_util::poll!(second.as_mut()).is_pending(), + "the first worker must retain its permit while unwinding" + ); + finish.send(()).unwrap(); + let second_permit = second.await.expect("second request acquired the lane"); first_worker.await.unwrap().unwrap(); + drop(second_permit); assert_eq!(generation_limit.available_permits(), 1); } From e60fe81f97431029274b53ff99281f023e61c2de Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sat, 21 Nov 2026 08:06:09 +1100 Subject: [PATCH 81/81] fix(skippy): account for embeddings after the cleanup fence --- .../skippy-api/src/split-certified.json | 2 +- ...rate-live-stage-planning-and-executi.patch | 128 ++++++++---------- ...cover-live-graph-and-state-contracts.patch | 45 +++++- 3 files changed, 96 insertions(+), 79 deletions(-) diff --git a/skippy/crates/skippy-api/src/split-certified.json b/skippy/crates/skippy-api/src/split-certified.json index 82e6b9cbcd..c2ab95fb18 100644 --- a/skippy/crates/skippy-api/src/split-certified.json +++ b/skippy/crates/skippy-api/src/split-certified.json @@ -3,7 +3,7 @@ "native_recipe": { "llama_upstream_sha": "8954f194837d2ec4d5f67f20c81b84abe63883ba", "skippy_abi": "0.1.86", - "patch_queue_sha256": "d34cb3cb339a60f56d067cad7299ee6e9b042331076b5fc2afd5789462bc922a" + "patch_queue_sha256": "85a61b8d48b96bdcd030664304197d0e55157200edf49e9c6aa8bcd85cf3254d" }, "architectures": [ "afmoe", diff --git a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index 218a251ddd..13463d990c 100644 --- a/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/skippy/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -1,4 +1,4 @@ -From d2883abb63c556f8b3807a85c3d9dec546286f9a Mon Sep 17 00:00:00 2001 +From 69e8740d65764e61c73895ee0e25294922b177a4 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 Subject: [PATCH] feat(llama): integrate live stage planning and execution @@ -20,12 +20,11 @@ additions, and test reserved ubatch sizes and stage boundaries against actual node counts on CPU, Metal and CUDA. Remove the architecture branches only after those bounds cover their current allowances and parity/reservation tests pass. Co-authored-by: Melkor - --- include/llama.h | 7 + src/llama-arch.cpp | 22 + src/llama-arch.h | 2 + - src/llama-context.cpp | 587 +++++++++-- + src/llama-context.cpp | 578 +++++++++-- src/llama-context.h | 99 +- src/llama-ext.h | 6 + src/llama-graph.h | 6 + @@ -47,7 +46,7 @@ Co-authored-by: Melkor = n_tokens && "encoder requires n_ubatch >= n_tokens"); - -+ if (t_compute_start_us == 0) { -+ t_compute_start_us = ggml_time_us(); -+ } -+ - // TODO: this clear of the buffer can easily be forgotten - need something better - // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { -@@ -1943,11 +2063,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1943,12 +2059,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } embd_seq.clear(); -- if (t_compute_start_us == 0) { -- t_compute_start_us = ggml_time_us(); -- } ++ sched_reserve(graph_build_inputs); ++ + if (t_compute_start_us == 0) { + t_compute_start_us = ggml_time_us(); + } - - sched_reserve(); -+ sched_reserve(graph_build_inputs); - +- n_queued_tokens += n_tokens; -@@ -1974,7 +2090,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { + const uint32_t n_outputs_all = balloc->get_n_outputs(); +@@ -1974,7 +2089,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { cparams.causal_attn = false; ggml_status status; @@ -624,7 +614,7 @@ index d597273a2..cd9a017fa 100644 cparams.causal_attn = causal_attn_org; -@@ -2094,6 +2210,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -2094,6 +2209,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return 0; } @@ -649,7 +639,7 @@ index d597273a2..cd9a017fa 100644 template static void copy_tensor_async_rows( const std::vector & tensors, -@@ -2147,9 +2281,15 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); - -+ if (t_compute_start_us == 0) { -+ t_compute_start_us = ggml_time_us(); -+ } -+ n_queued_tokens += n_tokens_all; -+ - // TODO: this clear of the buffer can easily be forgotten - need something better - // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { +@@ -2245,21 +2385,20 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { synchronize(); } embd_seq.clear(); -- -- if (t_compute_start_us == 0) { -- t_compute_start_us = ggml_time_us(); -- } -- n_queued_tokens += n_tokens_all; -- - output_swaps.clear(); - embd_batch_idxs.clear(); - -- sched_reserve(); ++ output_swaps.clear(); ++ embd_batch_idxs.clear(); ++ + sched_reserve(graph_build_inputs); + if (t_compute_start_us == 0) { + t_compute_start_us = ggml_time_us(); + } + n_queued_tokens += n_tokens_all; + +- output_swaps.clear(); +- embd_batch_idxs.clear(); +- +- sched_reserve(); +- bool did_optimize = false; // handle any pending shifts/copies @@ -721,7 +703,7 @@ index d597273a2..cd9a017fa 100644 llama_memory_context_ptr mctx; -@@ -2284,7 +2424,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2284,7 +2423,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (!did_optimize) { did_optimize = true; @@ -730,7 +712,7 @@ index d597273a2..cd9a017fa 100644 LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens()); continue; -@@ -2312,11 +2452,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2312,11 +2451,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -2; }; @@ -742,7 +724,7 @@ index d597273a2..cd9a017fa 100644 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2375,7 +2510,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2375,7 +2509,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_status status; @@ -756,7 +738,7 @@ index d597273a2..cd9a017fa 100644 if (!res) { // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module -@@ -2513,9 +2653,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2513,9 +2652,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { const uint32_t n_embd = hparams.n_embd_out(); float * embd_nextn_out = embd_nextn.data + offset*n_embd; @@ -780,7 +762,7 @@ index d597273a2..cd9a017fa 100644 extract_all_idxs = extract_all_idxs || !masked; } } -@@ -2527,7 +2680,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2527,7 +2679,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { embd_batch_idxs.insert(embd_batch_idxs.end(), batch_idxs.begin(), batch_idxs.end()); } @@ -791,7 +773,7 @@ index d597273a2..cd9a017fa 100644 const auto stride = n_vocab; // async copy the sampling data from the backend to the host -@@ -2539,6 +2694,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2539,6 +2693,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { n_outputs_prev += n_outputs; n_tokens_prev += ubatch.n_tokens; @@ -802,7 +784,7 @@ index d597273a2..cd9a017fa 100644 } while (mctx->next()); if (layer_inp_dev && ev_layer_inp_written) { -@@ -2824,9 +2983,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -2824,9 +2982,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -815,7 +797,7 @@ index d597273a2..cd9a017fa 100644 for (size_t s = 0; s < output_swaps.size(); ++s) { const uint64_t i0 = output_swaps[s].i0; -@@ -2839,6 +2998,7 @@ void llama_context::output_reorder() { +@@ -2839,6 +2997,7 @@ void llama_context::output_reorder() { } if (embd.size > 0) { @@ -823,7 +805,7 @@ index d597273a2..cd9a017fa 100644 for (uint64_t k = 0; k < n_embd_out; k++) { std::swap(embd.data[i0*n_embd_out + k], embd.data[i1*n_embd_out + k]); } -@@ -2909,6 +3069,8 @@ void llama_context::output_reorder() { +@@ -2909,6 +3068,8 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { @@ -832,7 +814,7 @@ index d597273a2..cd9a017fa 100644 uint32_t res; if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || model.arch == LLM_ARCH_HRM_TEXT) { -@@ -2936,10 +3098,13 @@ uint32_t llama_context::graph_max_nodes() const { +@@ -2936,10 +3097,13 @@ uint32_t llama_context::graph_max_nodes() const { // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft res = std::max(1024u, 12u*model.n_tensors()); } else { @@ -850,7 +832,7 @@ index d597273a2..cd9a017fa 100644 } // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling -@@ -2979,7 +3144,6 @@ static void ubatch_prepare_reserve( +@@ -2979,7 +3143,6 @@ static void ubatch_prepare_reserve( } } @@ -858,7 +840,7 @@ index d597273a2..cd9a017fa 100644 std::vector sampler_seqs; std::vector has_sampler(n_seqs, false); for (const auto & entry : samplers) { -@@ -2987,40 +3151,83 @@ static void ubatch_prepare_reserve( +@@ -2987,40 +3150,83 @@ static void ubatch_prepare_reserve( if (seq_id < 0 || (uint32_t) seq_id >= n_seqs) { continue; } @@ -949,7 +931,7 @@ index d597273a2..cd9a017fa 100644 LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs); GGML_ASSERT(n_outputs >= 1); -@@ -3045,16 +3252,40 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3045,16 +3251,40 @@ ggml_cgraph * llama_context::graph_reserve( llama_batch_allocr balloc(model.hparams.n_pos_per_embd()); llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs); @@ -991,7 +973,7 @@ index d597273a2..cd9a017fa 100644 // check the graph before scheduling: cross-backend copies break the producer chain that the check follows if (!hadamard_verified && gf && (!model.hdmd.rot.empty() || !model.hdmd.inv.empty())) { -@@ -3063,6 +3294,130 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3063,6 +3293,130 @@ ggml_cgraph * llama_context::graph_reserve( } this->n_input_tensors = llama_graph_n_input_tensors(gf); @@ -1122,7 +1104,7 @@ index d597273a2..cd9a017fa 100644 this->n_outputs = save_n_outputs; // initialize scheduler with the specified graph -@@ -3085,7 +3440,18 @@ llm_graph_params llama_context::graph_params( +@@ -3085,7 +3439,18 @@ llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, const llama_memory_context_i * mctx, @@ -1142,7 +1124,7 @@ index d597273a2..cd9a017fa 100644 return { /*.model =*/ &model, /*.hparams =*/ model.hparams, -@@ -3106,6 +3472,9 @@ llm_graph_params llama_context::graph_params( +@@ -3106,6 +3471,9 @@ llm_graph_params llama_context::graph_params( /*.h_nextn_dev =*/ cparams.embeddings_nextn_dev ? h_nextn_dev : nullptr, /*.h_nextn_src =*/ supports_state_row() ? cparams.ctx_state_src->get_h_nextn_dev() : nullptr, /*.samplers =*/ sampling.samplers, @@ -1152,7 +1134,7 @@ index d597273a2..cd9a017fa 100644 /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, -@@ -4325,7 +4694,8 @@ void llama_context::opt_epoch_iter( +@@ -4325,7 +4693,8 @@ void llama_context::opt_epoch_iter( auto * res = get_gf_res_prev(); @@ -1162,7 +1144,7 @@ index d597273a2..cd9a017fa 100644 // the optimizer graph is allocated outside sched, so the next decode must rebuild gf_res_prev_active = nullptr; -@@ -4431,7 +4801,7 @@ llama_context_params llama_context_default_params() { +@@ -4431,7 +4800,7 @@ llama_context_params llama_context_default_params() { /*.n_seq_max =*/ 1, /*.n_rs_seq =*/ 0, /*.n_outputs_max =*/ 0, @@ -1171,7 +1153,7 @@ index d597273a2..cd9a017fa 100644 /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS, /*.ctx_type =*/ LLAMA_CONTEXT_TYPE_DEFAULT, -@@ -4469,9 +4839,10 @@ llama_context_params llama_context_default_params() { +@@ -4469,9 +4838,10 @@ llama_context_params llama_context_default_params() { return result; } @@ -1185,7 +1167,7 @@ index d597273a2..cd9a017fa 100644 if (!model) { LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__); return nullptr; -@@ -4491,6 +4862,10 @@ llama_context * llama_init_from_model( +@@ -4491,6 +4861,10 @@ llama_context * llama_init_from_model( LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__); params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED; } @@ -1196,7 +1178,7 @@ index d597273a2..cd9a017fa 100644 if (model->split_mode() == LLAMA_SPLIT_MODE_TENSOR) { if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) { -@@ -4590,15 +4965,14 @@ llama_context * llama_init_from_model( +@@ -4590,15 +4964,14 @@ llama_context * llama_init_from_model( model->hparams.pooling_type, params.pooling_type); } @@ -1214,7 +1196,7 @@ index d597273a2..cd9a017fa 100644 const auto & cparams = ctx->get_cparams(); if (cparams.rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN && cparams.rope_freq_scale != model->hparams.rope_freq_scale_train) { -@@ -4615,6 +4989,12 @@ llama_context * llama_init_from_model( +@@ -4615,6 +4988,12 @@ llama_context * llama_init_from_model( return nullptr; } @@ -1227,7 +1209,7 @@ index d597273a2..cd9a017fa 100644 // deprecated llama_context * llama_new_context_with_model( llama_model * model, -@@ -4861,7 +5241,8 @@ struct ggml_cgraph * llama_graph_reserve( +@@ -4861,7 +5240,8 @@ struct ggml_cgraph * llama_graph_reserve( if (memory) { mctx = memory->init_full(); } @@ -1237,7 +1219,7 @@ index d597273a2..cd9a017fa 100644 } // llama adapter API -@@ -5113,13 +5494,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla +@@ -5113,13 +5493,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla // compat: llama_batch -> llama_batch_ext -> encode/decode int llama_context::encode(const llama_batch & batch_inp) { @@ -1267,7 +1249,7 @@ index d597273a2..cd9a017fa 100644 } /// -@@ -5138,7 +5531,11 @@ int32_t llama_encode( +@@ -5138,7 +5530,11 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { diff --git a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index a45d5f2dbd..e4ef61efc5 100644 --- a/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/skippy/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -1,4 +1,4 @@ -From 45535949e6a2493bf66107ac3e1d8ae2e7043e69 Mon Sep 17 00:00:00 2001 +From f1b7fd6e06d38c305f214533e7c59587a67e922d Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:43 +1100 Subject: [PATCH] test(skippy): cover live graph and state contracts @@ -6,7 +6,7 @@ Subject: [PATCH] test(skippy): cover live graph and state contracts Co-authored-by: Melkor --- src/CMakeLists.txt | 9 + - src/skippy/tests/async_state.cpp | 210 +++ + src/skippy/tests/async_state.cpp | 245 +++ .../tests/cast_destination_regression.h | 27 + src/skippy/tests/embedding_input_regression.h | 91 + src/skippy/tests/graph_build_inputs.cpp | 948 ++++++++++ @@ -45,7 +45,7 @@ Co-authored-by: Melkor model, params); ++ CHECK(ctx != nullptr); ++ ++ llama_token tokens[] = { 0, 1, 2 }; ++ const auto first = llama_batch_get_one(tokens, 2); ++ const auto second = llama_batch_get_one(tokens, 3); ++ ++ // Size the output buffer before measuring the embedding cleanup fence. ++ CHECK(llama_decode(ctx, second) == 0); ++ CHECK(llama_get_embeddings_seq(ctx, 0) != nullptr); ++ llama_perf_context_reset(ctx); ++ ++ CHECK(llama_decode(ctx, first) == 0); ++ // Starting the second batch fences the first batch's pooled outputs. ++ CHECK(llama_decode(ctx, second) == 0); ++ CHECK(llama_perf_context(ctx).n_p_eval == first.n_tokens); ++ llama_synchronize(ctx); ++ CHECK(llama_get_embeddings_seq(ctx, 0) != nullptr); ++ CHECK(llama_perf_context(ctx).n_p_eval == first.n_tokens + second.n_tokens); ++ llama_free(ctx); ++} ++ +void test_sampler_reservations(skippy_session * first, skippy_session * second) { + skippy_sampling_config sampling{}; + sampling.version = 1; @@ -313,6 +345,9 @@ index 000000000..0a0709d6a + } + CHECK(skippy_session_free(first, &error) == SKIPPY_STATUS_OK); + CHECK(skippy_session_free(second, &error) == SKIPPY_STATUS_OK); ++ if (std::strcmp(mode, "all") == 0) { ++ test_pooled_embedding_accounting(model); ++ } + CHECK(skippy_model_free(model, &error) == SKIPPY_STATUS_OK); + return 0; +}