diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 953bf520..4334474c 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -58,7 +58,12 @@ contract; no downstream product's workflow topology applies here. runs Graph Contracts in parallel with sixteen package jobs. Each CPU job supplies a shared platform CLI to its backend jobs. Routine CI uses two device jobs and checks the three remaining CUDA archives on hosted - compiler-image runners. + compiler-image runners. A dedicated KV path filter selects short cache checks + in the Metal and ARM64 CUDA 13 device jobs. Full CI qualifies all four KV + fixtures in those same device jobs using their exact packaged runtimes. + KV qualification gates known answers, identity/isolation and observed reuse; + token/score traces and optional upstream observations are diagnostics. It does + not require a separately built upstream server or numerical equivalence. Tagged releases add device smoke on those exact archives, including x64 CUDA 13. Windows ARM64 CPU is package-only in full CI and releases. Windows x64 CPU retains archive verification. Full CI additionally requires @@ -295,3 +300,5 @@ target matrix and `ci/README.md`. Validate syntax, matrix consistency, relevant Rust tests and the actual Just commands. Report unexecuted hardware checks and unverified external runner/repository configuration explicitly. Never describe workflow syntax validation as a successful build or hardware qualification. + +KV cache qualification in this branch runs after exact-package device smoke in the Metal and ARM64 CUDA 13 package jobs: short on selected PR packages, full on full CI. Harness and action inputs select those packages through the shared package filter. diff --git a/.github/actions/ci-cache-correctness/action.yml b/.github/actions/ci-cache-correctness/action.yml new file mode 100644 index 00000000..d2ba3ed2 --- /dev/null +++ b/.github/actions/ci-cache-correctness/action.yml @@ -0,0 +1,33 @@ +name: KV cache correctness +description: Qualify the exact native runtime in a Skippy package on its matching GPU. +inputs: + runtime-id: + description: Packaged runtime from ci/targets.json. + required: true + profile: + description: Short dense fixture or full four-fixture qualification. + required: true +runs: + using: composite + steps: + - uses: ./.github/actions/setup-hf + - name: Test KV reuse against the shipped runtime + shell: bash + env: + RUNTIME_ID: ${{ inputs.runtime-id }} + KV_PROFILE: ${{ inputs.profile }} + run: | + just cache-correctness-package "$RUNTIME_ID" "$KV_PROFILE" "dist/products/$RUNTIME_ID" "target/cache-qualification-$RUNTIME_ID" + - name: Retain reports and native logs + if: always() + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: ${{ env.SKIPPY_ARTIFACT_SCOPE }}-cache-correctness-${{ inputs.runtime-id }} + path: | + target/cache-qualification-${{ inputs.runtime-id }}/*.json + target/cache-qualification-${{ inputs.runtime-id }}/*/*.json + target/cache-qualification-${{ inputs.runtime-id }}/*/*.log + target/cache-qualification-${{ inputs.runtime-id }}/*/template-identity/*.log + if-no-files-found: ignore + overwrite: true + retention-days: 14 diff --git a/.github/actions/ci-package/action.yml b/.github/actions/ci-package/action.yml index 810aa17c..8f07a4e8 100644 --- a/.github/actions/ci-package/action.yml +++ b/.github/actions/ci-package/action.yml @@ -16,6 +16,9 @@ inputs: smoke: description: Select inference smoke, artifact smoke, or none for a package-only runtime. default: inference + kv-profile: + description: Run short or full KV qualification against the packaged runtime. + default: '' windows-cuda: description: Pinned CUDA toolkit version to provision on the hosted Windows builder. default: '' @@ -175,6 +178,7 @@ runs: if: inputs.smoke == 'inference' with: runtime_id: ${{ inputs.runtime-id }} + kv-profile: ${{ inputs.kv-profile }} - name: Upload package uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: diff --git a/.github/actions/ci-smoke/action.yml b/.github/actions/ci-smoke/action.yml index 80352f5a..42c92529 100644 --- a/.github/actions/ci-smoke/action.yml +++ b/.github/actions/ci-smoke/action.yml @@ -7,6 +7,9 @@ inputs: download-package: description: Restore the archived package for a separate release device smoke. default: 'false' + kv-profile: + description: Run short or full KV qualification after device smoke. + default: '' evidence-suffix: description: Driver vendor suffix for independent Vulkan device evidence. default: '' @@ -58,6 +61,11 @@ runs: export TMPDIR="$RUNNER_TEMP" fi just ci-smoke "$RUNTIME_ID" "dist/products/$RUNTIME_ID" + - uses: ./.github/actions/ci-cache-correctness + if: inputs.kv-profile != '' + with: + runtime-id: ${{ inputs.runtime_id }} + profile: ${{ inputs.kv-profile }} - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 if: inputs.download-package == 'true' with: diff --git a/.github/actions/setup-hf/action.yml b/.github/actions/setup-hf/action.yml new file mode 100644 index 00000000..136c69ce --- /dev/null +++ b/.github/actions/setup-hf/action.yml @@ -0,0 +1,19 @@ +name: Prepare Hugging Face CLI +description: Supply the hf command when it is missing from the runner. +runs: + using: composite + steps: + - name: Set up hf + shell: bash + run: | + if command -v hf >/dev/null; then + exit 0 + fi + venv="$RUNNER_TEMP/skippy-hf" + python3 -m venv "$venv" + bin="$venv/bin" + if [[ "$RUNNER_OS" == Windows ]]; then + bin="$venv/Scripts" + fi + "$bin/python" -m pip install --disable-pip-version-check 'huggingface-hub==1.33.0' + echo "$bin" >> "$GITHUB_PATH" diff --git a/.github/path-filters.yml b/.github/path-filters.yml index 3396d6f6..f2abd1e0 100644 --- a/.github/path-filters.yml +++ b/.github/path-filters.yml @@ -58,6 +58,8 @@ code: packages: - 'crates/**' + - 'tools/xtask/**' + - '.github/actions/ci-cache-correctness/**' - 'skippy_api/src/**' - 'skippy_api/include/**' - 'skippy_api/CMakeLists.txt' diff --git a/.github/scripts/ci-gate.test.cjs b/.github/scripts/ci-gate.test.cjs index 03b52301..730f4060 100644 --- a/.github/scripts/ci-gate.test.cjs +++ b/.github/scripts/ci-gate.test.cjs @@ -555,3 +555,14 @@ test('full CI requires both Windows GPU results and PR checks skip them', () => pr.smoke_windows_cuda.result = 'success'; assert.throws(() => gate(pr), /smoke_windows_cuda must be skipped/); }); + +test('native package smoke retains exact-archive KV qualification in both device jobs', () => { + for (const key of ['package_darwin_aarch64_metal', 'package_linux_aarch64_cuda13']) { + const body = workflow.split(`\n ${key}:\n`)[1].split(/\n \w+:\n/)[0]; + assert.match(body, /kv-profile:.*needs.plan.outputs.profile == 'full'.*'full'.*'short'/); + } + const packageAction = readFileSync(join(__dirname, '../actions/ci-package/action.yml'), 'utf8'); + assert.match(packageAction, /kv-profile: \$\{\{ inputs.kv-profile \}\}/); + const smoke = readFileSync(join(__dirname, '../actions/ci-smoke/action.yml'), 'utf8'); + assert.ok(smoke.indexOf('just ci-smoke') < smoke.indexOf('uses: ./.github/actions/ci-cache-correctness')); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4305cc2..a8614340 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -605,6 +605,7 @@ jobs: with: runtime-id: darwin-aarch64-metal host-id: darwin-aarch64 + kv-profile: ${{ needs.plan.outputs.profile == 'full' && 'full' || 'short' }} build-cli: ${{ needs.plan.outputs.profile == 'pr' }} candidate-artifact: ${{ inputs.candidate_artifact }} candidate-sha: ${{ inputs.candidate_sha }} @@ -862,6 +863,7 @@ jobs: with: runtime-id: linux-aarch64-cuda13 host-id: linux-aarch64 + kv-profile: ${{ needs.plan.outputs.profile == 'full' && 'full' || 'short' }} build-cli: ${{ needs.plan.outputs.profile == 'pr' }} candidate-artifact: ${{ inputs.candidate_artifact }} candidate-sha: ${{ inputs.candidate_sha }} diff --git a/Cargo.lock b/Cargo.lock index 04e87f63..b88417fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5304,6 +5304,7 @@ dependencies = [ "skippy-cache", "skippy-config", "skippy-coordinator", + "skippy-events", "skippy-ffi", "skippy-hf-hub", "skippy-inference-api", @@ -5788,6 +5789,7 @@ dependencies = [ "futures-util", "libc", "opentelemetry-proto", + "reqwest 0.13.5", "serde", "serde_json", "sha2 0.11.1", @@ -8025,6 +8027,20 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[package]] +name = "xtask" +version = "0.80.0" +dependencies = [ + "hex", + "serde", + "serde_json", + "sha2 0.11.1", + "skippy-model-artifact", + "skippy-subprocess", + "tar", + "tempfile", +] + [[package]] name = "xxhash-rust" version = "0.8.21" diff --git a/Cargo.toml b/Cargo.toml index dd3b79e9..ced7c591 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/*", "tools/process-supervision"] +members = ["crates/*", "tools/process-supervision", "tools/xtask"] default-members = ["crates/skippy-cli"] resolver = "2" @@ -24,6 +24,11 @@ tokio-tungstenite = "0.29" cognitive_complexity = "warn" too_many_lines = "warn" +# Hardware cache qualification uses the cold-prefill budget when staging a +# disk restore. Keep the pack digest on the same optimized path as release. +[profile.dev.package.blake3] +opt-level = 3 + [profile.dev.package.sha2] opt-level = 3 diff --git a/Justfile b/Justfile index 57d10417..6e3fcc88 100644 --- a/Justfile +++ b/Justfile @@ -135,6 +135,36 @@ test: skippy-api-test @cargo test --workspace --no-default-features @cargo test --manifest-path skippy-api-rs/Cargo.toml --workspace +cache-correctness-metal: + @SKIPPY_CACHE_QUAL_BACKEND=metal LLAMA_STAGE_BACKEND=metal just with-lld cargo test --locked -p skippy-serving --lib frontend::tests::cache_qualification::cross_tier -- --ignored --exact --nocapture + +[unix] +cache-correctness-cuda: + @SKIPPY_CACHE_QUAL_BACKEND="${SKIPPY_CACHE_QUAL_BACKEND:-cuda}" LLAMA_STAGE_BACKEND=cuda just with-lld cargo test --locked -p skippy-serving --lib frontend::tests::cache_qualification::cross_tier -- --ignored --exact --nocapture + +cache-correctness-matrix backend output *options: + @cargo run --locked -p xtask -- "{{ backend }}" "{{ output }}" {{ options }} + +cache-correctness-package variant profile product output: + @cargo run --locked -p xtask -- package {{ quote(variant) }} {{ quote(profile) }} {{ quote(product) }} {{ quote(output) }} + +[unix] +cache-correctness-verify backend report: + @SKIPPY_CACHE_QUAL_BACKEND={{ quote(backend) }} SKIPPY_CACHE_QUAL_VERIFY_REPORT={{ quote(report) }} just with-lld cargo test --locked -p skippy-serving --features dynamic-native-runtime --lib frontend::tests::cache_qualification::verify_report -- --ignored --exact --nocapture + +[unix] +cache-correctness-verify-matrix backend source report_dir: + @cargo run --locked -p xtask -- verify {{ quote(backend) }} {{ quote(source) }} {{ quote(report_dir) }} + +[unix] +cache-correctness-native-dir: + @scripts/build-llama.sh --print-build-dir + +[unix] +cache-correctness-reference source build pin *options: + @cmake -S "{{ source }}" -B "{{ build }}" -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DLLAMA_BUILD_COMMIT="{{ pin }}" -DLLAMA_BUILD_COMMON=ON -DLLAMA_BUILD_SERVER=ON -DLLAMA_BUILD_TOOLS=ON -DLLAMA_BUILD_APP=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF -DLLAMA_OPENSSL=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF {{ options }} + @cmake --build "{{ build }}" --target llama-server + llama-prepare: @scripts/prepare-llama.sh pinned @@ -292,6 +322,10 @@ ci-model-fetch: ci-artifact-smoke runtime product_dir: @"{{ automation_python }}" scripts/ci-product.py artifact-smoke "$@" +[positional-arguments] +ci-extract-runtime runtime product_dir output: + @"{{ automation_python }}" scripts/ci-product.py extract-runtime "$@" + ci: lint test llama-check [positional-arguments] diff --git a/README.md b/README.md index bd76476e..1583a7db 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ shared HTTP surface in - [Retained compatibility identifiers](docs/COMPATIBILITY.md) - [Configuration reference](docs/CONFIGURATION.md) - [Serving settings](docs/SERVING_SETTINGS.md) +- [Disk KV cache operations](docs/PROMPT_CACHE.md#inspect-and-maintain-the-disk-cache) - [Continuous integration](ci/README.md) - [Private releases](RELEASE.md) - [Split serving](docs/SKIPPY_SPLITS.md) diff --git a/ci/INFERENCE_QUALIFICATION.md b/ci/INFERENCE_QUALIFICATION.md index daf15df4..0b52f2e8 100644 --- a/ci/INFERENCE_QUALIFICATION.md +++ b/ci/INFERENCE_QUALIFICATION.md @@ -110,7 +110,8 @@ matching official tokenizer revision and layer count. Most fixtures use Q4_K_M; Flash-Next uses the four-shard IQ4_XS base model, not similarly named MTP sidecars. Admission reserves at least 16 GiB beyond weight bytes and checks available unified memory. This floor is not proof every context fits; real allocation -failures remain failures. Model caches are explicit, hash-verified inputs. +failures remain failures. Native jobs use `hf download` with the NAS-backed +Hugging Face cache, verify each shard, and serve from the snapshot paths. Nightly and release run CPU chain parity and state-handoff checks against native monolithic execution (sharing file-backed weights avoids duplicate GPU copies diff --git a/ci/README.md b/ci/README.md index 14f2f3a5..07f3c9b6 100644 --- a/ci/README.md +++ b/ci/README.md @@ -112,6 +112,16 @@ documentation and image builds use their ordinary workflows, not Depot wrappers. The existing inference PR comment is target-event-only; fork qualification links and artifacts are available in **Approved fork CI** and the aggregate status. +The `kv` filter also selects the Metal and Linux ARM64 CUDA 13 package jobs. +Each selected short run checks one dense fixture for known JSON answers, +L1 reuse, and L3 restoration in a fresh process. Numerical traces are diagnostic; the gate +requires correct answers, identity/isolation and actual reuse. Full profiles run all four +fixtures in those same jobs after device smoke, against the exact packaged +runtime. PRs read base-revision filters, falling back conservatively to code +selection before the KV filter lands. Main uses its last verified covered +commit and forces KV qualification when prior coverage cannot be verified. +See the [KV correctness gate](../docs/CACHE_CORRECTNESS_GATE.md). + Inference implementation changes require native qualification on every PR head. This includes serving, scheduling, runtime/FFI, native patches and qualification execution code; adding report or test files to the same PR does not remove that @@ -271,7 +281,7 @@ compares verified measurements directly with its saved baselines, and uploads aggregate Parquet results, the baseline manifest, and the generated card in one revision-checked commit to [the public qualification dataset](https://huggingface.co/datasets/meshllm/skippy-inference-qualification). -The initial tolerance and promotion threshold are 5% per performance metric. +The tolerance and promotion threshold are 1% per performance metric. A changed benchmark recipe seeds its own reference. Passing measurements are recorded while the saved reference remains in force until a new source exceeds the improvement threshold. Regressions and incomplete evidence fail nightly @@ -687,8 +697,8 @@ Sparks. Protected dispatch code verifies trust before sending a pinned source SHA. Jobs use the standard JY account and its existing host permissions without publisher credentials, fresh workspaces, read-only admitted models, exclusive machine reservations and bounded leases. Clean up job processes and workspaces after every outcome; -quarantine an allocation whose cleanup fails. Fork and other untrusted PRs still -require isolated ephemeral execution. The `unconfined` capability is not itself +quarantine an allocation whose cleanup fails. Fork PRs enter native execution only through the protected approved-fork +controller after maintainer workflow approval; other untrusted work stays isolated. The `unconfined` capability is not itself an admission failure; no separate job-account migration is required. Actions only orchestrates these jobs, so the 6 GiB runner-container limit does not bound model execution. Split jobs reserve both Sparks atomically. This policy does not @@ -715,6 +725,18 @@ artifact smoke is recorded separately from inference evidence. ## Artifact flow +```mermaid +flowchart LR + path["Independent path selection and build plan"] --> automation["Offline automation"] + automation --> quality["Source checks when selected"] + quality --> metal["Metal package and device smoke"] + quality --> arm["ARM64 CUDA 13 package and device smoke"] + metal --> metalKv["KV in the same job
Selected short: one fixture; full: four"] + arm --> armKv["KV in the same job
Selected short: one fixture; full: four"] + metalKv --> gate["CI result gate"] + armKv --> gate +``` + `just ci-plan` validates the target matrix with `jq`. The package and smoke commands use Python 3.9 or later. Release inventory uses Python 3.11 or later for TOML parsing. With uv installed, Justfile recipes run Python @@ -1073,3 +1095,5 @@ publication gates on scheduled llama upgrades. An already-current release must finish at hosted resolution without entering those stages. No hosted/hardware capacity or secret configuration is implied by these files. + +KV qualification remains attached to both native package jobs (Metal and ARM64 CUDA 13): short checks on selected PR packages and the full four-fixture checks on full CI. Both use the exact packaged runtime after device smoke and retain independent KV evidence. The shared packages filter includes the KV harness and action inputs. CUDA archives use the shared product handoff; no separate duplicate ARM64 package/device job is required. diff --git a/crates/llama-spec-bench/Cargo.toml b/crates/llama-spec-bench/Cargo.toml index ebf9b6b1..5b132f13 100644 --- a/crates/llama-spec-bench/Cargo.toml +++ b/crates/llama-spec-bench/Cargo.toml @@ -6,6 +6,9 @@ license.workspace = true publish = false version.workspace = true +[features] +dynamic-native-runtime = ["skippy-runtime/dynamic-native-runtime", "skippy-runtime/test-support"] + [dependencies] anyhow.workspace = true clap.workspace = true diff --git a/crates/llama-spec-bench/README.md b/crates/llama-spec-bench/README.md index 34bc93e7..1f4a7388 100644 --- a/crates/llama-spec-bench/README.md +++ b/crates/llama-spec-bench/README.md @@ -101,3 +101,60 @@ generation may legitimately diverge from the baseline at a near-tie token. The default corpus path is `evals/corpora/kv_mixed_prompts.jsonl`. + +## Packaged native runtimes + +Build with `--features dynamic-native-runtime` to use a separately packaged +runtime. Set `SKIPPY_NATIVE_RUNTIME_BUNDLE_DIR` to the matching runtime bundle +directory before invoking the benchmark. The default build retains static +linking. + +For draft readout comparisons, run `--dflash` once with +`SKIPPY_DFLASH_GPU_READOUT` unset and once with it set to `1`. JSON reports +include `draft_backend_readout`, `draft_backend_token_rows` and +`draft_host_fallback_rows`, so a requested backend path cannot silently be +reported as measured offload. Keep the same corpus, token counts and draft +window, warm up each arm, and interleave repeated runs before comparing rates. + +Compare feature transfers separately with `SKIPPY_DFLASH_GPU_READOUT=0` and +`SKIPPY_DFLASH_DEVICE_FEATURES=0` versus `1`. The +`draft_device_feature_rows` field must be positive in the device arm. These +component rates measure forward timings. The `*_decode_wall_ms` and +`*_wall_tokens_per_second` fields measure the complete post-prefill loop, +including rollback and bookkeeping. Use a serving workload to establish +request latency and concurrent throughput gains. + +DFlash target contexts default to `window + 1` recurrent rollback snapshots, +matching the serving plan's draft-plus-anchor depth. The JSON report records +`target_recurrent_rollback_tokens`. Use `--recurrent-rollback-tokens 0` only +when deliberately measuring checkpoint fallback; undersized snapshots can +make rollback replay dominate decode time. + +`--verify-reference` diagnoses target batching independently of a drafter. +It replays the serial continuation as forced inputs, compares single-token +sampling against `window + 1` row verification, and records the first +divergence with the top five raw log probabilities in each path. A trace +stops at its first mismatch because sampled verification intentionally does +not sample a rejected suffix. It fails on a difference unless +`--allow-mismatch` explicitly requests a diagnostic report. No throughput +claim should use that diagnostic mode. + +`--verify-reference --dflash-lanes 2 --shared-verify` traces shared target +forwards on two equal-length reference continuations without a draft model. +Add `--dflash` to attach the draft's feature-capture graph while still never +proposing or rolling back draft tokens. The report records `draft_attached`, +`lane_count` and actual `shared_forwards`, so capture and multi-sequence graph +effects can be distinguished from draft proposal or repair effects. + +For two concurrent DFlash lanes, provide two prompts and `--dflash-lanes 2`. +The control verifies each lane independently; `--shared-verify` combines +equal-length windows using native ABI `0.1.82`. Both arms include proposing, +verification, repair, and bookkeeping in `decode_wall_ms`, and report total +output throughput across the lanes. The report records shared versus single +forwards and the output tokens of each lane for exact comparison. This is a +runtime diagnostic, not a measurement of the serving scheduler. + +Add `--shared-draft` to combine compatible lanes' draft noise blocks too. +`shared_draft_lane_proposals` counts lanes that actually shared draft forwards, +so a capacity or head fallback remains visible. Hold `--shared-verify` fixed +when comparing independent and shared drafting to isolate its contribution. diff --git a/crates/llama-spec-bench/src/concurrent_dflash.rs b/crates/llama-spec-bench/src/concurrent_dflash.rs new file mode 100644 index 00000000..b6cfaf5a --- /dev/null +++ b/crates/llama-spec-bench/src/concurrent_dflash.rs @@ -0,0 +1,268 @@ +//! Matched concurrent decode loops with independent or shared verification. +use std::{collections::BTreeMap, time::Instant}; + +use anyhow::{Context, Result, bail}; +use serde::Serialize; +use skippy_runtime::dflash::proposal_batch::DFlashBatchRequest; +use skippy_runtime::{StageModel, StageSession, verification_batch::VerifyBatchRequest}; + +use crate::{Args, Baseline, PromptCase, elapsed_ms, first_mismatch, tokens_per_second}; + +struct Lane { + session: StageSession, + current: i32, + tokens: Vec, + accepted: usize, + finished: bool, +} + +#[derive(Serialize)] +struct Report { + mode: &'static str, + shared_verify: bool, + shared_draft: bool, + shared_draft_lane_proposals: u64, + lane_count: usize, + ctx_size: u32, + window: usize, + decode_wall_ms: f64, + output_tokens: usize, + output_tokens_per_second: f64, + shared_forwards: usize, + single_forwards: usize, + device_feature_rows: u64, + lanes: Vec, +} + +#[derive(Serialize)] +struct LaneReport { + id: String, + correct: bool, + mismatch_index: Option, + accepted_draft_tokens: usize, + output_tokens: Vec, + baseline_output_tokens: Vec, + verify_windows_in_place: u64, + verify_windows_checkpointed: u64, + shared_draft_proposals: u64, +} + +pub(super) fn run( + args: &Args, + target: &StageModel, + prompts: &[PromptCase], + baselines: &[Baseline], +) -> Result<()> { + let mut lanes = Vec::new(); + for baseline in baselines { + let mut session = target.create_session()?; + let prefix = &baseline.target_tokens[..baseline.target_tokens.len() - 1]; + session.prefill_chunked(prefix)?; + lanes.push(Lane { + session, + current: *baseline.target_tokens.last().expect("nonempty prompt"), + tokens: Vec::new(), + accepted: 0, + finished: false, + }); + } + let mut shared_forwards = 0; + let mut single_forwards = 0; + let started = Instant::now(); + while lanes.iter().any(|lane| !lane.finished) { + let inputs = propose(args, &mut lanes)?; + let (predictions, shared, single) = verify(&mut lanes, &inputs, args.shared_verify)?; + shared_forwards += shared; + single_forwards += single; + for ((lane, input), predicted) in lanes.iter_mut().zip(&inputs).zip(&predictions) { + if !lane.finished { + commit(target, args.max_new_tokens, lane, input, predicted)?; + } + } + } + let decode_wall_ms = elapsed_ms(started); + let mut reports = Vec::new(); + for ((lane, prompt), baseline) in lanes.into_iter().zip(prompts).zip(baselines) { + let mismatch_index = first_mismatch(&baseline.generation.tokens, &lane.tokens); + let rollback = lane.session.verify_rollback_counts()?; + reports.push(LaneReport { + id: prompt.id.clone(), + correct: mismatch_index.is_none(), + mismatch_index, + accepted_draft_tokens: lane.accepted, + output_tokens: lane.tokens, + baseline_output_tokens: baseline.generation.tokens.clone(), + verify_windows_in_place: rollback.in_place, + verify_windows_checkpointed: rollback.checkpointed, + shared_draft_proposals: lane + .session + .dflash_draft_stats() + .map_or(0, |stats| stats.shared_proposals), + }); + } + let output_tokens = reports + .iter() + .map(|report| report.output_tokens.len()) + .sum(); + let report = Report { + mode: "concurrent DFlash diagnostic; complete post-prefill loop", + shared_verify: args.shared_verify, + shared_draft: args.shared_draft, + shared_draft_lane_proposals: reports.iter().map(|lane| lane.shared_draft_proposals).sum(), + lane_count: args.dflash_lanes, + ctx_size: args.ctx_size, + window: args.speculative_window, + decode_wall_ms, + output_tokens, + output_tokens_per_second: tokens_per_second(output_tokens, decode_wall_ms), + shared_forwards, + single_forwards, + device_feature_rows: target.dflash_device_feature_rows(), + lanes: reports, + }; + eprintln!( + "concurrent decode: {:.2} tok/s shared={} single={}", + report.output_tokens_per_second, shared_forwards, single_forwards + ); + let json = serde_json::to_string_pretty(&report)?; + if let Some(path) = &args.json_out { + std::fs::write(path, format!("{json}\n"))?; + } else { + println!("{json}"); + } + if !args.allow_mismatch && report.lanes.iter().any(|lane| !lane.correct) { + bail!("concurrent verification diverged from serial target output"); + } + Ok(()) +} + +fn propose(args: &Args, lanes: &mut [Lane]) -> Result>> { + if args.shared_draft { + let mut requests: Vec<_> = lanes + .iter_mut() + .filter(|lane| !lane.finished) + .map(|lane| DFlashBatchRequest { + session: &mut lane.session, + anchor: lane.current, + max_tokens: args + .speculative_window + .min((args.max_new_tokens - lane.tokens.len()).saturating_sub(1)), + }) + .collect(); + let outputs = StageSession::dflash_propose_batch(&mut requests)?; + let mut outputs = outputs.into_iter(); + return lanes + .iter() + .map(|lane| { + if lane.finished { + return Ok(Vec::new()); + } + let proposal = outputs + .next() + .flatten() + .context("concurrent target has no DFlash draft")?; + let mut input = vec![lane.current]; + input.extend(proposal.tokens); + Ok(input) + }) + .collect(); + } + lanes + .iter_mut() + .map(|lane| { + if lane.finished { + return Ok(Vec::new()); + } + let remaining = args.max_new_tokens - lane.tokens.len(); + let proposal = lane + .session + .dflash_propose( + lane.current, + args.speculative_window.min(remaining.saturating_sub(1)), + )? + .context("concurrent target has no DFlash draft")?; + let mut input = vec![lane.current]; + input.extend(proposal.tokens); + Ok(input) + }) + .collect() +} + +fn verify( + lanes: &mut [Lane], + inputs: &[Vec], + shared: bool, +) -> Result<(Vec>, usize, usize)> { + let mut groups = BTreeMap::>::new(); + for (index, input) in inputs + .iter() + .enumerate() + .filter(|(_, input)| !input.is_empty()) + { + groups.entry(input.len()).or_default().push(index); + } + let mut predictions = vec![Vec::new(); lanes.len()]; + let mut shared_forwards = 0; + let mut single_forwards = 0; + for (width, indexes) in groups { + if shared && indexes.len() > 1 { + let mut requests: Vec<_> = lanes + .iter_mut() + .zip(inputs) + .filter(|(_, input)| input.len() == width) + .map(|(lane, input)| VerifyBatchRequest { + session: &mut lane.session, + token_ids: input, + sampling: None, + }) + .collect(); + let outputs = StageSession::verify_batch_sampled(&mut requests)?; + for (index, output) in indexes.into_iter().zip(outputs) { + predictions[index] = output; + } + shared_forwards += 1; + } else { + for index in indexes { + predictions[index] = lanes[index] + .session + .verify_tokens_sampled(&inputs[index], None)?; + single_forwards += 1; + } + } + } + Ok((predictions, shared_forwards, single_forwards)) +} + +fn commit( + target: &StageModel, + limit: usize, + lane: &mut Lane, + inputs: &[i32], + predicted: &[i32], +) -> Result<()> { + let accepted = inputs[1..] + .iter() + .zip(predicted) + .take_while(|(draft, target)| draft == target) + .count(); + let base = lane.session.token_count() - inputs.len() as u64; + let mut committed = 0; + for &token in predicted.iter().take(accepted + 1) { + lane.tokens.push(token); + lane.current = token; + committed += 1; + if target.token_is_eog(token)? || lane.tokens.len() == limit { + lane.finished = true; + break; + } + } + anyhow::ensure!(committed > 0, "verification produced no committed token"); + lane.accepted += accepted.min(committed); + if committed == inputs.len() { + lane.session + .retire_verify_checkpoint(base, inputs.len() as u64)?; + } else { + lane.session.trim_session(base + committed as u64)?; + } + Ok(()) +} diff --git a/crates/llama-spec-bench/src/dflash.rs b/crates/llama-spec-bench/src/dflash.rs index f94c4ed9..a6340340 100644 --- a/crates/llama-spec-bench/src/dflash.rs +++ b/crates/llama-spec-bench/src/dflash.rs @@ -16,7 +16,7 @@ pub(crate) fn generate_dflash( let mut session = target.create_session()?; let target_prefill_started = Instant::now(); if run.prompt_tokens.len() > 1 { - session.prefill_chunk(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?; + session.prefill_chunked(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?; } let target_prefill_ms = elapsed_ms(target_prefill_started); @@ -83,7 +83,12 @@ pub(crate) fn generate_dflash( } } + let decode_wall_ms = elapsed_ms(started); + let rollback = session.verify_rollback_counts()?; Ok(SpecGeneration { + verify_windows_in_place: rollback.in_place, + verify_windows_checkpointed: rollback.checkpointed, + decode_wall_ms, tokens: generated, stats, target_prefill_ms, diff --git a/crates/llama-spec-bench/src/main.rs b/crates/llama-spec-bench/src/main.rs index fe20fbb6..d09a6b05 100644 --- a/crates/llama-spec-bench/src/main.rs +++ b/crates/llama-spec-bench/src/main.rs @@ -13,7 +13,9 @@ use skippy_runtime::{ StageSession, }; +mod concurrent_dflash; mod dflash; +mod verify_reference; const DEFAULT_CORPUS: &str = "skippy/evals/corpora/kv_mixed_prompts.jsonl"; @@ -49,6 +51,21 @@ struct Args { /// Treat the draft as a DFlash/DFlash2 block drafter attached to the target. #[arg(long)] dflash: bool, + /// Target rollback snapshots; DFlash defaults to window + anchor. + #[arg(long)] + recurrent_rollback_tokens: Option, + /// Diagnose batched verification on the serial baseline's exact inputs. + #[arg(long)] + verify_reference: bool, + /// Concurrent DFlash lanes; provide exactly one prompt per lane. + #[arg(long, default_value_t = 1)] + dflash_lanes: usize, + /// Combine equal-length concurrent verify windows in one target forward. + #[arg(long)] + shared_verify: bool, + /// Combine concurrent noise blocks in one draft forward. + #[arg(long)] + shared_draft: bool, } #[derive(Debug, Clone)] @@ -60,6 +77,11 @@ struct PromptCase { #[derive(Debug, Serialize)] struct Report { + target_recurrent_rollback_tokens: u32, + draft_backend_readout: bool, + draft_backend_token_rows: u64, + draft_host_fallback_rows: u64, + draft_device_feature_rows: u64, target_model_path: String, draft_model_path: String, ctx_size: u32, @@ -73,6 +95,13 @@ struct Report { #[derive(Debug, Default, Serialize)] struct Summary { + verify_windows_in_place: u64, + verify_windows_checkpointed: u64, + baseline_decode_wall_ms: f64, + speculative_decode_wall_ms: f64, + baseline_wall_tokens_per_second: f64, + speculative_wall_tokens_per_second: f64, + speculative_wall_speedup_vs_baseline: f64, correct_prompts: usize, mismatched_prompts: usize, prompt_tokens_total: usize, @@ -96,6 +125,10 @@ struct Summary { #[derive(Debug, Serialize)] struct PromptReport { + verify_windows_in_place: u64, + verify_windows_checkpointed: u64, + baseline_decode_wall_ms: f64, + speculative_decode_wall_ms: f64, id: String, category: Option, prompt_tokens: usize, @@ -118,10 +151,13 @@ struct PromptReport { speculative_ttft_ms: f64, baseline_text_preview: String, speculative_text_preview: String, + baseline_output_tokens: Vec, + speculative_output_tokens: Vec, } #[derive(Debug)] struct Generation { + decode_wall_ms: f64, tokens: Vec, prefill_ms: f64, decode_ms: f64, @@ -130,6 +166,9 @@ struct Generation { #[derive(Debug)] struct SpecGeneration { + verify_windows_in_place: u64, + verify_windows_checkpointed: u64, + decode_wall_ms: f64, tokens: Vec, stats: SpecStats, target_prefill_ms: f64, @@ -149,6 +188,8 @@ struct SpecStats { fn main() -> Result<()> { let args = Args::parse(); + #[cfg(feature = "dynamic-native-runtime")] + skippy_runtime::test_support::require_native_runtime(); if args.max_new_tokens == 0 { bail!("--max-new-tokens must be greater than zero"); } @@ -172,6 +213,21 @@ fn main() -> Result<()> { if prompts.is_empty() { bail!("prompt set is empty"); } + if args.dflash_lanes == 0 + || (args.dflash_lanes > 1 + && ((!args.dflash && !args.verify_reference) || prompts.len() != args.dflash_lanes)) + { + bail!("multiple lanes require --dflash or --verify-reference, and one prompt per lane"); + } + if args.shared_verify && args.dflash_lanes < 2 { + bail!("--shared-verify requires multiple DFlash lanes"); + } + if args.shared_draft && args.dflash_lanes < 2 { + bail!("--shared-draft requires multiple DFlash lanes"); + } + if args.shared_draft && args.verify_reference { + bail!("--verify-reference does not run a draft model"); + } eprintln!( "loading target={} draft={} prompts={} ctx={} max_new_tokens={} window={}", @@ -185,11 +241,12 @@ fn main() -> Result<()> { 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); + target_config.lane_count = + u32::try_from(args.dflash_lanes).context("lane count exceeds u32")?; + // Both DFlash and native MTP verify drafts after the serial baseline. + target_config.recurrent_rollback_tokens = args.recurrent_rollback_tokens.unwrap_or_else(|| { + 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 @@ -199,7 +256,18 @@ fn main() -> Result<()> { eprintln!("baseline {}/{} {}", index + 1, prompts.len(), prompt.id); baselines.push(run_baseline(&args, &target, prompt)?); } + if args.verify_reference { + // Capture can change target graph fusion. Exercise that graph when + // requested, while still never proposing or rolling back draft tokens. + if args.dflash { + load_draft(&args, &mut target, &target_config)?; + } + return verify_reference::run(&args, &target, &baselines); + } let draft = load_draft(&args, &mut target, &target_config)?; + if args.dflash_lanes > 1 { + return concurrent_dflash::run(&args, &target, &prompts, &baselines); + } let mut reports = Vec::with_capacity(prompts.len()); for (index, (prompt, baseline)) in prompts.iter().zip(baselines).enumerate() { @@ -214,7 +282,13 @@ fn main() -> Result<()> { } let summary = summarize(&reports); + let (draft_backend_token_rows, draft_host_fallback_rows) = target.dflash_backend_readout_rows(); let report = Report { + target_recurrent_rollback_tokens: target_config.recurrent_rollback_tokens, + draft_backend_readout: target.dflash_backend_readout_enabled(), + draft_backend_token_rows, + draft_host_fallback_rows, + draft_device_feature_rows: target.dflash_device_feature_rows(), target_model_path: args.target_model_path.display().to_string(), draft_model_path: args.draft_model_path.display().to_string(), ctx_size: args.ctx_size, @@ -412,6 +486,10 @@ fn run_prompt_pair( }; Ok(PromptReport { + verify_windows_in_place: speculative.verify_windows_in_place, + verify_windows_checkpointed: speculative.verify_windows_checkpointed, + baseline_decode_wall_ms: baseline.decode_wall_ms, + speculative_decode_wall_ms: speculative.decode_wall_ms, id: prompt.id.clone(), category: prompt.category.clone(), prompt_tokens: target_tokens.len(), @@ -434,6 +512,8 @@ fn run_prompt_pair( speculative_ttft_ms: speculative.ttft_ms, baseline_text_preview: preview_text(target, &baseline.tokens)?, speculative_text_preview: preview_text(target, &speculative.tokens)?, + baseline_output_tokens: baseline.tokens, + speculative_output_tokens: speculative.tokens, }) } @@ -445,7 +525,7 @@ fn generate_baseline( let mut session = model.create_session()?; let prefill_started = Instant::now(); if prompt_tokens.len() > 1 { - session.prefill_chunk(&prompt_tokens[..prompt_tokens.len() - 1])?; + session.prefill_chunked(&prompt_tokens[..prompt_tokens.len() - 1])?; } let prefill_ms = elapsed_ms(prefill_started); let mut current = *prompt_tokens.last().expect("checked non-empty prompt"); @@ -466,6 +546,7 @@ fn generate_baseline( } } Ok(Generation { + decode_wall_ms: elapsed_ms(started), tokens: generated, prefill_ms, decode_ms, @@ -488,7 +569,7 @@ fn generate_speculative( let mut draft_session = draft.create_session()?; let target_prefill_started = Instant::now(); if run.prompt_tokens.len() > 1 { - target_session.prefill_chunk(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?; + target_session.prefill_chunked(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?; } let target_prefill_ms = elapsed_ms(target_prefill_started); let draft_prefill_started = Instant::now(); @@ -559,6 +640,9 @@ fn generate_speculative( } Ok(SpecGeneration { + verify_windows_in_place: 0, + verify_windows_checkpointed: 0, + decode_wall_ms: elapsed_ms(started), tokens: generated, stats, target_prefill_ms, @@ -572,7 +656,7 @@ fn generate_speculative( fn reset_draft_to_context(session: &mut StageSession, context_tokens: &[i32]) -> Result<()> { session.reset()?; if context_tokens.len() > 1 { - session.prefill_chunk(&context_tokens[..context_tokens.len() - 1])?; + session.prefill_chunked(&context_tokens[..context_tokens.len() - 1])?; } Ok(()) } @@ -595,6 +679,10 @@ fn preview_text(model: &StageModel, tokens: &[i32]) -> Result { fn summarize(prompts: &[PromptReport]) -> Summary { let mut summary = Summary::default(); for prompt in prompts { + summary.verify_windows_in_place += prompt.verify_windows_in_place; + summary.verify_windows_checkpointed += prompt.verify_windows_checkpointed; + summary.baseline_decode_wall_ms += prompt.baseline_decode_wall_ms; + summary.speculative_decode_wall_ms += prompt.speculative_decode_wall_ms; summary.correct_prompts += usize::from(prompt.correct); summary.mismatched_prompts += usize::from(!prompt.correct); summary.prompt_tokens_total += prompt.prompt_tokens; @@ -608,6 +696,18 @@ fn summarize(prompts: &[PromptReport]) -> Summary { summary.speculative_target_decode_ms += prompt.speculative_target_decode_ms; summary.speculative_draft_decode_ms += prompt.speculative_draft_decode_ms; } + summary.baseline_wall_tokens_per_second = tokens_per_second( + summary.baseline_generated_total, + summary.baseline_decode_wall_ms, + ); + summary.speculative_wall_tokens_per_second = tokens_per_second( + summary.speculative_generated_total, + summary.speculative_decode_wall_ms, + ); + summary.speculative_wall_speedup_vs_baseline = speedup( + summary.baseline_decode_wall_ms, + summary.speculative_decode_wall_ms, + ); summary.accept_rate = if summary.draft_tokens == 0 { 0.0 } else { @@ -637,8 +737,6 @@ fn summarize(prompts: &[PromptReport]) -> Summary { fn print_human_summary(report: &Report) { let summary = &report.summary; - let current_spec_total_ms = - summary.speculative_target_decode_ms + summary.speculative_draft_decode_ms; eprintln!("speculative pair benchmark:"); eprintln!( " prompts total={} correct={} mismatched={}", @@ -668,18 +766,18 @@ fn print_human_summary(report: &Report) { eprintln!( "{:<28} {:>12.2} {:>12.2} {:>10.2}x {:>10}", "target baseline", - summary.baseline_decode_ms, - summary.baseline_tokens_per_second, + summary.baseline_decode_wall_ms, + summary.baseline_wall_tokens_per_second, 1.0, - "actual" + "wall" ); eprintln!( "{:<28} {:>12.2} {:>12.2} {:>10.2}x {:>10}", "target/draft speculative", - current_spec_total_ms, - summary.speculative_total_tokens_per_second, - summary.speculative_speedup_vs_baseline, - "actual" + summary.speculative_decode_wall_ms, + summary.speculative_wall_tokens_per_second, + summary.speculative_wall_speedup_vs_baseline, + "wall" ); eprintln!(); eprintln!( diff --git a/crates/llama-spec-bench/src/verify_reference.rs b/crates/llama-spec-bench/src/verify_reference.rs new file mode 100644 index 00000000..a353fb3a --- /dev/null +++ b/crates/llama-spec-bench/src/verify_reference.rs @@ -0,0 +1,253 @@ +//! Teacher-forced target verification isolates batch numerics from rollback. +use anyhow::{Context, Result, bail, ensure}; +use serde::Serialize; +use skippy_runtime::{SamplingConfig, StageModel, StageSession, TokenLogprobs}; + +use crate::{Args, Baseline}; + +#[derive(Serialize)] +struct Report { + mode: &'static str, + window: usize, + lane_count: usize, + shared_verify: bool, + shared_forwards: usize, + draft_attached: bool, + prompts: Vec, +} + +#[derive(Serialize)] +struct Prompt { + baseline_tokens: Vec, + serial_tokens: Vec, + batch_tokens: Vec, + differences: Vec, +} + +#[derive(Serialize)] +struct Difference { + index: usize, + serial: Row, + batch: Row, +} + +#[derive(Serialize)] +struct Row { + token: i32, + logprob: f32, + top: Vec<(i32, f32)>, +} + +impl From<&TokenLogprobs> for Row { + fn from(row: &TokenLogprobs) -> Self { + Self { + token: row.token, + logprob: row.logprob, + top: row.top.clone(), + } + } +} + +pub(super) fn run(args: &Args, target: &StageModel, baselines: &[Baseline]) -> Result<()> { + let width = args + .speculative_window + .checked_add(1) + .context("verify window overflow")?; + let mut prompts = Vec::new(); + let (mut shared_trace, shared_forwards) = if args.shared_verify { + let (rows, forwards) = trace_shared(target, baselines, width)?; + (Some(rows), forwards) + } else { + (None, 0) + }; + for (index, baseline) in baselines.iter().enumerate() { + let mut inputs = vec![*baseline.target_tokens.last().expect("nonempty prompt")]; + inputs.extend_from_slice(&baseline.generation.tokens); + inputs.truncate(baseline.generation.tokens.len()); + let serial = trace(target, baseline, &inputs, 1)?; + let batch = if let Some(traces) = &mut shared_trace { + std::mem::take(&mut traces[index]) + } else { + trace(target, baseline, &inputs, width)? + }; + let differences: Vec<_> = serial + .iter() + .zip(&batch) + .enumerate() + .filter(|(_, (serial, batch))| serial.token != batch.token) + .map(|(index, (serial, batch))| Difference { + index, + serial: serial.into(), + batch: batch.into(), + }) + .collect(); + eprintln!("teacher-forced differences={}", differences.len()); + prompts.push(Prompt { + baseline_tokens: baseline.generation.tokens.clone(), + serial_tokens: serial.iter().map(|row| row.token).collect(), + batch_tokens: batch.iter().map(|row| row.token).collect(), + differences, + }); + } + let report = Report { + mode: "teacher-forced target verification; no draft proposals or rollback", + window: width, + lane_count: args.dflash_lanes, + shared_verify: args.shared_verify, + shared_forwards, + draft_attached: args.dflash, + prompts, + }; + let json = serde_json::to_string_pretty(&report)?; + if let Some(path) = &args.json_out { + std::fs::write(path, format!("{json}\n"))?; + } else { + println!("{json}"); + } + if !args.allow_mismatch + && report.prompts.iter().any(|prompt| { + !prompt.differences.is_empty() || prompt.serial_tokens != prompt.baseline_tokens + }) + { + bail!("teacher-forced verification diverged from the serial baseline"); + } + Ok(()) +} + +/// Forces identical continuations through a shared target without attaching +/// any draft, so cross-sequence kernel numerics can be inspected directly. +fn trace_shared( + target: &StageModel, + baselines: &[Baseline], + width: usize, +) -> Result<(Vec>, usize)> { + use skippy_runtime::{StageSession, verification_batch::VerifyBatchRequest}; + let length = baselines + .first() + .context("no reference lanes")? + .generation + .tokens + .len(); + ensure!( + baselines + .iter() + .all(|baseline| baseline.generation.tokens.len() == length), + "shared reference tracing requires equal continuation lengths" + ); + let mut sessions = Vec::new(); + let mut inputs = Vec::new(); + for baseline in baselines { + let mut session = target.create_session()?; + session.prefill_chunked(&baseline.target_tokens[..baseline.target_tokens.len() - 1])?; + sessions.push(session); + let mut tokens = vec![ + *baseline + .target_tokens + .last() + .context("empty reference prompt")?, + ]; + tokens.extend_from_slice(&baseline.generation.tokens); + tokens.truncate(length); + inputs.push(tokens); + } + let sampling = SamplingConfig { + enabled: true, + temperature: 0.0, + top_logprobs: Some(5), + ..SamplingConfig::default() + }; + let mut rows = vec![Vec::new(); baselines.len()]; + let mut forwards = 0; + for offset in (0..length).step_by(width) { + let end = (offset + width).min(length); + let bases: Vec<_> = sessions.iter().map(StageSession::token_count).collect(); + let mut requests: Vec<_> = sessions + .iter_mut() + .zip(&inputs) + .map(|(session, inputs)| VerifyBatchRequest { + session, + token_ids: &inputs[offset..end], + sampling: Some(&sampling), + }) + .collect(); + StageSession::verify_batch_sampled(&mut requests)?; + forwards += 1; + for (index, request) in requests.into_iter().enumerate() { + let chunk_rows = request.session.take_token_logprobs()?; + ensure!( + !chunk_rows.is_empty() && chunk_rows.len() <= end - offset, + "missing shared trace logprobs" + ); + rows[index].extend(chunk_rows); + request + .session + .retire_verify_checkpoint(bases[index], (end - offset) as u64)?; + } + if rows.iter().zip(baselines).any(|(rows, baseline)| { + rows.iter() + .zip(&baseline.generation.tokens) + .any(|(row, &token)| row.token != token) + }) { + break; + } + } + Ok((rows, forwards)) +} + +fn trace( + target: &StageModel, + baseline: &Baseline, + inputs: &[i32], + width: usize, +) -> Result> { + let mut session = target.create_session()?; + ensure!( + width <= session.batch_size()?, + "verify window exceeds native batch size" + ); + session.prefill_chunked(&baseline.target_tokens[..baseline.target_tokens.len() - 1])?; + let sampling = SamplingConfig { + enabled: true, + temperature: 0.0, + top_logprobs: Some(5), + ..SamplingConfig::default() + }; + let mut rows = Vec::new(); + for chunk in inputs.chunks(width) { + trace_chunk(&mut session, chunk, &sampling, width == 1)?; + let chunk_rows = session.take_token_logprobs()?; + ensure!( + !chunk_rows.is_empty() && chunk_rows.len() <= chunk.len(), + "missing trace logprobs" + ); + rows.extend(chunk_rows); + // Stateful sampling stops at the first rejected proposal. These are + // deliberately forced inputs, but stop the trace rather than sample + // or fabricate probabilities for the unreported suffix. + if rows + .iter() + .zip(&baseline.generation.tokens) + .any(|(row, &token)| row.token != token) + { + break; + } + } + Ok(rows) +} + +fn trace_chunk( + session: &mut StageSession, + chunk: &[i32], + sampling: &SamplingConfig, + serial: bool, +) -> Result<()> { + if serial { + session.decode_step_sampled(chunk[0], Some(sampling))?; + } else { + let start = session.token_count(); + session.verify_tokens_sampled(chunk, Some(sampling))?; + // Every forced input is committed, irrespective of the prediction. + session.retire_verify_checkpoint(start, chunk.len() as u64)?; + } + Ok(()) +} diff --git a/crates/skippy-api/Cargo.toml b/crates/skippy-api/Cargo.toml index a63f518b..55809939 100644 --- a/crates/skippy-api/Cargo.toml +++ b/crates/skippy-api/Cargo.toml @@ -22,6 +22,7 @@ reqwest = { version = "0.13", features = ["json"] } tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] } skippy-config = { path = "../skippy-config", version = "0.80.0" } skippy-cache = { path = "../skippy-cache", version = "0.80.0" } +skippy-events = { path = "../skippy-events", version = "0.80.0" } skippy-serving = { path = "../skippy-serving", version = "0.80.0" } skippy-native-runtime = { path = "../skippy-native-runtime", version = "0.80.0" } skippy-runtime-install = { path = "../skippy-runtime-install", version = "0.80.0" } diff --git a/crates/skippy-api/src/execution/split/plan.rs b/crates/skippy-api/src/execution/split/plan.rs index fa504c23..8b127cc6 100644 --- a/crates/skippy-api/src/execution/split/plan.rs +++ b/crates/skippy-api/src/execution/split/plan.rs @@ -133,6 +133,7 @@ impl SplitOptions { ctx_size: options.ctx_size, lane_count: options.generation_concurrency as u32, selected_device: options.selected_device.clone(), + max_request_tier: None, package_ref: identity.package_ref.clone(), manifest_sha256: identity.manifest_sha256.clone(), model_path: Some(identity.source_model_path.to_string_lossy().into_owned()), diff --git a/crates/skippy-api/src/family_policy.rs b/crates/skippy-api/src/family_policy.rs index 423c7d88..0bba7b00 100644 --- a/crates/skippy-api/src/family_policy.rs +++ b/crates/skippy-api/src/family_policy.rs @@ -53,6 +53,7 @@ impl FamilyPolicy { max_entries: bounded_entries, max_bytes, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-api/src/native-recipe.json b/crates/skippy-api/src/native-recipe.json index 2a8af891..9d180dc6 100644 --- a/crates/skippy-api/src/native-recipe.json +++ b/crates/skippy-api/src/native-recipe.json @@ -1,4 +1,4 @@ { "llama_upstream_sha": "918fe468dbaae80bcdaf975c1b368023f2578ead", - "patch_queue_sha256": "eca168e13f2535d5c7f0efd20a837e96ac9741a61aa6b77f4a6380ffd9807986" + "patch_queue_sha256": "059242225b40fa06c3d7bc3d43d58cf4c9ef44b2a33dcee10f7f79010669d389" } \ No newline at end of file diff --git a/crates/skippy-api/src/serving.rs b/crates/skippy-api/src/serving.rs index 776ff1d3..68375f92 100644 --- a/crates/skippy-api/src/serving.rs +++ b/crates/skippy-api/src/serving.rs @@ -31,6 +31,8 @@ pub struct InferenceOptions { pub pipeline_decode_groups: Option, pub adaptive_generation_min_concurrency: Option, pub generation_queue_capacity: usize, + /// Percent of the KV token budget only `local`-tier requests may reserve. + pub local_kv_reserve_percent: u8, pub generation_admission_timeout_secs: u64, pub prefill_chunk_size: usize, pub prefill_chunk_policy: String, @@ -88,6 +90,7 @@ impl InferenceOptions { generation_queue_capacity: skippy_serving::frontend::default_generation_queue_capacity( generation_concurrency, ), + local_kv_reserve_percent: 0, generation_admission_timeout_secs: DEFAULT_GENERATION_ADMISSION_TIMEOUT_SECS, prefill_chunk_size: BUILTIN_PREFILL_CHUNK_SIZE, prefill_chunk_policy: skippy_config::local_serving::PREFILL_CHUNK_POLICY.to_string(), @@ -148,6 +151,7 @@ impl InferenceOptions { pipeline_decode_groups: self.pipeline_decode_groups, adaptive_generation_min_concurrency: self.adaptive_generation_min_concurrency, generation_queue_capacity: self.generation_queue_capacity, + local_kv_reserve_percent: self.local_kv_reserve_percent, generation_admission_timeout_secs: self.generation_admission_timeout_secs, prefill_chunk_size: self.prefill_chunk_size, prefill_chunk_policy: self.prefill_chunk_policy, diff --git a/crates/skippy-api/src/serving/local.rs b/crates/skippy-api/src/serving/local.rs index 970dcfa5..575d2216 100644 --- a/crates/skippy-api/src/serving/local.rs +++ b/crates/skippy-api/src/serving/local.rs @@ -22,7 +22,14 @@ impl LocalDiskCacheOptions { ) { Ok(manager) => manager, Err(error) => { - tracing::warn!(%error, "disk prompt cache unavailable; using cold prefill"); + let message = "Skippy L3 disk cache unavailable. Serving continues without L3."; + tracing::warn!(%error, "{message}"); + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: message.to_owned(), + context: Some(format!("{error:#}")), + }, + ); None } } diff --git a/crates/skippy-api/src/split_execution/direct.rs b/crates/skippy-api/src/split_execution/direct.rs index b8ac78f5..747c0124 100644 --- a/crates/skippy-api/src/split_execution/direct.rs +++ b/crates/skippy-api/src/split_execution/direct.rs @@ -264,6 +264,7 @@ fn realize_configs( upstream: index.checked_sub(1).map(peer), downstream: (index + 1 < topology.stages.len()).then(|| peer(index + 1)), admission: admission.clone(), + max_request_tier: None, }; configs.push(stage_load::admitted_stage_config(&load, None, names)?); } diff --git a/crates/skippy-api/src/stage.rs b/crates/skippy-api/src/stage.rs index 2792186a..769cda4f 100644 --- a/crates/skippy-api/src/stage.rs +++ b/crates/skippy-api/src/stage.rs @@ -224,6 +224,7 @@ pub fn single_stage_config( bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, }; config.kv_cache = options .kv_cache diff --git a/crates/skippy-api/src/stage_load.rs b/crates/skippy-api/src/stage_load.rs index 8f42ecf1..cf3394a0 100644 --- a/crates/skippy-api/src/stage_load.rs +++ b/crates/skippy-api/src/stage_load.rs @@ -76,6 +76,9 @@ pub struct AdmittedStageOptions { pub upstream: Option, pub downstream: Option, pub admission: skippy_protocol::StageAdmissionDescriptor, + /// Highest request tier this stage serves; see + /// [`StageConfig::max_request_tier`]. `None` serves the stamped tier. + pub max_request_tier: Option, } impl AdmittedStageOptions { @@ -199,6 +202,7 @@ pub fn admitted_stage_config( bind_addr: load.bind_addr.clone(), upstream: load.upstream.clone(), downstream: load.downstream.clone(), + max_request_tier: load.max_request_tier.clone(), }; let family_policy = crate::family_policy::family_policy_for_stage_config(&config); config.kv_cache = package.map_or_else( diff --git a/crates/skippy-cache/README.md b/crates/skippy-cache/README.md index 3b85fdc6..bff991f8 100644 --- a/crates/skippy-cache/README.md +++ b/crates/skippy-cache/README.md @@ -24,6 +24,12 @@ 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. +Serving puts the request tier and private partition in the cache namespace +(see `skippy-inference-api`'s request tiers), so a prefix one tier or partition +computed never matches another's. Recurrent entries are evicted by the +retention their owner gives them (`evict_recurrent_by_retention`), least +recently used first among equals; serving uses the storing request's tier. + 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) diff --git a/crates/skippy-cache/src/identity.rs b/crates/skippy-cache/src/identity.rs index 74a3b5b6..a5d8aa46 100644 --- a/crates/skippy-cache/src/identity.rs +++ b/crates/skippy-cache/src/identity.rs @@ -677,6 +677,7 @@ mod identity_completeness_tests { bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, } } @@ -1047,6 +1048,7 @@ mod identity_stability_tests { bind_addr: "127.0.0.1:0".to_string(), upstream: None, downstream: None, + max_request_tier: None, } } @@ -1076,6 +1078,7 @@ mod identity_stability_tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: StageKvCacheCodec::CacheGen, min_tokens: 64, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-cache/src/l2/mod.rs b/crates/skippy-cache/src/l2/mod.rs index 0a73565c..4bbf2380 100644 --- a/crates/skippy-cache/src/l2/mod.rs +++ b/crates/skippy-cache/src/l2/mod.rs @@ -3,7 +3,7 @@ //! The radix cache (L1) holds resident payloads; the L3 tier holds the same //! state durably on disk as content-addressed packed segments. This module //! adds the missing middle tier: a bounded host-RAM cache of *immutable -//! packed segments*, keyed and identified exactly like the L3 entries they +//! checkpoint bytes*, keyed and identified exactly like the L3 entries they //! mirror. //! //! Contract (mirrors `crate::tier::L3Tier`): @@ -20,7 +20,7 @@ //! entry's L3 manifest segment list onto those handles. A longer prefix //! that extends a shorter one references the same segment handles, so //! turn growth shares prefix bytes instead of duplicating them — L2 RAM -//! tracks *distinct segment* bytes, not per-prefix assembled bytes. +//! tracks *distinct segment* bytes. //! - **Integrity**: the whole concatenated L3 wire digest (the manifest key) //! is verified exactly once, at admission, against the payload being //! admitted. After admission the segment bytes are immutable, so every @@ -35,12 +35,13 @@ //! first admission pays for it. //! - **Zero-copy reads**: `get` clones handles, not bytes; the returned //! `CacheBytes` is a block-backed view over the shared segment storages, -//! contiguous in the single-segment case. +//! contiguous in the single-segment case. Native import can consume the +//! shared segments directly. //! //! `skippy-server` wires this tier as a bounded mirror of repeated or //! high-value L3 fills. An L2 hit rewarms L1. use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, ops::Range, sync::{ Arc, Mutex, @@ -52,7 +53,8 @@ use std::{ use crate::PayloadCodec; use crate::payload::{CacheBytes, ExactStatePayload, ExactStatePayloadKind}; use crate::{ - HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION, SegmentCodecIdentity, segment_digest, + CHECKPOINT_MANIFEST_VERSION, HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION, + SegmentCodecIdentity, segment_digest, }; const DIRECT_SEGMENT_BYTES: usize = 1024 * 1024; @@ -91,8 +93,7 @@ pub struct L2Stats { pub entries: u64, /// Sum of entries' distinct segment charges — the live budget usage. pub bytes: u64, - /// Sum of entry payload lengths including cross-entry sharing; larger - /// than `bytes` exactly when entries share prefix segments. + /// Sum of entry payload lengths, including cross-entry sharing. pub logical_bytes: u64, /// Distinct immutable segment handles currently held. pub segments: u64, @@ -229,13 +230,13 @@ impl ExactStatePayloadMirror { /// Segment digests in wire order, deduplicated. fn segment_digests(&self) -> Vec<&str> { - let mut seen = Vec::new(); - for (digest, _) in &self.layout().segments { - if !seen.contains(&digest.as_str()) { - seen.push(digest.as_str()); - } - } - seen + let mut seen = HashSet::new(); + self.layout() + .segments + .iter() + .map(|(digest, _)| digest.as_str()) + .filter(|digest| seen.insert(*digest)) + .collect() } } @@ -260,13 +261,16 @@ impl L2Hit { /// `Cow` on `as_cow`. pub fn to_payload(&self) -> crate::payload::ExactStatePayload { let layout = self.payload.layout(); - let wire = self.wire_view(0..layout.total_bytes); match self.payload.kind() { crate::payload::ExactStatePayloadKind::FullState => { - crate::payload::ExactStatePayload::FullState { bytes: wire } + crate::payload::ExactStatePayload::FullState { + bytes: self.wire_view(0..layout.total_bytes), + } } crate::payload::ExactStatePayloadKind::RecurrentOnly => { - crate::payload::ExactStatePayload::RecurrentOnly { recurrent: wire } + crate::payload::ExactStatePayload::RecurrentOnly { + recurrent: self.wire_view(0..layout.total_bytes), + } } crate::payload::ExactStatePayloadKind::KvRecurrent => { // Split the wire at kv_bytes exactly like L3 load does: kv @@ -280,6 +284,23 @@ impl L2Hit { } } + /// Borrows the verified KV portion in wire order. The last segment may + /// also contain recurrent bytes, which are outside this view. + pub fn kv_chunks(&self) -> Option> { + let layout = self.payload.layout(); + if layout.payload_kind != ExactStatePayloadKind::KvRecurrent { + return None; + } + let kv_len = layout.kv_bytes.min(layout.total_bytes); + let end = layout + .segments + .partition_point(|(_, range)| range.start < kv_len); + Some(layout.segments[..end].iter().map(move |(digest, range)| { + let len = (range.end.min(kv_len) - range.start) as usize; + &self.segments[digest].bytes[..len] + })) + } + /// Block-backed `CacheBytes` over `range` of the assembled wire, in /// wire order. Blocks outside `range` are skipped; edge blocks are /// narrowed to the overlap. Byte-identical views share the same @@ -625,6 +646,42 @@ impl L2Tier { self.budget_bytes } + /// Mirror the exact layout of a checkpoint without hashing its bytes as + /// a second, monolithic object. The shared admission path verifies every + /// segment before installing it in the immutable pool. + pub fn admit_manifest_payload( + &self, + cache_key: String, + manifest: &HandoffManifest, + payload: &ExactStatePayload, + ) -> Result, L2InsertRefusal> { + let mirror = ExactStatePayloadMirror::from_manifest(manifest)?; + let digest = manifest.payload_digest.clone(); + if manifest.version != CHECKPOINT_MANIFEST_VERSION { + let (wire, _, _) = payload_wire(payload)?; + return self.admit( + cache_key, + manifest.token_count, + digest, + &wire, + mirror, + L2Origin::FromL3, + ); + } + manifest + .verify_checkpoint() + .map_err(|error| L2InsertRefusal::MalformedManifest(error.to_string()))?; + let (wire, _, _) = payload_wire(payload)?; + self.admit_segments( + cache_key, + manifest.token_count, + digest, + &wire, + mirror, + L2Origin::FromL3, + ) + } + /// Admit an exact-state payload restored from the authoritative L3 tier. /// /// The payload is cut into stable one-MiB content chunks. This preserves @@ -726,6 +783,18 @@ impl L2Tier { actual, }); } + self.admit_segments(cache_key, token_count, payload_digest, wire, mirror, origin) + } + + fn admit_segments( + &self, + cache_key: String, + token_count: u64, + payload_digest: String, + wire: &[u8], + mirror: ExactStatePayloadMirror, + origin: L2Origin, + ) -> Result, L2InsertRefusal> { let payload_bytes = mirror.byte_len(); if payload_bytes == 0 { // Mirrors L3: an empty payload cannot represent state. @@ -752,8 +821,9 @@ impl L2Tier { let mut new_segments: Vec<(String, SegmentHandle)> = Vec::new(); let mut new_bytes = 0u64; let mut shared_bytes = 0u64; - for &(digest, slice) in segments.iter() { - if new_segments.iter().any(|(d, _)| d == digest) { + let mut seen = HashSet::with_capacity(segments.len()); + for (digest, slice) in segments { + if !seen.insert(digest) { // Within-admission duplicate digest: the validation pass // already proved both slices have identical content, so // keep the first copy. @@ -786,22 +856,18 @@ impl L2Tier { .to_string(), }); } - new_bytes = new_bytes.saturating_add(slice.len() as u64); - new_segments.push(( - digest.to_string(), - SegmentHandle { - bytes: Arc::new(slice.to_vec()), - }, - )); + let handle = SegmentHandle { + bytes: Arc::new(slice.to_vec()), + }; + new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64); + new_segments.push((digest.to_string(), handle)); } None => { - new_bytes = new_bytes.saturating_add(slice.len() as u64); - new_segments.push(( - digest.to_string(), - SegmentHandle { - bytes: Arc::new(slice.to_vec()), - }, - )); + let handle = SegmentHandle { + bytes: Arc::new(slice.to_vec()), + }; + new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64); + new_segments.push((digest.to_string(), handle)); } } } @@ -1182,23 +1248,26 @@ impl L2Tier { /// corruption cleanup, and rollback alike. Deterministic: identical /// map states produce identical ownership. fn recompute_all_charges(inner: &mut L2Inner) { - let mut ownership: HashMap = HashMap::new(); - for digest in inner.segments.keys() { - let Some(bytes) = inner.segments.get(digest).map(|h| h.bytes.len() as u64) else { - continue; - }; - let owner = inner - .map - .iter() - .filter(|(_, entry)| entry.payload.segment_digests().contains(&digest.as_str())) - .map(|(key, _)| key.clone()) - .min(); - if let Some(owner) = owner { - *ownership.entry(owner).or_insert(0) += bytes; + let mut owners = HashMap::<&str, &str>::with_capacity(inner.segments.len()); + for (key, entry) in &inner.map { + for (digest, _) in &entry.payload.layout().segments { + let owner = owners.entry(digest).or_insert(key); + *owner = (*owner).min(key); + } + } + let mut charges = HashMap::::with_capacity(inner.map.len()); + for (digest, owner) in owners { + if let Some(segment) = inner.segments.get(digest) { + let bytes = segment.bytes.len() as u64; + if let Some(charge) = charges.get_mut(owner) { + *charge += bytes; + } else { + charges.insert(owner.to_owned(), bytes); + } } } for (key, entry) in inner.map.iter_mut() { - entry.charge_bytes = ownership.get(key).copied().unwrap_or(0); + entry.charge_bytes = charges.get(key).copied().unwrap_or(0); } } @@ -1404,6 +1473,50 @@ mod tests { l2_cache_key("model-a", "state-a", namespace, tokens) } + #[test] + fn kv_chunks_borrow_shared_segments_and_exclude_recurrent_bytes() { + let tier = L2Tier::new(16); + let admit = |key: &str, wire: &[u8], kv_bytes: u64| { + let mut start = 0; + let segments = wire + .chunks(4) + .map(|chunk| { + let end = start + chunk.len() as u64; + let segment = (segment_digest(chunk), start..end); + start = end; + segment + }) + .collect(); + let layout = L2Layout { + payload_kind: ExactStatePayloadKind::KvRecurrent, + total_bytes: wire.len() as u64, + kv_bytes, + recurrent_bytes: wire.len() as u64 - kv_bytes, + kv_desc_json: None, + segments, + }; + tier.admit( + key.into(), + 2, + segment_digest(wire), + wire, + ExactStatePayloadMirror::KvRecurrent { layout }, + L2Origin::Direct, + ) + .unwrap(); + }; + admit("first", b"abcdefRR", 6); + admit("grown", b"abcdefghiirr", 10); + assert_eq!(tier.stats().bytes, 16); + let first = tier.get("first").unwrap(); + let grown = tier.get("grown").unwrap(); + let first_chunks: Vec<_> = first.kv_chunks().unwrap().collect(); + let grown_chunks: Vec<_> = grown.kv_chunks().unwrap().collect(); + assert_eq!(first_chunks, [b"abcd".as_slice(), b"ef"]); + assert_eq!(grown_chunks, [b"abcd".as_slice(), b"efgh", b"ii"]); + assert_eq!(first_chunks[0].as_ptr(), grown_chunks[0].as_ptr()); + } + #[test] fn admit_get_round_trip_serves_wire_bytes() { let tier = L2Tier::new(1 << 20); @@ -1940,6 +2053,7 @@ mod tests { payload_kind: "kv-recurrent".to_string(), total_bytes: wire_bytes.len() as u64, payload_digest: digest.clone(), + prefix_key: None, segments: vec![ HandoffSegmentRef { index: 0, @@ -2000,6 +2114,7 @@ mod tests { payload_kind: "blob".to_string(), total_bytes: 10, payload_digest: "blake3:aa".to_string(), + prefix_key: None, segments: Vec::new(), kv_bytes: 10, kv_decoded_bytes: 10, @@ -2725,6 +2840,7 @@ mod tests { payload_kind: "full-state".to_string(), total_bytes: 32, payload_digest: digest.clone(), + prefix_key: None, segments: vec![HandoffSegmentRef { index, offset, diff --git a/crates/skippy-cache/src/l3.rs b/crates/skippy-cache/src/l3.rs index bb9c2caa..c42dca83 100644 --- a/crates/skippy-cache/src/l3.rs +++ b/crates/skippy-cache/src/l3.rs @@ -61,6 +61,9 @@ const EVICTION_LOW_WATER_PERCENT: u64 = 85; /// version whose segment lacks it is rejected rather than reinterpreted. pub const MANIFEST_VERSION: u32 = 4; +/// Serving checkpoints address ordered page metadata instead of concatenated bytes. +pub const CHECKPOINT_MANIFEST_VERSION: u32 = 5; + /// The pre-codec-identity manifest format. These entries predate codec /// identity, are always raw by construction, and are decoded as raw through /// the explicit legacy path in [`decode_manifest`]. New manifests are never @@ -313,8 +316,12 @@ pub struct HandoffManifest { #[serde(default)] pub codec: Option, pub total_bytes: u64, - /// BLAKE3 of the assembled payload; also the manifest's key. + /// Manifest key. Older handoff manifests use the digest of the assembled bytes. + /// Serving checkpoints use the digest of the manifest with this field cleared. pub payload_digest: String, + /// The serving prefix coordinate includes the cache namespace and token IDs. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prefix_key: Option, pub segments: Vec, pub kv_bytes: u64, /// Decoded native KV length. Equal to `kv_bytes` for native pages; for a @@ -335,6 +342,32 @@ pub struct HandoffManifest { } impl HandoffManifest { + pub(crate) fn checkpoint_digest(&self) -> Result { + let mut manifest = self.clone(); + manifest.payload_digest.clear(); + let mut hasher = blake3::Hasher::new_derive_key("Skippy L3 checkpoint manifest v5"); + hasher.update(&serde_json::to_vec(&manifest)?); + Ok(hasher.finalize().to_hex().to_string()) + } + + pub(crate) fn verify_checkpoint(&self) -> Result<()> { + if self.version == CHECKPOINT_MANIFEST_VERSION { + if !self + .prefix_key + .as_deref() + .is_some_and(|key| key.strip_prefix("blake3:").is_some_and(packed::is_digest)) + { + bail!("checkpoint manifest has no valid prefix key"); + } + if self.checkpoint_digest()? != self.payload_digest { + bail!("checkpoint manifest does not match its digest"); + } + } else if self.prefix_key.is_some() { + bail!("handoff manifest carries a serving checkpoint prefix key"); + } + Ok(()) + } + pub fn new(state_identity: String, payload_kind: String) -> Self { Self::new_for_model(state_identity.clone(), state_identity, payload_kind) } @@ -352,6 +385,7 @@ impl HandoffManifest { codec: Some(PayloadCodec::raw()), total_bytes: 0, payload_digest: String::new(), + prefix_key: None, segments: Vec::new(), kv_bytes: 0, kv_decoded_bytes: 0, @@ -525,6 +559,11 @@ impl StoreLimits { minimum_free_bytes, } } + + pub fn low_water_bytes(self) -> Option { + (self.budget_bytes > 0) + .then(|| self.budget_bytes.saturating_mul(EVICTION_LOW_WATER_PERCENT) / 100) + } } /// Why a write was not admitted. Every refusal is a miss with a stable reason, @@ -632,7 +671,7 @@ impl Drop for ManifestPin<'_> { } /// What the store currently holds, for the status contract. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct StoreUsage { pub budget_bytes: u64, pub used_bytes: u64, @@ -646,7 +685,7 @@ pub struct StoreUsage { } /// Repairs performed before a node starts serving a cache root. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct StoreReconciliation { pub removed_temporary_files: u64, pub quarantined_manifests: u64, @@ -702,8 +741,25 @@ pub fn segment_digest(bytes: &[u8]) -> String { blake3::hash(bytes).to_hex().to_string() } +/// Another process has the exclusive lock for this cache directory. +#[derive(Debug)] +pub struct CacheRootInUse(PathBuf); + +impl std::fmt::Display for CacheRootInUse { + fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + output, + "cache root {} is already owned by another manager", + self.0.display() + ) + } +} + +impl std::error::Error for CacheRootInUse {} + fn acquire_root_lock(root: &Path) -> Result { let path = root.join(ROOT_LOCK_FILE); + fsinfo::refuse_symlink(&path)?; let file = fs::OpenOptions::new() .create(true) .truncate(false) @@ -711,18 +767,14 @@ fn acquire_root_lock(root: &Path) -> Result { .write(true) .open(&path) .with_context(|| format!("failed to open cache root lock {}", path.display()))?; - fsinfo::restrict_to_owner(&path, 0o600)?; - if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) { if fsinfo::is_lock_contended(&error) { - bail!( - "cache root {} is already owned by another manager", - root.display() - ); + return Err(CacheRootInUse(root.to_path_buf()).into()); } return Err(error).with_context(|| format!("failed to lock cache root {}", root.display())); } + fsinfo::restrict_to_owner(&path, 0o600)?; Ok(file) } @@ -750,6 +802,14 @@ impl HandoffSegmentStore { root: impl Into, limits: StoreLimits, ) -> Result { + Ok(Self::open_unreconciled(root, |_| Ok(Some(limits)))? + .expect("a fixed limit always opens the cache or returns an error")) + } + + pub(crate) fn open_unreconciled( + root: impl Into, + select_limits: impl FnOnce(&Path) -> Result>, + ) -> Result> { let root = root.into(); if !root.is_absolute() { bail!("cache root must be absolute: {}", root.display()); @@ -767,6 +827,11 @@ impl HandoffSegmentStore { root.display() ); } + let root_lock = acquire_root_lock(&root)?; + fsinfo::restrict_to_owner(&root, 0o700)?; + let Some(limits) = select_limits(&root)? else { + return Ok(None); + }; for directory in [ SEGMENT_DIR, MANIFEST_DIR, @@ -781,10 +846,8 @@ impl HandoffSegmentStore { })?; fsinfo::restrict_to_owner(&path, 0o700)?; } - fsinfo::restrict_to_owner(&root, 0o700)?; - let root_lock = acquire_root_lock(&root)?; let packed = PackedSegmentStore::open(&root)?; - Ok(Self { + Ok(Some(Self { root, limits: RwLock::new(limits), _root_lock: root_lock, @@ -799,7 +862,7 @@ impl HandoffSegmentStore { quarantined_objects: AtomicU64::new(0), inflight_segments: Mutex::new(std::collections::BTreeMap::new()), packed, - }) + })) } pub fn root(&self) -> &Path { @@ -1144,29 +1207,36 @@ impl HandoffSegmentStore { } /// Store one spill's logical segments in one immutable physical pack. - pub fn try_put_segments<'store>( - &'store self, + pub fn try_put_segments( + &self, segments: &[&[u8]], - ) -> Result>, WriteRefusal>> { - let digests = segments + ) -> Result>, WriteRefusal>> { + let inputs = segments .iter() - .map(|bytes| segment_digest(bytes)) + .map(|bytes| (segment_digest(bytes), *bytes)) .collect::>(); - let holds = digests + let inputs = inputs .iter() - .map(|digest| self.hold_segment(digest)) + .map(|(digest, bytes)| (digest.as_str(), *bytes)) .collect::>(); - let inputs = digests + self.try_put_hashed_segments(&inputs) + } + + /// Callers must compute each digest from the supplied immutable slice. + pub(crate) fn try_put_hashed_segments( + &self, + inputs: &[(&str, &[u8])], + ) -> Result>, WriteRefusal>> { + let holds = inputs .iter() - .zip(segments) - .map(|(digest, bytes)| (digest.as_str(), *bytes)) + .map(|(digest, _)| self.hold_segment(digest)) .collect::>(); - let estimated = self.packed.estimated_new_bytes(&inputs); + let estimated = self.packed.estimated_new_bytes(inputs); let reservation = match self.reserve(estimated)? { Ok(reservation) => reservation, Err(refusal) => return Ok(Err(refusal)), }; - let (packed, new_bytes) = match self.packed.write_batch(&inputs) { + let (packed, new_bytes) = match self.packed.write_batch(inputs) { Ok(result) => result, Err(error) => { self.invalidate_usage(); @@ -1175,13 +1245,12 @@ impl HandoffSegmentStore { }; self.add_usage_bytes(new_bytes); drop(reservation); - Ok(Ok(digests - .into_iter() + Ok(Ok(inputs + .iter() .zip(holds) .zip(packed) - .zip(segments) - .map(|(((digest, hold), packed), bytes)| StoredSegment { - digest, + .map(|(((digest, bytes), hold), packed)| StoredSegment { + digest: (*digest).to_owned(), put: SegmentPut { new: packed.new, bytes: bytes.len() as u64, @@ -1410,13 +1479,14 @@ impl HandoffSegmentStore { Ok(entries.into_iter().map(|(_, stem)| stem).collect()) } - /// Assemble the full payload for a manifest, verifying every segment - /// digest, the tiling, and the whole-payload digest. + /// Assemble a checkpoint from verified pages. Legacy handoff manifests + /// additionally verify the digest of the assembled bytes. pub fn assemble(&self, manifest: &HandoffManifest) -> Result> { validate_manifest_compatibility(manifest)?; let total = usize::try_from(manifest.total_bytes).context("payload exceeds usize")?; let mut payload = Vec::with_capacity(total); - let mut payload_hasher = blake3::Hasher::new(); + let mut payload_hasher = + (manifest.version != CHECKPOINT_MANIFEST_VERSION).then(blake3::Hasher::new); let locations = self .packed .load_manifest_index(&manifest.payload_digest, manifest.segments.len())?; @@ -1449,21 +1519,25 @@ impl HandoffSegmentStore { output_offset: segment.offset, }); } else { - self.append_packed(&packed_requests, &mut payload, &mut payload_hasher)?; + self.append_packed(&packed_requests, &mut payload, payload_hasher.as_mut())?; packed_requests.clear(); let bytes = self.read_segment(&segment.digest)?; - payload_hasher.update(&bytes); + if let Some(hasher) = &mut payload_hasher { + hasher.update(&bytes); + } payload.extend_from_slice(&bytes); } } - self.append_packed(&packed_requests, &mut payload, &mut payload_hasher)?; + self.append_packed(&packed_requests, &mut payload, payload_hasher.as_mut())?; if payload.len() != total { bail!( "assembled {} bytes but manifest records {total}", payload.len() ); } - if payload_hasher.finalize().to_hex().as_str() != manifest.payload_digest { + if payload_hasher + .is_some_and(|hasher| hasher.finalize().to_hex().as_str() != manifest.payload_digest) + { bail!("assembled payload failed manifest digest verification"); } Ok(payload) @@ -1473,12 +1547,9 @@ impl HandoffSegmentStore { &self, requests: &[PackedReadRequest<'_>], payload: &mut Vec, - payload_hasher: &mut blake3::Hasher, + payload_hasher: Option<&mut blake3::Hasher>, ) -> Result<()> { - match self - .packed - .append_many(requests, payload, Some(payload_hasher)) - { + match self.packed.append_many(requests, payload, payload_hasher) { Ok(()) => Ok(()), Err(failure) => { let path = self.packed.pack_path(&failure.pack_digest); @@ -1721,10 +1792,7 @@ impl HandoffSegmentStore { /// The level eviction drops to once it runs. fn low_water_bytes(&self) -> u64 { - self.limits() - .budget_bytes - .saturating_mul(EVICTION_LOW_WATER_PERCENT) - / 100 + self.limits().low_water_bytes().unwrap_or_default() } /// Evict until managed usage is at or below `target_bytes`. @@ -1973,10 +2041,15 @@ fn reject_unsupported_codec(manifest: &HandoffManifest) -> Result<()> { /// and the two legacy formats (pre-codec and payload-level-codec). fn manifest_version_is_supported(version: u32) -> bool { version == MANIFEST_VERSION + || version == CHECKPOINT_MANIFEST_VERSION || version == LEGACY_MANIFEST_VERSION || version == LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION } +fn manifest_has_segment_codecs(version: u32) -> bool { + matches!(version, MANIFEST_VERSION | CHECKPOINT_MANIFEST_VERSION) +} + /// Reject a manifest whose segment codec identities this build cannot decode, /// before any segment is read or reassembled. Also enforces the per-segment /// negotiation contract: every identity must be internally consistent with @@ -2010,7 +2083,7 @@ fn reject_unsupported_segment_codecs(manifest: &HandoffManifest) -> Result<()> { .as_deref() .is_some_and(|descriptor| serde_json::from_str::(descriptor).is_ok()); if has_native_kv - && (manifest.version != MANIFEST_VERSION + && (!manifest_has_segment_codecs(manifest.version) || manifest.payload_kind != "kv-recurrent" || manifest.kv_bytes == 0 || !has_runtime_descriptor @@ -2023,7 +2096,7 @@ fn reject_unsupported_segment_codecs(manifest: &HandoffManifest) -> Result<()> { ); } if has_cachegen_kv - && (manifest.version != MANIFEST_VERSION + && (!manifest_has_segment_codecs(manifest.version) || manifest.payload_kind != "kv-recurrent" || manifest.kv_bytes == 0 || manifest.kv_decoded_bytes == 0 @@ -2157,7 +2230,8 @@ fn validate_manifest_compatibility(manifest: &HandoffManifest) -> Result<()> { manifest.version ); } - if manifest.version == MANIFEST_VERSION { + manifest.verify_checkpoint()?; + if manifest_has_segment_codecs(manifest.version) { require_v4_segment_identities(manifest)?; } reject_unsupported_codec(manifest)?; @@ -2168,7 +2242,7 @@ fn decode_manifest(payload_digest: &str, bytes: &[u8]) -> Result { + MANIFEST_VERSION | CHECKPOINT_MANIFEST_VERSION => { // The current format must stamp both the payload codec and every // per-segment codec identity explicitly. A missing field means it // was stripped to force a reinterpretation of bytes this build @@ -2217,6 +2291,7 @@ fn decode_manifest(payload_digest: &str, bytes: &[u8]) -> Result::new(); let mut pack_segments = Vec::new(); - let mut pack_hasher = blake3::Hasher::new(); + let mut pack_hasher = blake3::Hasher::new_derive_key("Skippy L3 pack page list v1"); let mut candidate_bytes = 0u64; let mut new_digests = HashSet::new(); @@ -140,7 +140,8 @@ impl PackedSegmentStore { candidate_bytes = candidate_bytes .checked_add(bytes.len() as u64) .context("packed object size overflows u64")?; - pack_hasher.update(bytes); + // Page digests are fixed-width and already cover the stored bytes. + pack_hasher.update(digest.as_bytes()); pack_segments.push(*bytes); planned.insert( (*digest).to_string(), @@ -562,7 +563,7 @@ fn write_pack_atomically(path: &Path, segments: &[&[u8]]) -> Result<()> { Ok(()) } -fn is_digest(value: &str) -> bool { +pub(super) fn is_digest(value: &str) -> bool { value.len() == 64 && value .bytes() diff --git a/crates/skippy-cache/src/l3/tests.rs b/crates/skippy-cache/src/l3/tests.rs index 12828f80..926ec864 100644 --- a/crates/skippy-cache/src/l3/tests.rs +++ b/crates/skippy-cache/src/l3/tests.rs @@ -914,7 +914,7 @@ fn future_version_raw_manifest_is_refused_at_commit_and_leaves_no_manifest() { let (mut manifest, held) = manifest_for(&store, &payload, 4096); // A supported (raw) codec but an unknown future version: commit must refuse // it, or it would persist a manifest load_manifest immediately rejects. - manifest.version = MANIFEST_VERSION + 1; + manifest.version = CHECKPOINT_MANIFEST_VERSION + 1; let error = store .commit(&manifest) .expect_err("a future manifest version must not commit"); @@ -938,7 +938,7 @@ fn future_version_raw_manifest_is_refused_before_assembly() { let mut loaded = store .load_manifest(&manifest.payload_digest) .expect("load manifest"); - loaded.version = MANIFEST_VERSION + 1; + loaded.version = CHECKPOINT_MANIFEST_VERSION + 1; let error = store .assemble(&loaded) .expect_err("a future manifest version must not assemble"); diff --git a/crates/skippy-cache/src/lib.rs b/crates/skippy-cache/src/lib.rs index fbc6e33c..007136e6 100644 --- a/crates/skippy-cache/src/lib.rs +++ b/crates/skippy-cache/src/lib.rs @@ -26,12 +26,13 @@ pub use l2::{ l2_cache_key, }; pub use l3::{ - CODEC_CACHEGEN_KV_ENVELOPE, CODEC_CACHEGEN_KV_ENVELOPE_VERSION, CODEC_NATIVE_KV_PAGE, - CODEC_NATIVE_KV_PAGE_VERSION, CODEC_RAW, CODEC_RAW_VERSION, CodecClass, GeometryBlock, - GeometryKind, HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, LEGACY_MANIFEST_VERSION, - LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION, MANIFEST_VERSION, ManifestPin, PayloadCodec, - PayloadGeometry, Reservation, SegmentCodecIdentity, SegmentHold, SegmentPut, StoreLimits, - StorePressure, StoreReconciliation, StoreUsage, StoredSegment, WriteRefusal, segment_digest, + CHECKPOINT_MANIFEST_VERSION, CODEC_CACHEGEN_KV_ENVELOPE, CODEC_CACHEGEN_KV_ENVELOPE_VERSION, + CODEC_NATIVE_KV_PAGE, CODEC_NATIVE_KV_PAGE_VERSION, CODEC_RAW, CODEC_RAW_VERSION, + CacheRootInUse, CodecClass, GeometryBlock, GeometryKind, HandoffManifest, HandoffSegmentRef, + HandoffSegmentStore, LEGACY_MANIFEST_VERSION, LEGACY_PAYLOAD_CODEC_MANIFEST_VERSION, + MANIFEST_VERSION, ManifestPin, PayloadCodec, PayloadGeometry, Reservation, + SegmentCodecIdentity, SegmentHold, SegmentPut, StoreLimits, StorePressure, StoreReconciliation, + StoreUsage, StoredSegment, WriteRefusal, segment_digest, }; pub use l3_remote::{ FetchStats, KvFetchClient, serve_connection, serve_store, serve_store_with_timeout, @@ -54,7 +55,8 @@ pub use resident::{ pub use source::{ManifestSource, SegmentSource}; pub use tier::{ - CacheGenKvPayload, L3Fill, L3Location, L3Status, L3Tier, l3_namespace_key, l3_prefix_key, + CacheGenKvPayload, L3Fill, L3Location, L3Status, L3Tier, NativeKvExtension, l3_namespace_key, + l3_prefix_key, }; /// llama.cpp's hard sequence-id capacity for one context. diff --git a/crates/skippy-cache/src/manager.rs b/crates/skippy-cache/src/manager.rs index 210ec4fc..acb8468a 100644 --- a/crates/skippy-cache/src/manager.rs +++ b/crates/skippy-cache/src/manager.rs @@ -10,7 +10,7 @@ use std::{ }; use anyhow::Result; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::{ l3::{HandoffSegmentStore, StoreLimits, StoreReconciliation, StoreUsage, WriteRefusal}, @@ -75,7 +75,7 @@ impl L3Activity { } /// Point-in-time activity across every stage attached to one root manager. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct L3ActivitySnapshot { pub fills: u64, pub hits: u64, @@ -110,7 +110,7 @@ pub enum L3EffectiveState { Degraded, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum L3StateReason { ReadOnlyLowSpace, @@ -851,7 +851,7 @@ mod tests { fs::write(root.join("manifests/corrupt.json"), b"{").unwrap(); let mut incompatible = crate::HandoffManifest::new("state".to_string(), "full-state".to_string()); - incompatible.version = crate::MANIFEST_VERSION + 1; + incompatible.version = crate::CHECKPOINT_MANIFEST_VERSION + 1; incompatible.payload_digest = "incompatible".to_string(); fs::write( root.join("manifests/incompatible.json"), diff --git a/crates/skippy-cache/src/manager/acquisition.rs b/crates/skippy-cache/src/manager/acquisition.rs index 09278fe0..5914c7d2 100644 --- a/crates/skippy-cache/src/manager/acquisition.rs +++ b/crates/skippy-cache/src/manager/acquisition.rs @@ -70,22 +70,18 @@ fn acquire_with_budget(root: &Path, budget: AcquisitionBudget) -> Result Result { - let store = Arc::new(open_store_for_acquire(root, limits, expiring_owner)?); +fn create_manager(store: HandoffSegmentStore) -> Result { + let store = Arc::new(store); let reconciliation = store.reconcile_startup()?; let inner = Arc::new(L3ManagerInner { store, @@ -104,16 +100,16 @@ fn create_manager( /// Retry briefly while the previous in-process owner releases its root lock. fn open_store_for_acquire( root: &Path, - limits: StoreLimits, + budget: AcquisitionBudget, expiring_owner: bool, -) -> Result { +) -> Result> { const HANDOFF_ATTEMPTS: u32 = 20; const HANDOFF_BACKOFF: std::time::Duration = std::time::Duration::from_millis(5); let attempts = if expiring_owner { HANDOFF_ATTEMPTS } else { 1 }; let mut last = None; for attempt in 0..attempts { - match HandoffSegmentStore::open_unreconciled_with_limits(root, limits) { + match HandoffSegmentStore::open_unreconciled(root, |root| budget.new_owner_limits(root)) { Ok(store) => return Ok(store), Err(error) => { last = Some(error); diff --git a/crates/skippy-cache/src/radix.rs b/crates/skippy-cache/src/radix.rs index e6a480ee..144c7852 100644 --- a/crates/skippy-cache/src/radix.rs +++ b/crates/skippy-cache/src/radix.rs @@ -354,7 +354,47 @@ impl UnifiedRadixCache { } pub fn evict_lru_recurrent(&mut self) -> Option> { - let victim = self.lru_victim(ComponentKind::KvRecurrent)?; + self.evict_recurrent_by_retention(|_| 0) + } + + /// The retention of the entry [`Self::evict_recurrent_by_retention`] + /// would evict next, if any is evictable. + pub fn recurrent_victim_retention(&self, retention: impl Fn(&E) -> u64) -> Option { + self.ranked_victim(&|node| { + node.components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| { + ( + retention(&entry.value), + entry.last_used, + entry.logical_bytes, + ) + }) + }) + .map(|victim| victim.retention) + } + + /// Evict the unreferenced recurrent entry with the lowest `retention`, + /// least recently used first among equals. + pub fn evict_recurrent_by_retention( + &mut self, + retention: impl Fn(&E) -> u64, + ) -> Option> { + let victim = self.ranked_victim(&|node| { + node.components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| { + ( + retention(&entry.value), + entry.last_used, + entry.logical_bytes, + ) + }) + })?; let value = self.remove_recurrent(&victim.namespace, &victim.tokens)?; self.recurrent_evictions = self.recurrent_evictions.saturating_add(1); Some(RadixEviction { @@ -365,6 +405,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(), @@ -391,9 +460,29 @@ impl UnifiedRadixCache { } fn lru_victim(&self, component: ComponentKind) -> Option { + self.ranked_victim(&|node| match component { + ComponentKind::ResidentKv => node + .components + .resident + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| (0, entry.last_used, entry.logical_bytes)), + ComponentKind::KvRecurrent => node + .components + .recurrent + .as_ref() + .filter(|entry| entry.active_refs == 0) + .map(|entry| (0, entry.last_used, entry.logical_bytes)), + }) + } + + /// The evictable node with the lowest `(retention, last_used)`, where + /// `candidate` yields `(retention, last_used, logical_bytes)` for nodes + /// holding an evictable entry. + fn ranked_victim(&self, candidate: &VictimCandidate<'_, R, E>) -> Option { let mut victim = None; for (namespace, root) in &self.roots { - collect_lru_victim(namespace, root, component, &mut Vec::new(), &mut victim); + collect_lru_victim(namespace, root, candidate, &mut Vec::new(), &mut victim); } victim } @@ -636,6 +725,7 @@ struct Victim { tokens: Vec, logical_bytes: u64, last_used: u64, + retention: u64, } fn validate_tokens(tokens: &[i32]) -> Result<()> { @@ -832,35 +922,24 @@ fn find_recurrent_path( None } +type VictimCandidate<'a, R, E> = dyn Fn(&RadixNode) -> Option<(u64, u64, u64)> + 'a; + fn collect_lru_victim( namespace: &str, node: &RadixNode, - component: ComponentKind, + candidate: &VictimCandidate<'_, R, E>, path: &mut Vec, victim: &mut Option, ) { let original_len = path.len(); path.extend_from_slice(&node.edge); - let candidate = match component { - ComponentKind::ResidentKv => node - .components - .resident - .as_ref() - .filter(|entry| entry.active_refs == 0) - .map(|entry| (entry.last_used, entry.logical_bytes)), - ComponentKind::KvRecurrent => node - .components - .recurrent - .as_ref() - .filter(|entry| entry.active_refs == 0) - .map(|entry| (entry.last_used, entry.logical_bytes)), - }; - if let Some((last_used, logical_bytes)) = candidate { + if let Some((retention, last_used, logical_bytes)) = candidate(node) { let replace = victim .as_ref() .map(|current| { - (last_used, namespace, path.as_slice()) + (retention, last_used, namespace, path.as_slice()) < ( + current.retention, current.last_used, current.namespace.as_str(), current.tokens.as_slice(), @@ -873,15 +952,69 @@ fn collect_lru_victim( tokens: path.clone(), logical_bytes, last_used, + retention, }); } } for child in node.children.values() { - collect_lru_victim(namespace, child, component, path, victim); + collect_lru_victim(namespace, child, candidate, path, 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, + retention: 0, + }); + } + } + path.truncate(original_len); + below || entry.is_some() +} + fn collect_resident_eviction_candidates( namespace: &str, node: &RadixNode, @@ -1319,6 +1452,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/crates/skippy-cache/src/tier.rs b/crates/skippy-cache/src/tier.rs index e6284972..4e581175 100644 --- a/crates/skippy-cache/src/tier.rs +++ b/crates/skippy-cache/src/tier.rs @@ -10,8 +10,10 @@ use std::sync::atomic::Ordering; +mod native_extension; mod spill_payload; mod spill_segments; +pub use native_extension::NativeKvExtension; use spill_payload::SpillPayload; #[cfg(test)] @@ -20,8 +22,8 @@ use anyhow::{Context, Result, bail}; use serde::Serialize; use crate::l3::{ - HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, MANIFEST_VERSION, PayloadCodec, - PayloadGeometry, StoreLimits, StoreUsage, segment_digest, + CHECKPOINT_MANIFEST_VERSION, HandoffManifest, HandoffSegmentRef, HandoffSegmentStore, + PayloadCodec, PayloadGeometry, StoreLimits, StoreUsage, segment_digest, }; use crate::manager::{ BenefitRestoreObservation, L3ActivitySnapshot, L3CacheManager, L3EffectiveStatus, @@ -48,13 +50,26 @@ pub struct L3Status { /// namespace (which already binds the numerical stage identity) and the /// exact token path. pub fn l3_prefix_key(namespace: &str, token_ids: &[i32]) -> String { + let mut hasher = l3_prefix_hasher(namespace); + hash_l3_tokens(&mut hasher, token_ids); + format!("blake3:{}", hasher.finalize().to_hex()) +} + +fn l3_prefix_hasher(namespace: &str) -> blake3::Hasher { let mut hasher = blake3::Hasher::new(); hasher.update(b"l3-prefix-key-v1"); hasher.update(namespace.as_bytes()); - for token_id in token_ids { - hasher.update(&token_id.to_le_bytes()); + hasher +} + +fn hash_l3_tokens(hasher: &mut blake3::Hasher, token_ids: &[i32]) { + let mut encoded = [0; 4096]; + for tokens in token_ids.chunks(encoded.len() / size_of::()) { + for (bytes, token) in encoded.as_chunks_mut::<4>().0.iter_mut().zip(tokens) { + *bytes = token.to_le_bytes(); + } + hasher.update(&encoded[..size_of_val(tokens)]); } - format!("blake3:{}", hasher.finalize().to_hex()) } /// The namespace's own index key. @@ -88,7 +103,7 @@ pub struct L3Location { pub namespace_key: String, pub prefix_key: String, pub token_count: u64, - /// Manifest key (payload digest) — the identity of the physical entry; + /// Manifest key, the identity of the stored checkpoint and /// the correct single-flight claim key. pub manifest_key: String, /// Metadata copied from the located manifest so the runtime can reject an @@ -101,8 +116,10 @@ pub struct L3Location { } /// A successful fill from the tier. +#[derive(Clone)] pub struct L3Fill { pub payload: ExactStatePayload, + pub manifest: HandoffManifest, /// How many of the query's leading tokens the filled state covers — the /// length the entry was recorded at, which may be shorter than the /// query (longest-recorded-prefix semantics, mirroring the radix). @@ -230,13 +247,10 @@ impl L3Tier { &self, namespace: &str, token_ids: &[i32], - location: &L3Location, + manifest: &HandoffManifest, cold_prefill_cost: Option, restore_cost: f64, ) { - let Ok(manifest) = self.store().load_manifest(&location.manifest_key) else { - return; - }; let shared = manifest .segments .iter() @@ -246,7 +260,7 @@ impl L3Tier { .benefit_observe_restore(BenefitRestoreObservation { state_identity: self.state_identity.clone(), key: benefit_entry_key(namespace, token_ids), - manifest: location.manifest_key.clone(), + manifest: manifest.payload_digest.clone(), exclusive_bytes: 0, shared, cold_prefill_cost, @@ -277,7 +291,7 @@ impl L3Tier { model_identity: self.model_identity.clone(), state_identity: self.state_identity.clone(), effective: self.manager.effective_status(), - format_version: MANIFEST_VERSION, + format_version: CHECKPOINT_MANIFEST_VERSION, usage: self.store().usage()?, restorable_manifests: restorable_manifests as u64, restorable_tokens, @@ -384,15 +398,14 @@ impl L3Tier { 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(), self.state_identity.clone(), payload.kind().as_str().to_string(), ); + manifest.version = CHECKPOINT_MANIFEST_VERSION; manifest.total_bytes = wire.len() as u64; - manifest.payload_digest = payload_digest.clone(); + manifest.prefix_key = Some(l3_prefix_key(namespace, token_ids)); manifest.kv_bytes = kv_bytes; manifest.kv_decoded_bytes = kv_decoded_bytes; manifest.recurrent_bytes = recurrent_bytes; @@ -457,6 +470,30 @@ impl L3Tier { meta_json: (!cut.label.is_empty()).then(|| cut.label.clone()), }) .collect(); + self.commit_spill( + namespace, + token_ids, + manifest, + segment_slices.into_iter().map(Some).collect(), + cost, + ) + } + + fn commit_spill( + &self, + namespace: &str, + token_ids: &[i32], + mut manifest: HandoffManifest, + fresh_segments: Vec>, + cost: Option, + ) -> Result> { + let prefix_key = manifest + .prefix_key + .clone() + .context("missing checkpoint prefix")?; + let token_count = manifest.token_count; + let payload_digest = manifest.checkpoint_digest()?; + manifest.payload_digest.clone_from(&payload_digest); let exclusive_bytes = serde_json::to_vec(&manifest) .map(|bytes| bytes.len() as u64) .unwrap_or_default(); @@ -474,11 +511,22 @@ impl L3Tier { } if !self.manager.benefit_prepare_write( benefit_key, - (wire.len() as u64).saturating_add(exclusive_bytes), + fresh_segments + .iter() + .flatten() + .fold(exclusive_bytes, |total, bytes| { + total.saturating_add(bytes.len() as u64) + }), )? { return Ok(None); } - let stored_segments = match self.store().try_put_segments(&segment_slices) { + let hashed_segments = manifest + .segments + .iter() + .zip(fresh_segments) + .filter_map(|(segment, bytes)| bytes.map(|bytes| (segment.digest.as_str(), bytes))) + .collect::>(); + let stored_segments = match self.store().try_put_hashed_segments(&hashed_segments) { Ok(Ok(stored)) => stored, Ok(Err(refusal)) => { self.manager.record_write_refusal(refusal); @@ -521,7 +569,7 @@ impl L3Tier { if let Err(error) = self.store().link_prefix( &l3_namespace_key(namespace), token_count, - &l3_prefix_key(namespace, token_ids), + &prefix_key, &payload_digest, ) { self.manager.record_storage_error(); @@ -583,18 +631,40 @@ impl L3Tier { let namespace_key = l3_namespace_key(namespace); let query_len = token_ids.len() as u64; let lengths = self.store().recorded_prefix_lengths(&namespace_key)?; - for length in lengths + let candidates: Vec<_> = lengths .into_iter() .filter(|length| *length > 0 && *length <= query_len) .take(max_probes.max(1)) - { - let prefix_key = l3_prefix_key(namespace, &token_ids[..length as usize]); + .collect(); + // Snapshot each selected prefix from the same token stream. Probe + // disk in the original longest-first order. + let mut hasher = l3_prefix_hasher(namespace); + let mut hashed = 0; + let digests: Vec<_> = candidates + .iter() + .rev() + .map(|&length| { + let end = length as usize; + hash_l3_tokens(&mut hasher, &token_ids[hashed..end]); + hashed = end; + hasher.finalize() + }) + .collect(); + for (length, digest) in candidates.into_iter().zip(digests.into_iter().rev()) { + let prefix_key = format!("blake3:{}", digest.to_hex()); let Some(manifest) = self.store() .manifest_for_prefix(&namespace_key, length, &prefix_key)? else { continue; }; + if manifest + .prefix_key + .as_ref() + .is_some_and(|key| key != &prefix_key) + { + continue; + } if manifest.model_identity != self.model_identity || manifest.state_identity != self.state_identity { @@ -633,13 +703,18 @@ impl L3Tier { /// itself. Full-state fills are whole-blob by nature; kv-recurrent /// fills could stream per segment later. pub fn load(&self, location: &L3Location) -> Result { + self.load_bounded(location, u64::MAX) + } + + /// Bound the packed buffers allocated before any page bytes are read. + pub fn load_bounded(&self, location: &L3Location, max_bytes: u64) -> Result { let Some(_operation) = self.manager.try_operation_guard() else { bail!("disk cache lifecycle operation in progress"); }; // Pinned for the whole load: eviction under a concurrent spill must // not remove the segments this fill is assembling. let _pin = self.store().pin(&location.manifest_key); - let result = self.load_inner(location); + let result = self.load_inner(location, max_bytes); match &result { Ok(fill) => { self.manager @@ -656,8 +731,19 @@ impl L3Tier { result } - fn load_inner(&self, location: &L3Location) -> Result { + fn load_inner(&self, location: &L3Location, max_bytes: u64) -> Result { let manifest = self.store().load_manifest(&location.manifest_key)?; + if manifest.total_bytes > max_bytes { + bail!("L3 checkpoint exceeds the staging budget"); + } + if manifest.token_count != location.token_count + || manifest + .prefix_key + .as_ref() + .is_some_and(|key| key != &location.prefix_key) + { + bail!("L3 manifest does not match the located prefix"); + } if manifest.model_identity != self.model_identity || manifest.state_identity != self.state_identity { @@ -693,10 +779,11 @@ impl L3Tier { Ok(L3Fill { payload, token_count: manifest.token_count, - kv_desc_json: manifest.kv_desc_json, + kv_desc_json: manifest.kv_desc_json.clone(), payload_bytes, cachegen_kv, kv_decoded_bytes: manifest.kv_decoded_bytes, + manifest, }) } @@ -741,6 +828,31 @@ mod tests { CODEC_NATIVE_KV_PAGE, CODEC_NATIVE_KV_PAGE_VERSION, GeometryBlock, GeometryKind, }; + #[test] + fn streaming_prefix_hashes_match_the_existing_disk_keys() { + let namespace = "model/prefix-v1"; + let tokens: Vec = (-1400..1700).collect(); + let mut hashed = 0; + let mut stream = l3_prefix_hasher(namespace); + for end in [1, 19, 1025, 2505, tokens.len()] { + hash_l3_tokens(&mut stream, &tokens[hashed..end]); + hashed = end; + + let mut original = blake3::Hasher::new(); + original.update(b"l3-prefix-key-v1"); + original.update(namespace.as_bytes()); + for token in &tokens[..end] { + original.update(&token.to_le_bytes()); + } + let digest = original.finalize(); + assert_eq!(stream.finalize(), digest); + assert_eq!( + l3_prefix_key(namespace, &tokens[..end]), + format!("blake3:{}", digest.to_hex()), + ); + } + } + fn temp_root(name: &str) -> std::path::PathBuf { let root = std::env::temp_dir() .join("skippy-l3-tier-tests") @@ -861,7 +973,13 @@ mod tests { .expect("seed locate") .expect("seed location"); assert_eq!(seed_location.manifest_key, seed); - tier.benefit_observe_l3_restore("ns", &seed_tokens, &seed_location, Some(400.0), 100.0); + tier.benefit_observe_l3_restore( + "ns", + &seed_tokens, + &tier.load(&seed_location).unwrap().manifest, + Some(400.0), + 100.0, + ); let candidate_tokens = tokens(8); let candidate_payload = ExactStatePayload::full_state(vec![9; 256]); @@ -1176,6 +1294,77 @@ mod tests { ); } + #[test] + fn native_extension_reuses_whole_windows_and_restores_the_new_recurrent_state() { + use std::num::NonZeroU64; + + let tier = tier("native-tail", "blake3:native"); + let base = kv_payload(1, 10, 16, 16); + let plan = kv_geometry(1, 10, 16, 16, 4); + tier.spill( + "ns", + &tokens(10), + &base, + Some(runtime_kv_desc(1, 10, 320)), + Some(&plan), + ) + .unwrap(); + let base = tier.locate_longest("ns", &tokens(10), 1).unwrap().unwrap(); + let bytes_before = tier.activity().bytes_written; + let full = kv_payload(1, 15, 16, 16); + let full = full.kv_bytes().unwrap().unwrap(); + let tail = [&full[128..240], &full[368..480]].concat(); + let recurrent = [42u8; 50]; + let geometry = PayloadGeometry { + tail_bytes: 50, + ..kv_geometry(1, 15, 16, 16, 4) + }; + let key = tier + .spill_native_extension( + "ns", + &tokens(15), + NativeKvExtension { + base: &base, + reused_rows: NonZeroU64::new(8).unwrap(), + geometry: &geometry, + kv_desc_json: runtime_kv_desc(1, 15, 480), + kv_tail: &tail, + recurrent: &recurrent, + }, + ) + .unwrap() + .unwrap(); + assert_eq!( + tier.activity().bytes_written - bytes_before, + (tail.len() + recurrent.len()) as u64 + ); + + let fill = tier.fill_longest("ns", &tokens(15), 1).unwrap().unwrap(); + assert_eq!(fill.payload.kv_bytes().unwrap().unwrap(), full); + assert_eq!( + fill.payload.recurrent_state_bytes().unwrap().as_ref(), + recurrent + ); + assert_eq!(fill.manifest.payload_digest, key); + let mut tampered = fill.manifest; + tampered.segments[0].digest = segment_digest(b"wrong page"); + assert!(tier.store().assemble(&tampered).is_err()); + + tier.store() + .link_prefix( + &l3_namespace_key("other"), + 15, + &l3_prefix_key("other", &tokens(15)), + &key, + ) + .unwrap(); + assert!( + tier.locate_longest("other", &tokens(15), 1) + .unwrap() + .is_none() + ); + } + #[test] fn fixed_offset_cutting_is_what_fails_the_gate() { // The same growth without geometry: this is the 8x the probe measured, @@ -1238,7 +1427,7 @@ mod tests { let fill = tier.load(&location).unwrap(); let status = tier.status().unwrap(); - assert_eq!(status.format_version, MANIFEST_VERSION); + assert_eq!(status.format_version, CHECKPOINT_MANIFEST_VERSION); assert_eq!(status.restorable_manifests, 1); assert_eq!(status.restorable_tokens, 3); assert_eq!(status.namespaces, 1); diff --git a/crates/skippy-cache/src/tier/native_extension.rs b/crates/skippy-cache/src/tier/native_extension.rs new file mode 100644 index 00000000..994e92f3 --- /dev/null +++ b/crates/skippy-cache/src/tier/native_extension.rs @@ -0,0 +1,188 @@ +use std::{collections::HashMap, num::NonZeroU64}; + +use anyhow::{Context, Result, ensure}; + +use crate::{GeometryBlock, SegmentCodecIdentity}; + +use super::*; + +/// New native rows and recurrent state for a prefix backed by durable pages. +/// The geometry describes the full checkpoint at its final token boundary. +pub struct NativeKvExtension<'a> { + pub base: &'a L3Location, + pub reused_rows: NonZeroU64, + pub geometry: &'a PayloadGeometry, + pub kv_desc_json: String, + pub kv_tail: &'a [u8], + pub recurrent: &'a [u8], +} + +impl L3Tier { + pub fn spill_native_extension( + &self, + namespace: &str, + tokens: &[i32], + extension: NativeKvExtension<'_>, + ) -> Result> { + let _operation = self.manager.operation_guard(); + let _base_pin = self.store().pin(&extension.base.manifest_key); + let base = self.store().load_manifest(&extension.base.manifest_key)?; + let base_tokens = tokens + .get(..usize::try_from(base.token_count)?) + .context("base extends past the new checkpoint")?; + ensure!( + base.version == CHECKPOINT_MANIFEST_VERSION + && base.uses_native_kv_passthrough() + && base.model_identity == self.model_identity + && base.state_identity == self.state_identity + && base.prefix_key.as_deref() == Some(&l3_prefix_key(namespace, base_tokens)), + "base checkpoint is incompatible with this extension" + ); + let reused = extension.reused_rows.get(); + let geometry = extension.geometry; + ensure!( + geometry.rows == tokens.len() as u64 + && geometry.window_rows > 0 + && reused.is_multiple_of(geometry.window_rows) + && reused <= base.token_count + && reused < geometry.rows + && geometry.tail_bytes == extension.recurrent.len() as u64, + "invalid native extension geometry" + ); + + let mut manifest = HandoffManifest::new_for_model( + self.model_identity.clone(), + self.state_identity.clone(), + "kv-recurrent".to_owned(), + ); + manifest.version = CHECKPOINT_MANIFEST_VERSION; + manifest.prefix_key = Some(l3_prefix_key(namespace, tokens)); + manifest.token_count = geometry.rows; + manifest.total_bytes = geometry.total_bytes(); + manifest.recurrent_bytes = geometry.tail_bytes; + manifest.kv_bytes = manifest + .total_bytes + .checked_sub(geometry.tail_bytes) + .context("native extension KV size underflows")?; + manifest.kv_decoded_bytes = manifest.kv_bytes; + manifest.kv_desc_json = Some(extension.kv_desc_json); + + let mut pages = ExtensionPages { + reusable: base + .segments + .iter() + .filter_map(|page| { + page.codec_identity + .as_ref() + .filter(|codec| codec.is_native_kv_page())?; + Some((page.meta_json.as_deref()?, page)) + }) + .collect(), + fresh: Vec::new(), + manifest: &mut manifest, + offset: 0, + }; + let mut tail = extension.kv_tail; + for block in &geometry.blocks { + pages.append_run(block, &mut tail, geometry, reused)?; + } + ensure!(tail.is_empty(), "unused native extension KV bytes"); + for chunk in extension.recurrent.chunks(self.segment_bytes) { + pages.append( + chunk.len() as u64, + Some(chunk), + None, + SegmentCodecIdentity::raw(chunk.len() as u64), + "tail".into(), + )?; + } + ensure!( + pages.offset == pages.manifest.total_bytes, + "incorrect native extension length" + ); + let fresh = pages.fresh; + self.commit_spill(namespace, tokens, manifest, fresh, None) + } +} + +struct ExtensionPages<'base, 'fresh, 'out> { + reusable: HashMap<&'base str, &'base HandoffSegmentRef>, + fresh: Vec>, + manifest: &'out mut HandoffManifest, + offset: u64, +} + +impl<'fresh> ExtensionPages<'_, 'fresh, '_> { + fn append_run( + &mut self, + block: &GeometryBlock, + tail: &mut &'fresh [u8], + geometry: &PayloadGeometry, + reused: u64, + ) -> Result<()> { + let mut row = 0; + while row < geometry.rows { + let rows = geometry.window_rows.min(geometry.rows - row); + let bytes = rows + .checked_mul(block.stride) + .context("page size overflows")?; + let label = format!( + "{}:{}:{}:{row}", + block.kind.as_str(), + block.layer, + block.column + ); + let (fresh, reused_page) = if row < reused { + let page = self + .reusable + .get(label.as_str()) + .filter(|page| page.bytes == bytes) + .context("base checkpoint is missing a reusable page")?; + (None, Some(page.digest.clone())) + } else { + let (chunk, next) = tail + .split_at_checked(usize::try_from(bytes)?) + .context("native extension KV is truncated")?; + *tail = next; + (Some(chunk), None) + }; + self.append( + bytes, + fresh, + reused_page, + SegmentCodecIdentity::native_kv_page(bytes), + label, + )?; + row += rows; + } + Ok(()) + } + + fn append( + &mut self, + bytes: u64, + fresh: Option<&'fresh [u8]>, + reused: Option, + codec: SegmentCodecIdentity, + label: String, + ) -> Result<()> { + let digest = fresh + .map(segment_digest) + .or(reused) + .context("page has no digest")?; + self.manifest.segments.push(HandoffSegmentRef { + index: u32::try_from(self.manifest.segments.len())?, + offset: self.offset, + bytes, + digest, + codec_identity: Some(codec), + meta_json: Some(label), + }); + self.fresh.push(fresh); + self.offset = self + .offset + .checked_add(bytes) + .context("checkpoint size overflows")?; + Ok(()) + } +} diff --git a/crates/skippy-cache/src/tier/spill_payload.rs b/crates/skippy-cache/src/tier/spill_payload.rs index 620735f2..b8d93d4d 100644 --- a/crates/skippy-cache/src/tier/spill_payload.rs +++ b/crates/skippy-cache/src/tier/spill_payload.rs @@ -71,13 +71,6 @@ impl<'a> SpillPayload<'a> { 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( @@ -133,21 +126,6 @@ fn validate_cachegen( #[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() { @@ -185,7 +163,6 @@ mod tests { 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(_))); diff --git a/crates/skippy-cli/src/analytics.rs b/crates/skippy-cli/src/analytics.rs index e81ccfda..0390c814 100644 --- a/crates/skippy-cli/src/analytics.rs +++ b/crates/skippy-cli/src/analytics.rs @@ -32,6 +32,7 @@ pub fn init(command: &Command) { pub fn family(command: &Command) -> &'static str { match command { Command::Doctor { .. } => "doctor", + Command::KvCache(_) => "kv_cache", Command::GpuBenchmark { .. } => "gpu_benchmark", Command::Prompt(_) => "prompt", Command::Serve(_) => "serve", diff --git a/crates/skippy-cli/src/cli.rs b/crates/skippy-cli/src/cli.rs index cfb11d47..5c30178b 100644 --- a/crates/skippy-cli/src/cli.rs +++ b/crates/skippy-cli/src/cli.rs @@ -62,6 +62,8 @@ pub enum Command { #[arg(long, default_value_t = 120)] timeout_secs: u64, }, + /// Inspect or maintain the local disk KV cache. + KvCache(crate::kv_cache::CacheArgs), /// Prompt a running Skippy OpenAI endpoint interactively. Prompt(PromptArgs), /// Serve OpenAI and Anthropic APIs, or an explicitly selected stage transport. @@ -374,7 +376,7 @@ pub struct ServeOpenAiArgs { pub openai_guardrails: OpenAiGuardrailsCliMode, #[arg( long, - help = "Disk prompt cache: off, auto, or an IEC budget such as 32GiB" + help = "Disk prompt cache: auto (default), off, or an IEC budget such as 32GiB" )] pub kv_cache_disk: Option, #[arg(long, help = "Absolute directory for the disk prompt cache")] diff --git a/crates/skippy-cli/src/conversion.rs b/crates/skippy-cli/src/conversion.rs index 4a063990..405dea2c 100644 --- a/crates/skippy-cli/src/conversion.rs +++ b/crates/skippy-cli/src/conversion.rs @@ -273,6 +273,15 @@ pub fn local_openai_options( args.kv_cache_disk_dir.clone(), args.kv_cache_min_free.as_deref(), )?; + if args.config.is_none() + && disk_cache.is_some() + && !args.settings.values.contains_key("prefix-cache-ram") + && let Some(cache) = config.kv_cache.as_mut() + && cache.mode == skippy_protocol::StageKvCacheMode::LookupRecord + && cache.l2_max_bytes == 0 + { + cache.l2_max_bytes = crate::disk_cache::DEFAULT_HOST_CACHE_BYTES; + } args.settings.validate_cache_dependencies(&config)?; Ok(skippy_api::serving::LocalOpenAiOptions { tuning, diff --git a/crates/skippy-cli/src/disk_cache.rs b/crates/skippy-cli/src/disk_cache.rs index 5f55faa6..fcb30674 100644 --- a/crates/skippy-cli/src/disk_cache.rs +++ b/crates/skippy-cli/src/disk_cache.rs @@ -6,6 +6,8 @@ use anyhow::{Context, Result, bail}; use skippy_api::serving::LocalDiskCacheOptions; use skippy_cache::disk_policy::{DiskCacheBudget, parse_disk_budget}; +pub(crate) const DEFAULT_HOST_CACHE_BYTES: u64 = 256 * 1024 * 1024; + pub(crate) fn from_public_settings( mode: Option<&str>, directory: Option, @@ -26,7 +28,7 @@ pub(crate) fn from_public_settings( .unwrap_or(32 * 1024 * 1024 * 1024); DiskCacheBudget::Fixed(bytes) } - None => DiskCacheBudget::Off, + None => DiskCacheBudget::Auto, }; if budget == DiskCacheBudget::Off { return Ok(None); diff --git a/crates/skippy-cli/src/kv_cache.rs b/crates/skippy-cli/src/kv_cache.rs new file mode 100644 index 00000000..68ca7b99 --- /dev/null +++ b/crates/skippy-cli/src/kv_cache.rs @@ -0,0 +1,262 @@ +//! Standalone disk cache administration. + +mod admin; +mod report; + +use std::{ + ffi::OsString, + io::{self, IsTerminal, Write}, + path::PathBuf, +}; + +use anyhow::{Context, Result, bail, ensure}; +use clap::{Args, Subcommand}; +use serde::{Deserialize, Serialize}; +use skippy_api::serving::LocalDiskCacheOptions; +use skippy_cache::{ + L3CacheManager, + disk_policy::{DiskCacheBudget, acquire_disk_cache, parse_disk_budget}, +}; +use skippy_commands::console; + +pub(crate) use admin::start as start_admin; +use report::{Outcome, Report, Status}; + +#[derive(Args)] +pub(crate) struct CacheArgs { + /// The serving settings file used to configure this cache. + #[arg(long, global = true)] + settings: Option, + /// Disk cache budget (off, auto, or an IEC size). + #[arg(long, global = true)] + kv_cache_disk: Option, + /// Absolute path to the disk cache root. + #[arg(long, global = true)] + kv_cache_disk_dir: Option, + /// Minimum free space to keep on the disk cache filesystem. + #[arg(long, global = true)] + kv_cache_min_free: Option, + #[command(subcommand)] + command: CacheCommand, +} + +#[derive(Subcommand)] +enum CacheCommand { + /// Report disk cache limits, state, activity and model inventory. + Status, + /// Evict inactive entries toward a byte target. + Prune { + /// Target for whole-cache usage, such as 4GiB. Defaults to the cache's low-water mark. + #[arg(long, value_parser = target_bytes)] + target: Option, + #[command(flatten)] + scope: MaintenanceScope, + }, + /// Remove eligible inactive entries. + Clear { + #[command(flatten)] + scope: MaintenanceScope, + }, +} + +#[derive(Args)] +struct MaintenanceScope { + /// Select the exact model identity shown by kv-cache status. + #[arg(long, value_parser = exact_identity)] + model_identity: Option, + /// Confirm removal of inactive entries. + #[arg(long)] + yes: bool, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case", tag = "operation", deny_unknown_fields)] +enum Operation { + Status, + Prune { + target_bytes: Option, + model_identity: Option, + }, + Clear { + model_identity: Option, + }, +} + +pub(crate) async fn run(args: CacheArgs) -> Result<()> { + let settings = resolve_settings(&args)?; + let Some(settings) = settings else { + ensure!( + matches!(args.command, CacheCommand::Status), + "disk KV cache is disabled; use the disk cache settings from skippy serve" + ); + return Report::status(Status::disabled()).present(); + }; + let operation = args.command.confirm()?; + match admin::forward(&settings.directory, &operation).await { + Ok(Some(report)) => return report.present(), + Ok(None) => {} + Err(error) if matches!(operation, Operation::Status) => { + return Report::status(Status::unavailable(&settings, format!("{error:#}"))).present(); + } + Err(error) => return Err(error), + } + tokio::task::spawn_blocking(move || offline(settings, operation)) + .await?? + .present() +} + +fn resolve_settings(args: &CacheArgs) -> Result> { + // Reuse the serving parser so it applies the same settings sources, + // aliases, relative paths and validation without preparing a model. + let mut argv = vec![OsString::from("skippy"), OsString::from("serve")]; + for (flag, value) in [ + ("--settings", args.settings.as_ref().map(|x| x.as_os_str())), + ( + "--kv-cache-disk", + args.kv_cache_disk.as_ref().map(AsRef::as_ref), + ), + ( + "--kv-cache-disk-dir", + args.kv_cache_disk_dir.as_ref().map(|x| x.as_os_str()), + ), + ( + "--kv-cache-min-free", + args.kv_cache_min_free.as_ref().map(AsRef::as_ref), + ), + ] { + if let Some(value) = value { + argv.push(flag.into()); + argv.push(value.into()); + } + } + let crate::cli::Command::Serve(serve) = crate::serve_settings::parse(argv)?.command else { + unreachable!("synthetic settings arguments always select serve"); + }; + crate::disk_cache::from_public_settings( + serve.public.kv_cache_disk.as_deref(), + serve.public.kv_cache_disk_dir, + serve.public.kv_cache_min_free.as_deref(), + ) +} + +impl CacheCommand { + fn confirm(self) -> Result { + let (scope, target) = match self { + Self::Status => return Ok(Operation::Status), + Self::Prune { target, scope } => (scope, Some(target)), + Self::Clear { scope } => (scope, None), + }; + if !scope.yes { + confirm_removal(scope.model_identity.as_deref())?; + } + let model_identity = scope.model_identity; + Ok(match target { + Some(target_bytes) => Operation::Prune { + target_bytes, + model_identity, + }, + None => Operation::Clear { model_identity }, + }) + } +} + +fn confirm_removal(model_identity: Option<&str>) -> Result<()> { + let stdin = io::stdin(); + ensure!( + stdin.is_terminal() && console::mode() == console::OutputMode::Human, + "cache maintenance requires interactive confirmation or --yes" + ); + let mut stderr = io::stderr().lock(); + match model_identity { + Some(identity) => write!( + stderr, + "Remove eligible entries for model {identity:?} from the disk KV cache? [y/N] " + )?, + None => write!( + stderr, + "Remove eligible entries from the disk KV cache? [y/N] " + )?, + } + stderr.flush()?; + let mut answer = String::new(); + stdin.read_line(&mut answer)?; + ensure!( + answer.trim().eq_ignore_ascii_case("yes") || answer.trim().eq_ignore_ascii_case("y"), + "cache maintenance cancelled" + ); + Ok(()) +} + +fn target_bytes(value: &str) -> Result { + match parse_disk_budget(value)? { + DiskCacheBudget::Fixed(bytes) => Ok(bytes), + _ => bail!("prune target must be a positive IEC size, such as 4GiB"), + } +} + +fn exact_identity(value: &str) -> Result { + ensure!(!value.trim().is_empty(), "model identity must be non-empty"); + Ok(value.to_owned()) +} + +fn offline(settings: LocalDiskCacheOptions, operation: Operation) -> Result { + let manager = acquire_disk_cache( + &settings.directory, + settings.budget, + settings.minimum_free_bytes, + ) + .and_then(|manager| manager.context("automatic cache budget is zero")) + .with_context(|| { + format!( + "cannot administer {} offline; check its configuration and permissions or stop the skippy serve process that owns it", + settings.directory.display() + ) + }); + match manager { + Ok(manager) => operation.execute(&manager), + Err(error) if matches!(operation, Operation::Status) => Ok(Report::status( + Status::unavailable(&settings, format!("{error:#}")), + )), + Err(error) => Err(error), + } +} + +impl Operation { + fn execute(&self, manager: &L3CacheManager) -> Result { + let outcome = match self { + Self::Status => return Ok(Report::status(Status::from_manager(manager)?)), + Self::Prune { + target_bytes, + model_identity, + } => { + let target = target_bytes + .or_else(|| manager.limits().low_water_bytes()) + .context("an uncapped cache requires an explicit --target")?; + let freed_bytes = match model_identity { + Some(identity) => manager.prune_model_to(&exact_identity(identity)?, target)?, + None => manager.prune_to(target)?, + }; + let used_bytes = manager.usage()?.used_bytes; + Outcome::Prune { + model_identity: model_identity.clone(), + target_bytes: target, + freed_bytes, + used_bytes, + target_reached: used_bytes <= target, + } + } + Self::Clear { model_identity } => { + let freed_bytes = match model_identity { + Some(identity) => manager.clear_model(&exact_identity(identity)?)?, + None => manager.clear()?, + }; + Outcome::Clear { + model_identity: model_identity.clone(), + freed_bytes, + used_bytes: manager.usage()?.used_bytes, + } + } + }; + Ok(Report::new(outcome)) + } +} diff --git a/crates/skippy-cli/src/kv_cache/admin.rs b/crates/skippy-cli/src/kv_cache/admin.rs new file mode 100644 index 00000000..24405f88 --- /dev/null +++ b/crates/skippy-cli/src/kv_cache/admin.rs @@ -0,0 +1,263 @@ +//! Local administration for the process that owns an L3 store. + +use std::{ + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + net::{Ipv4Addr, SocketAddrV4}, + path::Path, + time::Duration, +}; + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use skippy_cache::{L3CacheManager, fsinfo}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + task::{JoinHandle, JoinSet}, + time::timeout, +}; + +use super::{Operation, Report}; + +#[cfg(test)] +mod tests; + +const ENDPOINT_FILE: &str = ".cache-admin.json"; +const ENDPOINT_VERSION: u32 = 1; +const REQUEST_LIMIT: u32 = 16 * 1024; +const REPLY_LIMIT: u32 = 32 * 1024 * 1024; +const MAX_CONNECTIONS: usize = 8; +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(2); +const REPLY_TIMEOUT: Duration = Duration::from_secs(120); + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Endpoint { + version: u32, + address: SocketAddrV4, + token: [u8; 16], +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Request { + token: [u8; 16], + command: Operation, +} + +#[derive(Deserialize, Serialize)] +enum Reply { + Report(Box), + Error(String), +} + +pub(crate) struct Admin { + task: JoinHandle<()>, + owner: L3CacheManager, +} + +impl Drop for Admin { + fn drop(&mut self) { + self.task.abort(); + // The manager still holds the exclusive root lock. + let _ = fs::remove_file(self.owner.root().join(ENDPOINT_FILE)); + } +} + +pub(crate) async fn start(manager: Option<&L3CacheManager>) -> Result> { + let Some(owner) = manager else { + return Ok(None); + }; + let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) + .await + .context("bind the local disk KV cache administration listener")?; + let std::net::SocketAddr::V4(address) = listener.local_addr()? else { + unreachable!("bound an IPv4 loopback address"); + }; + let token = *uuid::Uuid::new_v4().as_bytes(); + publish( + owner.root(), + &Endpoint { + version: ENDPOINT_VERSION, + address, + token, + }, + )?; + let task = tokio::spawn(accept(listener, owner.clone(), token)); + Ok(Some(Admin { + task, + owner: owner.clone(), + })) +} + +fn publish(root: &Path, endpoint: &Endpoint) -> Result<()> { + let destination = root.join(ENDPOINT_FILE); + fsinfo::refuse_symlink(&destination)?; + let temporary = root.join(format!(".cache-admin-{}.tmp", uuid::Uuid::new_v4())); + let mut open = OpenOptions::new(); + open.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + open.mode(0o600); + } + let result = (|| -> Result<()> { + let mut file = open.open(&temporary)?; + fsinfo::restrict_to_owner(&temporary, 0o600)?; + serde_json::to_writer(&mut file, endpoint)?; + file.flush()?; + drop(file); + fsinfo::replace_file(&temporary, &destination) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result.context("publish the local disk KV cache administration endpoint") +} + +fn discover(root: &Path) -> Result> { + fsinfo::refuse_symlink(root)?; + if !root.try_exists()? { + return Ok(None); + } + // Apply the cache's directory traversal rules before reading an endpoint. + fsinfo::create_dir_all_without_links(root)?; + let path = root.join(ENDPOINT_FILE); + fsinfo::refuse_symlink(&path)?; + let file = match File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + require_private_file(&file)?; + let mut bytes = Vec::new(); + file.take(u64::from(REQUEST_LIMIT) + 1) + .read_to_end(&mut bytes)?; + ensure!( + bytes.len() <= REQUEST_LIMIT as usize, + "cache owner endpoint metadata is too large" + ); + let endpoint: Endpoint = serde_json::from_slice(&bytes)?; + ensure!( + endpoint.version == ENDPOINT_VERSION, + "disk KV cache owner uses an incompatible administration protocol" + ); + ensure!( + endpoint.address.ip().is_loopback() && endpoint.address.port() != 0, + "cache owner endpoint is not a loopback listener" + ); + Ok(Some(endpoint)) +} + +fn require_private_file(file: &File) -> Result<()> { + let metadata = file.metadata()?; + ensure!( + metadata.is_file(), + "cache owner endpoint must be a regular file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + metadata.permissions().mode() & 0o077 == 0, + "cache owner endpoint permissions are not private" + ); + } + Ok(()) +} + +pub(super) async fn forward(root: &Path, command: &Operation) -> Result> { + let Some(endpoint) = discover(root).context("locate the disk KV cache owner")? else { + return Ok(None); + }; + let mut stream = match timeout(HANDSHAKE_TIMEOUT, TcpStream::connect(endpoint.address)).await? { + Ok(stream) => stream, + // An owner interrupted before cleanup can leave a stale endpoint. + // Offline execution still has to acquire the store's exclusive lock. + Err(error) if error.kind() == io::ErrorKind::ConnectionRefused => return Ok(None), + Err(error) => return Err(error).context("connect to the disk KV cache owner"), + }; + let request = Request { + token: endpoint.token, + command: command.clone(), + }; + timeout( + HANDSHAKE_TIMEOUT, + write_frame(&mut stream, &request, REQUEST_LIMIT), + ) + .await??; + let response: Reply = timeout(REPLY_TIMEOUT, read_frame(&mut stream, REPLY_LIMIT)) + .await + .context( + "cache owner response timed out; check cache status before retrying maintenance", + )??; + match response { + Reply::Report(report) => { + ensure!( + report.schema_version == Report::VERSION, + "incompatible cache report" + ); + Ok(Some(*report)) + } + Reply::Error(error) => anyhow::bail!("{error}"), + } +} + +async fn accept(listener: TcpListener, owner: L3CacheManager, token: [u8; 16]) { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + connection = listener.accept(), if connections.len() < MAX_CONNECTIONS => { + let Ok((stream, peer)) = connection else { return }; + if peer.ip().is_loopback() { + let manager = owner.clone(); + connections.spawn(async move { + let _ = handle(stream, manager, token).await; + }); + } + } + _ = connections.join_next(), if !connections.is_empty() => {} + } + } +} + +async fn handle(mut stream: TcpStream, manager: L3CacheManager, token: [u8; 16]) -> Result<()> { + let request: Request = + timeout(HANDSHAKE_TIMEOUT, read_frame(&mut stream, REQUEST_LIMIT)).await??; + ensure!(request.token == token, "cache owner authorization failed"); + let result = tokio::task::spawn_blocking(move || request.command.execute(&manager)).await?; + let reply = match result { + Ok(report) => Reply::Report(Box::new(report)), + Err(error) => Reply::Error(format!("{error:#}")), + }; + timeout( + HANDSHAKE_TIMEOUT, + write_frame(&mut stream, &reply, REPLY_LIMIT), + ) + .await??; + Ok(()) +} + +async fn read_frame(stream: &mut TcpStream, limit: u32) -> Result { + let size = stream.read_u32().await?; + ensure!( + size <= limit, + "cache administration message exceeds the size limit" + ); + let mut bytes = vec![0; size as usize]; + stream.read_exact(&mut bytes).await?; + Ok(serde_json::from_slice(&bytes)?) +} + +async fn write_frame(stream: &mut TcpStream, value: &T, limit: u32) -> Result<()> { + let bytes = serde_json::to_vec(value)?; + let size = u32::try_from(bytes.len())?; + ensure!( + size <= limit, + "cache administration message exceeds the size limit" + ); + stream.write_u32(size).await?; + stream.write_all(&bytes).await?; + Ok(()) +} diff --git a/crates/skippy-cli/src/kv_cache/admin/tests.rs b/crates/skippy-cli/src/kv_cache/admin/tests.rs new file mode 100644 index 00000000..d34fdfae --- /dev/null +++ b/crates/skippy-cli/src/kv_cache/admin/tests.rs @@ -0,0 +1,175 @@ +use super::*; +use skippy_cache::{ExactStatePayload, StoreLimits}; + +const LIMIT: u64 = 1024 * 1024; + +fn owner(temporary: &tempfile::TempDir) -> L3CacheManager { + L3CacheManager::acquire(temporary.path(), StoreLimits::new(LIMIT, 0)).unwrap() +} + +#[tokio::test] +async fn authorized_control_uses_live_counters_and_preserves_pinned_state() { + let directory = tempfile::tempdir().unwrap(); + let manager = owner(&directory); + let admin = start(Some(&manager)).await.unwrap().unwrap(); + let tier = manager.tier_for_model("model-a".into(), "state".into(), 1024); + let key = tier + .spill( + "namespace", + &[10, 20, 30], + &ExactStatePayload::full_state(vec![42; 8192]), + None, + None, + ) + .unwrap(); + let pin = tier.store().pin(&key); + let status = forward(directory.path(), &Operation::Status) + .await + .unwrap() + .unwrap(); + let status = serde_json::to_value(status).unwrap(); + assert_eq!(status["activity"]["writes"], 1); + assert_eq!(status["models"][0]["model_identity"], "model-a"); + assert_eq!(status["budget_bytes"], LIMIT); + + let prune = forward( + directory.path(), + &Operation::Prune { + model_identity: Some("model-a".into()), + target_bytes: Some(1), + }, + ) + .await + .unwrap() + .unwrap(); + let prune = serde_json::to_value(prune).unwrap(); + assert_eq!(prune["target_reached"], false); + assert_eq!(prune["freed_bytes"], 0); + let clear = Operation::Clear { + model_identity: None, + }; + let result = forward(directory.path(), &clear).await.unwrap().unwrap(); + assert_eq!(serde_json::to_value(result).unwrap()["freed_bytes"], 0); + assert!(tier.store().load_manifest(&key).is_ok()); + + drop(pin); + let result = forward(directory.path(), &clear).await.unwrap().unwrap(); + assert!( + serde_json::to_value(result).unwrap()["freed_bytes"] + .as_u64() + .unwrap() + > 0 + ); + assert!(manager.inventory().unwrap().is_empty()); + assert!(manager.root().join(ENDPOINT_FILE).exists()); + drop(admin); + assert!(!manager.root().join(ENDPOINT_FILE).exists()); +} + +#[tokio::test] +async fn unauthorized_control_cannot_clear_the_live_cache() { + let directory = tempfile::tempdir().unwrap(); + let manager = owner(&directory); + let _admin = start(Some(&manager)).await.unwrap().unwrap(); + let tier = manager.tier("state".into(), 1024); + tier.spill( + "namespace", + &[1, 2, 3], + &ExactStatePayload::full_state(b"test".to_vec()), + None, + None, + ) + .unwrap(); + let endpoint = discover(directory.path()).unwrap().unwrap(); + let mut token = endpoint.token; + token[0] ^= 1; + let mut stream = TcpStream::connect(endpoint.address).await.unwrap(); + write_frame( + &mut stream, + &Request { + token, + command: Operation::Clear { + model_identity: None, + }, + }, + REQUEST_LIMIT, + ) + .await + .unwrap(); + assert!(read_frame::(&mut stream, REPLY_LIMIT).await.is_err()); + assert_eq!(manager.inventory().unwrap().len(), 1); +} + +#[tokio::test] +async fn stale_owner_endpoint_allows_a_locked_offline_reopen() { + let directory = tempfile::tempdir().unwrap(); + let manager = owner(&directory); + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let std::net::SocketAddr::V4(address) = listener.local_addr().unwrap() else { + unreachable!() + }; + publish( + manager.root(), + &Endpoint { + version: ENDPOINT_VERSION, + address, + token: [0; 16], + }, + ) + .unwrap(); + drop(listener); + drop(manager); + assert!( + forward(directory.path(), &Operation::Status) + .await + .unwrap() + .is_none() + ); + assert_eq!(owner(&directory).limits().budget_bytes, LIMIT); +} + +#[tokio::test] +async fn degraded_owner_exposes_the_storage_error_and_uncapped_prune_requires_a_target() { + let directory = tempfile::tempdir().unwrap(); + let manager = L3CacheManager::acquire(directory.path(), StoreLimits::new(0, 0)).unwrap(); + let _admin = start(Some(&manager)).await.unwrap().unwrap(); + let tier = manager.tier("state".into(), 1024); + let hashed = skippy_cache::l3_namespace_key("namespace"); + let blocker = manager + .root() + .join("prefixes") + .join(hashed.trim_start_matches("blake3:")); + fs::write(blocker, b"blocks index publication").unwrap(); + assert!( + tier.spill( + "namespace", + &[1, 2, 3], + &ExactStatePayload::full_state(b"test".to_vec()), + None, + None, + ) + .is_err() + ); + let status = forward(directory.path(), &Operation::Status) + .await + .unwrap() + .unwrap(); + let status = serde_json::to_value(status).unwrap(); + assert_eq!(status["state"], "degraded"); + assert_eq!(status["reason"], "storage_error"); + assert!(status["activity"]["last_error"].is_string()); + let error = forward( + directory.path(), + &Operation::Prune { + target_bytes: None, + model_identity: None, + }, + ) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("uncapped cache requires an explicit --target") + ); +} diff --git a/crates/skippy-cli/src/kv_cache/report.rs b/crates/skippy-cli/src/kv_cache/report.rs new file mode 100644 index 00000000..73b1cb37 --- /dev/null +++ b/crates/skippy-cli/src/kv_cache/report.rs @@ -0,0 +1,256 @@ +use std::{ + collections::BTreeMap, + io::{self, Write}, +}; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use skippy_api::serving::LocalDiskCacheOptions; +use skippy_cache::{ + L3ActivitySnapshot, L3CacheManager, L3EffectiveState, L3StateReason, StoreReconciliation, + StoreUsage, disk_policy::DiskCacheBudget, +}; +use skippy_commands::console; + +#[derive(Debug, Deserialize, Serialize)] +pub(super) struct Report { + pub(super) schema_version: u32, + #[serde(flatten)] + outcome: Outcome, +} + +impl Report { + pub(super) const VERSION: u32 = 1; + + pub(super) fn new(outcome: Outcome) -> Self { + Self { + schema_version: Self::VERSION, + outcome, + } + } + + pub(super) fn status(status: Status) -> Self { + Self::new(Outcome::Status(Box::new(status))) + } + + pub(super) fn present(&self) -> Result<()> { + console::present(self, |output| match &self.outcome { + Outcome::Status(status) => status.render(output), + Outcome::Prune { + freed_bytes, + used_bytes, + target_bytes, + target_reached, + .. + } => { + writeln!( + output, + "Freed {freed_bytes} bytes from the disk KV cache. {used_bytes} bytes remain." + )?; + if !target_reached { + writeln!( + output, + "The cache could not reach the {target_bytes}-byte target with the eligible entries." + )?; + } + Ok(()) + } + Outcome::Clear { + freed_bytes, + used_bytes, + .. + } => writeln!( + output, + "Freed {freed_bytes} bytes from the disk KV cache. {used_bytes} bytes remain." + ), + }) + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case", tag = "operation")] +pub(super) enum Outcome { + Status(Box), + Prune { + model_identity: Option, + target_bytes: u64, + freed_bytes: u64, + used_bytes: u64, + target_reached: bool, + }, + Clear { + model_identity: Option, + freed_bytes: u64, + used_bytes: u64, + }, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +enum State { + #[default] + Disabled, + Unavailable, + Active, + ReadOnlyLowSpace, + Degraded, +} + +impl State { + fn label(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Unavailable => "unavailable", + Self::Active => "active", + Self::ReadOnlyLowSpace => "read-only due to low disk space", + Self::Degraded => "degraded", + } + } +} + +#[derive(Debug, Default, Deserialize, Serialize)] +pub(super) struct Status { + enabled: bool, + available: bool, + directory: Option, + state: State, + reason: Option, + detail: Option, + budget_bytes: Option, + minimum_free_bytes: Option, + low_water_bytes: Option, + usage: Option, + reconciliation: Option, + activity: Option, + models: Vec, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +struct ModelInventory { + model_identity: String, + manifests: u64, + logical_bytes: u64, +} + +impl Status { + pub(super) fn disabled() -> Self { + Self::default() + } + + pub(super) fn unavailable(settings: &LocalDiskCacheOptions, detail: String) -> Self { + Self { + enabled: true, + directory: Some(settings.directory.display().to_string()), + state: State::Unavailable, + detail: Some(detail), + budget_bytes: match settings.budget { + DiskCacheBudget::Fixed(bytes) => Some(bytes), + _ => None, + }, + minimum_free_bytes: Some(settings.minimum_free_bytes), + ..Self::default() + } + } + + pub(super) fn from_manager(manager: &L3CacheManager) -> Result { + let usage = manager.usage()?; + let limits = manager.limits(); + let effective = manager.effective_status(); + let (state, reason) = match effective.state { + L3EffectiveState::Degraded => (State::Degraded, effective.reason), + _ if usage.filesystem_available_bytes <= limits.minimum_free_bytes => ( + State::ReadOnlyLowSpace, + Some(L3StateReason::ReadOnlyLowSpace), + ), + L3EffectiveState::ReadOnlyLowSpace => (State::ReadOnlyLowSpace, effective.reason), + L3EffectiveState::Active => (State::Active, None), + }; + let mut models = BTreeMap::::new(); + for entry in manager.inventory()? { + let model = models.entry(entry.model_identity).or_default(); + model.logical_bytes = model.logical_bytes.saturating_add(entry.total_bytes); + model.manifests += 1; + } + Ok(Self { + enabled: true, + available: true, + directory: Some(manager.root().display().to_string()), + state, + reason, + detail: None, + budget_bytes: Some(limits.budget_bytes), + minimum_free_bytes: Some(limits.minimum_free_bytes), + low_water_bytes: limits.low_water_bytes(), + usage: Some(usage), + reconciliation: Some(manager.reconciliation()), + activity: Some(manager.activity()?), + models: models + .into_iter() + .map(|(model_identity, model)| ModelInventory { + model_identity, + ..model + }) + .collect(), + }) + } + + fn render(&self, output: &mut dyn Write) -> io::Result<()> { + writeln!(output, "Disk KV cache is {}.", self.state.label())?; + if let Some(directory) = &self.directory { + writeln!(output, "Directory {directory}")?; + } + if let Some(detail) = &self.detail { + writeln!(output, "{detail}")?; + } + if let Some(usage) = self.usage { + writeln!( + output, + "Usage {} bytes, {} manifests, {} unique segments", + usage.used_bytes, usage.manifests, usage.unique_segments + )?; + writeln!( + output, + "Limits {} bytes cache budget, {} bytes minimum filesystem free space", + usage.budget_bytes, usage.minimum_free_bytes + )?; + writeln!( + output, + "Available {} bytes on the filesystem", + usage.filesystem_available_bytes + )?; + } + if let Some(activity) = &self.activity { + writeln!( + output, + "Activity {} hits, {} misses, {} fills, {} writes, {} evictions, {} corrupt objects", + activity.hits, + activity.misses, + activity.fills, + activity.writes, + activity.evictions, + activity.corrupt_entries + )?; + if let Some(error) = &activity.last_error { + writeln!(output, "Last error {error}")?; + } + } + if let Some(reconciliation) = self.reconciliation { + writeln!( + output, + "Recovery {} temporary files removed, {} manifests quarantined, {} prefix links removed, {} orphan bytes removed", + reconciliation.removed_temporary_files, + reconciliation.quarantined_manifests, + reconciliation.removed_prefix_links, + reconciliation.removed_orphan_bytes + )?; + } + for model in &self.models { + writeln!( + output, + "Model {:?} has {} manifests and {} logical bytes.", + model.model_identity, model.manifests, model.logical_bytes + )?; + } + Ok(()) + } +} diff --git a/crates/skippy-cli/src/main.rs b/crates/skippy-cli/src/main.rs index 8a50d6d5..2cf1e17f 100644 --- a/crates/skippy-cli/src/main.rs +++ b/crates/skippy-cli/src/main.rs @@ -4,6 +4,7 @@ mod conversion; mod disk_cache; mod draft; mod gpu_benchmark; +mod kv_cache; mod local_model; mod local_resource_planning; #[cfg(unix)] @@ -154,6 +155,7 @@ async fn run_command(cli: Cli, native_logs: Arc { gpu_benchmark::run(&native_options, timeout_secs).await } + Command::KvCache(args) => kv_cache::run(args).await, Command::Prompt(args) => { tokio::task::spawn_blocking(move || { skippy_commands::prompt::run(skippy_commands::prompt::PromptCommand { diff --git a/crates/skippy-cli/src/serve.rs b/crates/skippy-cli/src/serve.rs index ae4fd058..777a662b 100644 --- a/crates/skippy-cli/src/serve.rs +++ b/crates/skippy-cli/src/serve.rs @@ -129,12 +129,13 @@ async fn serve_public(args: ServeCommandArgs) -> Result<()> { tokio::select! { _ = shutdown => {}, _ = stopped => {} } }); let server = async move { - skippy_api::serving::serve_local_openai_with_default_draft( - options, - draft.as_ref(), - shutdown, - ) - .await + let (bind_addr, request) = options.into_request()?; + let _admin = crate::kv_cache::start_admin(request.l3_manager.as_ref()).await?; + let loaded = match draft.as_ref() { + Some(draft) => request.load_with_default_draft(draft), + None => request.load(), + }?; + loaded.serve_http_with_shutdown(bind_addr, shutdown).await }; serve_with_readiness( ReadinessServer { @@ -219,6 +220,7 @@ async fn serve_binary_stage(mut args: ServeCommandArgs) -> Result<()> { )); } options.l3_manager = disk_cache.and_then(skippy_api::serving::LocalDiskCacheOptions::acquire); + let _admin = crate::kv_cache::start_admin(options.l3_manager.as_ref()).await?; let Some(openai) = options.openai.as_ref() else { if args.prompt { bail!("--prompt requires stage 0 to expose the public inference API"); diff --git a/crates/skippy-cli/src/serve_settings/catalog.rs b/crates/skippy-cli/src/serve_settings/catalog.rs index 5e479622..b8c90ce5 100644 --- a/crates/skippy-cli/src/serve_settings/catalog.rs +++ b/crates/skippy-cli/src/serve_settings/catalog.rs @@ -243,7 +243,14 @@ pub const OPTIONS: &[OptionSpec] = &[ "cache", "kv_cache.l2_max_bytes", Kind::Bytes, - "Resident checkpoint RAM budget: off for default or a fixed IEC size; independent of disk", + "L2 host-RAM mirror: off or a fixed IEC size", + ), + option( + "prefix-cache-checkpoint-ram", + "cache", + "kv_cache.l1_checkpoint_max_bytes", + Kind::Bytes, + "L1 recurrent-checkpoint RAM: auto (default 1GiB) or a positive fixed IEC size", ), option( "prefix-cache-max-entries", diff --git a/crates/skippy-cli/src/serve_settings/resolution.rs b/crates/skippy-cli/src/serve_settings/resolution.rs index f2cde875..201ae585 100644 --- a/crates/skippy-cli/src/serve_settings/resolution.rs +++ b/crates/skippy-cli/src/serve_settings/resolution.rs @@ -63,7 +63,8 @@ impl ServeSettings { pub fn validate_cache_dependencies(&self, config: &StageConfig) -> Result<()> { if let Some(cache) = &config.kv_cache { anyhow::ensure!( - cache.mode != StageKvCacheMode::Disabled || cache.l2_max_bytes == 0, + cache.mode != StageKvCacheMode::Disabled + || (cache.l2_max_bytes == 0 && cache.l1_checkpoint_max_bytes.is_none()), "RAM caching requires enabled prefix caching" ); } @@ -111,7 +112,13 @@ impl ServeSettings { spec.name != "prefix-cache-budget" || value.as_str() != Some("off"), "use --prefix-cache off to disable caching" ); - bytes(value)? + let budget = bytes(value)?; + anyhow::ensure!( + spec.name != "prefix-cache-checkpoint-ram" + || budget.as_u64().is_some_and(|bytes| bytes > 0), + "prefix-cache-checkpoint-ram requires auto or a positive fixed IEC budget" + ); + budget } else if spec.name == "prefix-cache-retention-tokens" { retention(value)? } else if spec.name == "prefix-cache" { diff --git a/crates/skippy-cli/src/serve_settings/tests.rs b/crates/skippy-cli/src/serve_settings/tests.rs index 1a29acd3..a770ab86 100644 --- a/crates/skippy-cli/src/serve_settings/tests.rs +++ b/crates/skippy-cli/src/serve_settings/tests.rs @@ -865,7 +865,7 @@ fn checkpoint_ram_budget_does_not_require_disk() { "missing.gguf", "--prefix-cache", "on", - "--prefix-cache-ram", + "--prefix-cache-checkpoint-ram", "1GiB", ]) .unwrap() @@ -880,9 +880,10 @@ fn checkpoint_ram_budget_does_not_require_disk() { .validate_cache_dependencies(&stage) .unwrap(); assert_eq!( - stage.kv_cache.as_ref().unwrap().l2_max_bytes, - 1024 * 1024 * 1024 + stage.kv_cache.as_ref().unwrap().l1_checkpoint_max_bytes, + std::num::NonZeroU64::new(1024 * 1024 * 1024) ); + assert_eq!(stage.kv_cache.as_ref().unwrap().l2_max_bytes, 0); let tuning = args .public .settings diff --git a/crates/skippy-cli/tests/kv_cache.rs b/crates/skippy-cli/tests/kv_cache.rs new file mode 100644 index 00000000..b78d02c6 --- /dev/null +++ b/crates/skippy-cli/tests/kv_cache.rs @@ -0,0 +1,368 @@ +//! Exercise the public cache operator commands across real process boundaries. + +use std::{ + fs, + path::Path, + process::{Child, Command, Output, Stdio}, + thread, + time::{Duration, Instant}, +}; + +use serde_json::{Value, json}; +use skippy_cache::{ExactStatePayload, L3CacheManager, StoreLimits}; + +const BUDGET: u64 = 32 * 1024 * 1024; +const RESERVE: u64 = 1024 * 1024 * 1024; + +fn command(temporary: &Path, root: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_skippy")); + command + .env("SKIPPY_DATA_DIR", temporary.join("downloads")) + .env("SKIPPY_SERVE_KV_CACHE_DISK", "32MiB") + .env("SKIPPY_SERVE_KV_CACHE_MIN_FREE", "1GiB") + .env("SKIPPY_SERVE_KV_CACHE_DISK_DIR", root) + .stdin(Stdio::null()); + command +} + +fn run(root: &Path, args: &[&str]) -> Output { + command(root.parent().unwrap(), root) + .args(["--output", "json", "kv-cache"]) + .args(args) + .output() + .unwrap() +} + +fn report(output: Output) -> Value { + assert!(output.status.success(), "{:?}", output); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn seed(manager: &L3CacheManager, model: &str, marker: u8) { + let tier = manager.tier_for_model(model.to_owned(), model.to_owned(), 64 * 1024); + tier.spill( + model, + &[1, 2, 3], + &ExactStatePayload::full_state(vec![marker; 32 * 1024]), + None, + None, + ) + .unwrap(); +} + +#[test] +fn disabled_status_has_a_stable_document_and_output_modes() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let expected = json!({ + "schema_version": 1, "operation": "status", "enabled": false, "available": false, + "directory": null, "state": "disabled", "reason": null, "detail": null, + "budget_bytes": null, "minimum_free_bytes": null, "low_water_bytes": null, + "usage": null, "reconciliation": null, "activity": null, "models": [] + }); + assert_eq!( + report(run(&root, &["status", "--kv-cache-disk", "off"])), + expected + ); + let output = command(temporary.path(), &root) + .args([ + "kv-cache", + "status", + "--kv-cache-disk", + "off", + "--output", + "jsonl", + ]) + .output() + .unwrap(); + assert!(output.status.success()); + let event = String::from_utf8(output.stdout) + .unwrap() + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .find(|event| event["type"] == "result") + .unwrap(); + assert_eq!(event["data"], expected); + let output = command(temporary.path(), &root) + .args([ + "--output", + "human", + "kv-cache", + "--kv-cache-disk", + "off", + "status", + ]) + .output() + .unwrap(); + assert!(output.status.success()); + assert!( + String::from_utf8(output.stdout) + .unwrap() + .contains("Disk KV cache is disabled") + ); + assert!(!root.exists()); +} + +#[test] +fn disk_cache_defaults_to_a_bounded_auto_budget() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let output = command(temporary.path(), &root) + .env_remove("SKIPPY_SERVE_KV_CACHE_DISK") + .env_remove("SKIPPY_KV_CACHE_DISK") + .env_remove("SKIPPY_L3_DIR") + .args(["--output", "json", "kv-cache", "status"]) + .output() + .unwrap(); + let status = report(output); + assert_eq!(status["enabled"], true); + assert_eq!(status["minimum_free_bytes"], RESERVE); + if let Some(budget) = status["budget_bytes"].as_u64() { + assert!((1..=64 * 1024 * 1024 * 1024).contains(&budget)); + } else { + assert_eq!(status["available"], false); + assert!( + status["detail"] + .as_str() + .unwrap() + .contains("automatic cache budget is zero") + ); + } +} + +#[test] +fn serving_settings_environment_and_cli_share_precedence() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("environment-cache"); + let settings = temporary.path().join("serve.toml"); + fs::write( + &settings, + "[cache]\nkv_cache_disk = '8MiB'\nkv_cache_disk_dir = 'file-cache'\nkv_cache_min_free = '1GiB'\n", + ) + .unwrap(); + let mut cli = command(temporary.path(), &root); + cli.args(["--output", "json", "kv-cache", "--settings"]) + .arg(&settings); + let mut file_only = command(temporary.path(), &root); + let file_report = report( + file_only + .env_remove("SKIPPY_SERVE_KV_CACHE_DISK") + .env_remove("SKIPPY_SERVE_KV_CACHE_DISK_DIR") + .args(["--output", "json", "kv-cache", "--settings"]) + .arg(&settings) + .arg("status") + .output() + .unwrap(), + ); + assert_eq!(file_report["budget_bytes"], 8 * 1024 * 1024); + assert!(temporary.path().join("file-cache/.owner.lock").is_file()); + let report = report( + cli.args(["status", "--kv-cache-disk", "16MiB"]) + .output() + .unwrap(), + ); + assert_eq!(report["budget_bytes"], 16 * 1024 * 1024); + assert_eq!(report["minimum_free_bytes"], RESERVE); + assert_eq!( + report["directory"], + root.canonicalize().unwrap().display().to_string() + ); +} + +#[test] +fn invalid_filters_sizes_and_unconfirmed_mutations_do_not_open_the_store() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + for (args, message) in [ + ( + &["clear", "--model-identity", " "][..], + "model identity must be non-empty", + ), + (&["prune", "--target", "32GB"], "IEC suffix"), + ( + &["prune", "--target", "auto"], + "target must be a positive IEC size", + ), + (&["prune", "--target", "0GiB"], "positive whole number"), + (&["clear"], "interactive confirmation or --yes"), + ( + &["prune", "--target", "1KiB"], + "interactive confirmation or --yes", + ), + ( + &["clear", "--yes", "--kv-cache-disk", "off"], + "disk KV cache is disabled", + ), + ] { + let output = run(&root, args); + assert!(!output.status.success(), "{args:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains(message), + "{output:?}" + ); + } + assert!(!root.exists()); +} + +#[test] +fn offline_maintenance_respects_model_identity_and_whole_cache_targets() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let owner = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + for (model, marker) in [("model-b", 1), ("model-a-other", 2), ("model-a", 3)] { + seed(&owner, model, marker); + } + drop(owner); + + let status = report(run(&root, &["status"])); + assert_eq!(status["state"], "active"); + assert_eq!(status["usage"]["manifests"], 3); + assert_eq!(status["models"][0]["model_identity"], "model-a"); + assert_eq!(status["models"][1]["model_identity"], "model-a-other"); + assert_eq!(status["models"][2]["model_identity"], "model-b"); + let default_prune = report(run(&root, &["prune", "--yes"])); + assert_eq!(default_prune["target_bytes"], status["low_water_bytes"]); + assert_eq!(default_prune["freed_bytes"], 0); + + let scoped = report(run( + &root, + &[ + "prune", + "--target", + "1KiB", + "--model-identity", + "model-a", + "--yes", + ], + )); + assert!(scoped["freed_bytes"].as_u64().unwrap() > 0); + assert_eq!(scoped["target_reached"], false); + let status = report(run(&root, &["status"])); + assert_eq!(status["usage"]["manifests"], 2); + assert_eq!(status["models"][0]["model_identity"], "model-a-other"); + + let scoped = report(run( + &root, + &["clear", "--model-identity", "model-a-other", "--yes"], + )); + assert!(scoped["freed_bytes"].as_u64().unwrap() > 0); + let prune = report(run(&root, &["prune", "--target", "1KiB", "--yes"])); + assert!(prune["freed_bytes"].as_u64().unwrap() > 0); + assert_eq!(prune["target_reached"], true); + let owner = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + seed(&owner, "model-b", 4); + drop(owner); + let clear = report(run(&root, &["clear", "--yes"])); + assert!(clear["freed_bytes"].as_u64().unwrap() > 0); + assert_eq!(report(run(&root, &["status"]))["models"], json!([])); +} + +#[test] +fn independent_cli_refuses_to_mutate_a_store_with_an_unreachable_owner() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let owner = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + seed(&owner, "model-a", 1); + let status = report(run(&root, &["status"])); + assert_eq!(status["enabled"], true); + assert_eq!(status["available"], false); + assert_eq!(status["state"], "unavailable"); + assert!(status["detail"].as_str().unwrap().contains("already owned")); + let auto = report(run(&root, &["status", "--kv-cache-disk", "auto"])); + assert_eq!(auto["state"], "unavailable"); + assert!(auto["detail"].as_str().unwrap().contains("already owned")); + let output = run(&root, &["clear", "--yes"]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("stop the skippy serve process")); + assert_eq!(owner.inventory().unwrap().len(), 1); +} + +#[test] +fn offline_status_reports_low_space_and_startup_reconciliation() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let owner = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + drop(owner); + fs::write(root.join("segments/.tmp-dead"), b"interrupted").unwrap(); + let report = report(run(&root, &["status", "--kv-cache-min-free", "1024TiB"])); + assert_eq!(report["state"], "read_only_low_space"); + assert_eq!(report["available"], true); + assert_eq!(report["reconciliation"]["removed_temporary_files"], 1); +} + +struct CacheOwner(Child); + +impl Drop for CacheOwner { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[test] +fn replacement_reconciles_a_killed_owner_and_reloads_its_committed_state() { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path().join("kv"); + let mut owner = CacheOwner( + Command::new(std::env::current_exe().unwrap()) + .args(["--ignored", "--exact", "hold_crash_fixture"]) + .env("SKIPPY_TEST_L3_OWNER_ROOT", &root) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .unwrap(), + ); + let ready = temporary.path().join("owner-ready"); + let deadline = Instant::now() + Duration::from_secs(10); + while !ready.exists() { + assert!( + owner.0.try_wait().unwrap().is_none(), + "cache owner exited before readiness" + ); + assert!( + Instant::now() < deadline, + "cache owner did not report readiness" + ); + thread::sleep(Duration::from_millis(10)); + } + + let blocked = report(run(&root, &["status", "--kv-cache-disk", "auto"])); + assert_eq!(blocked["state"], "unavailable"); + assert!( + blocked["detail"] + .as_str() + .unwrap() + .contains("already owned") + ); + assert!(root.join("segments/.tmp-abandoned").exists()); + owner.0.kill().unwrap(); + assert!(!owner.0.wait().unwrap().success()); + + let recovered = report(run(&root, &["status"])); + assert_eq!(recovered["reconciliation"]["removed_temporary_files"], 1); + assert_eq!(recovered["usage"]["manifests"], 1); + assert!(!root.join("segments/.tmp-abandoned").exists()); + let replacement = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + let tier = replacement.tier_for_model("model-a".into(), "model-a".into(), 64 * 1024); + let fill = tier + .fill_longest("model-a", &[1, 2, 3], 8) + .unwrap() + .unwrap(); + assert_eq!( + fill.payload.full_state_bytes_timed().unwrap().0.as_ref(), + &[42; 32 * 1024] + ); +} + +#[test] +#[ignore = "spawned explicitly by the cache owner crash-recovery test"] +fn hold_crash_fixture() { + let root = std::path::PathBuf::from(std::env::var_os("SKIPPY_TEST_L3_OWNER_ROOT").unwrap()); + let owner = L3CacheManager::acquire(&root, StoreLimits::new(BUDGET, RESERVE)).unwrap(); + seed(&owner, "model-a", 42); + fs::write(root.join("segments/.tmp-abandoned"), b"uncommitted state").unwrap(); + fs::write(root.parent().unwrap().join("owner-ready"), []).unwrap(); + let mut line = String::new(); + std::io::stdin().read_line(&mut line).unwrap(); + drop(owner); +} diff --git a/crates/skippy-ffi/README.md b/crates/skippy-ffi/README.md index 77c4352c..5fe47273 100644 --- a/crates/skippy-ffi/README.md +++ b/crates/skippy-ffi/README.md @@ -105,17 +105,18 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.88`. The patch header in +The staged ABI is versioned as `0.1.95`. The patch header in `llama_cpp/patches/` and the Rust constants in `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. -ABI `0.1.88` includes llama.cpp b12780's enlarged `llama_model_quantize_params`, -which crosses the FFI boundary both by value and by pointer. The exact-version -loader gate rejects `0.1.87` runtimes before resolving or calling these APIs. -The version covers consumed upstream C layouts as well as Skippy's own exports; -changes to either require a distinct ABI identity. Rebuild the native runtime -and callers together from the matching patch recipe. +ABI `0.1.95` adds borrowed-chunk KV import, resident sliding-window KV component +export, and byte-range recurrent state export. Existing on-disk checkpoint +layouts and whole-state export entry points retain their contracts. + +ABI `0.1.94` combines the b12780 upstream C layouts with the shared target verification API, device row entry points, and their request descriptors. Rebuild the native runtime and callers from the matching source recipe. + +ABI `0.1.88` includes b12780’s enlarged `llama_model_quantize_params`, which crosses the FFI boundary by value and by pointer. ABI `0.1.87` removes the callback-backed checkpoint loader. The staged model loaders accept GGUF files and GGUF package parts. diff --git a/crates/skippy-ffi/bindgen/generator.rs b/crates/skippy-ffi/bindgen/generator.rs index cf3ab699..da601d64 100644 --- a/crates/skippy-ffi/bindgen/generator.rs +++ b/crates/skippy-ffi/bindgen/generator.rs @@ -240,6 +240,12 @@ impl BindingGenerator { llama_memory_seq_rm|llama_get_logits_ith|llama_n_ctx|llama_n_batch|\ llama_n_ubatch|llama_model_n_embd|llama_model_n_layer|\ llama_model_rope_type|llama_set_causal_attn|\ + llama_sampler_chain_default_params|llama_sampler_chain_init|\ + llama_sampler_chain_add|llama_sampler_init_greedy|llama_sampler_free|\ + llama_set_sampler|llama_get_sampled_token_ith|\ + llama_batch_ext_init|llama_batch_ext_free|llama_batch_ext_clear|\ + llama_batch_ext_set_pos|llama_batch_ext_set_output_logits|\ + llama_process|llama_synchronize|\ ggml_backend_dev_by_name)$", ) .allowlist_type( diff --git a/crates/skippy-ffi/src/bindings/llama.rs b/crates/skippy-ffi/src/bindings/llama.rs index e26d78f8..c849bd37 100644 --- a/crates/skippy-ffi/src/bindings/llama.rs +++ b/crates/skippy-ffi/src/bindings/llama.rs @@ -379,6 +379,12 @@ pub enum llama_model_kv_override_type { Bool = 2, Str = 3, } +#[repr(u32)] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum llama_process_type { + Encode = 0, + Decode = 1, +} #[repr(C)] #[derive(Copy, Clone)] pub struct llama_model_kv_override { @@ -516,12 +522,20 @@ pub struct llama_logit_bias { pub token: llama_token, pub bias: f32, } +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct llama_sampler_chain_params { + pub no_perf: bool, +} unsafe extern "C" { pub fn llama_model_default_params() -> llama_model_params; } unsafe extern "C" { pub fn llama_context_default_params() -> llama_context_params; } +unsafe extern "C" { + pub fn llama_sampler_chain_default_params() -> llama_sampler_chain_params; +} unsafe extern "C" { pub fn llama_model_quantize_default_params() -> llama_model_quantize_params; } @@ -608,21 +622,81 @@ unsafe extern "C" { unsafe extern "C" { pub fn llama_decode(ctx: *mut llama_context, batch: llama_batch) -> i32; } +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct llama_batch_ext { + _unused: [u8; 0], +} +unsafe extern "C" { + pub fn llama_batch_ext_init(ctx: *mut llama_context) -> *mut llama_batch_ext; +} +unsafe extern "C" { + pub fn llama_batch_ext_free(batch: *mut llama_batch_ext); +} +unsafe extern "C" { + pub fn llama_batch_ext_clear(batch: *mut llama_batch_ext); +} +unsafe extern "C" { + pub fn llama_batch_ext_set_output_logits( + batch: *mut llama_batch_ext, + idx: i32, + value: bool, + ) -> bool; +} +unsafe extern "C" { + pub fn llama_batch_ext_set_pos( + batch: *mut llama_batch_ext, + idx: i32, + pos: *const llama_pos, + ) -> bool; +} +unsafe extern "C" { + pub fn llama_process( + ctx: *mut llama_context, + type_: llama_process_type, + batch: *mut llama_batch_ext, + ) -> i32; +} unsafe extern "C" { pub fn llama_set_embeddings(ctx: *mut llama_context, embeddings: bool); } unsafe extern "C" { pub fn llama_set_causal_attn(ctx: *mut llama_context, causal_attn: bool); } +unsafe extern "C" { + pub fn llama_synchronize(ctx: *mut llama_context); +} unsafe extern "C" { pub fn llama_get_logits_ith(ctx: *mut llama_context, i: i32) -> *mut f32; } unsafe extern "C" { pub fn llama_get_embeddings_ith(ctx: *mut llama_context, i: i32) -> *mut f32; } +unsafe extern "C" { + pub fn llama_get_sampled_token_ith(ctx: *mut llama_context, i: i32) -> llama_token; +} unsafe extern "C" { pub fn llama_vocab_mask(vocab: *const llama_vocab) -> llama_token; } +unsafe extern "C" { + pub fn llama_set_sampler( + ctx: *mut llama_context, + seq_id: llama_seq_id, + smpl: *mut llama_sampler, + ) -> bool; +} +unsafe extern "C" { + pub fn llama_sampler_free(smpl: *mut llama_sampler); +} +unsafe extern "C" { + pub fn llama_sampler_chain_init(params: llama_sampler_chain_params) -> *mut llama_sampler; +} +unsafe extern "C" { + pub fn llama_sampler_chain_add(chain: *mut llama_sampler, smpl: *mut llama_sampler); +} +unsafe extern "C" { + pub fn llama_sampler_init_greedy() -> *mut llama_sampler; +} unsafe extern "C" { pub fn llama_log_set(log_callback: ggml_log_callback, user_data: *mut ::std::os::raw::c_void); } diff --git a/crates/skippy-ffi/src/bindings/skippy.rs b/crates/skippy-ffi/src/bindings/skippy.rs index 434e9696..4ab63ab2 100644 --- a/crates/skippy-ffi/src/bindings/skippy.rs +++ b/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 = 88; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 95; 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; @@ -1213,6 +1213,26 @@ pub struct skippy_iteration_request { #[doc = " Optional final-row readout; mutually exclusive with sample_last."] pub readout: *const skippy_token_score_request, } +#[doc = " @brief One independently sampled speculative window in a shared forward."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_verify_request { + pub session: *mut skippy_session, + pub token_ids: *const llama_token, + pub token_count: usize, + pub sampling: *const skippy_sampling_config, + pub output_tokens: *mut llama_token, + pub output_capacity: usize, + pub out_token_count: *mut usize, +} +unsafe extern "C" { + #[doc = " @brief Verify equal-length windows on independent lanes of one terminal model.\n\n Every window retains its own rollback checkpoint and sampler history. Sampling\n stops at the first rejected proposal in each lane. The caller must trim or\n retire every window before reusing that lane. The combined windows must fit\n one native microbatch. Activation-frontier stages are not supported here."] + pub fn skippy_verify_batch_sampled( + requests: *const skippy_verify_request, + request_count: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Executes mixed prefill chunks and decode tokens in one model iteration.\n\n Requests may have different token counts. Activation outputs are request-major.\n Sampled outputs are compact and explicitly map back to the request indexes\n whose final rows requested logits. GLM-DSA inputs in one iteration must use\n the same sideband width and stream count."] pub fn skippy_iteration_batch_sampled( @@ -1618,6 +1638,23 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +#[doc = " @brief A borrowed range of raw KV page bytes."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_kv_page_chunk { + pub data: *const ::std::os::raw::c_void, + pub bytes: usize, +} +unsafe extern "C" { + #[doc = " @brief Imports a single raw KV page from non-empty chunks in wire order.\n The ranges must remain readable until return and together cover exactly\n desc->payload_bytes. Unsupported layouts or backends leave the session\n untouched, so the caller can retry with a contiguous payload."] + pub fn skippy_import_kv_page_chunks( + session: *mut skippy_session, + desc: *const skippy_kv_page_desc, + chunks: *const skippy_kv_page_chunk, + chunk_count: usize, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Imports validated CacheGen records directly into resident KV storage."] pub fn skippy_import_cachegen_kv_page_v1( @@ -1663,6 +1700,23 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +unsafe extern "C" { + #[doc = " @brief Exports an absolute token range from one resident sliding-window page component.\n The selected range must still be resident in that component.\n The returned descriptor is a single page, with no component offset."] + pub fn skippy_session_export_resident_kv_component( + session: *mut skippy_session, + cache_seq_id: i32, + role: skippy_kv_page_component_role, + 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( @@ -1674,6 +1728,17 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +unsafe extern "C" { + #[doc = " @brief Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint."] + pub fn skippy_session_copy_resident_recurrent_range( + session: *mut skippy_session, + cache_seq_id: i32, + offset: usize, + output: *mut ::std::os::raw::c_void, + bytes: 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( diff --git a/crates/skippy-ffi/src/dynamic.rs b/crates/skippy-ffi/src/dynamic.rs index 4653ddc6..68263544 100644 --- a/crates/skippy-ffi/src/dynamic.rs +++ b/crates/skippy-ffi/src/dynamic.rs @@ -10,17 +10,17 @@ use crate::{ ABI_VERSION_MAJOR, ABI_VERSION_MINOR, ABI_VERSION_PATCH, AbiVersion, ActivationBoundaryDesc, ActivationDesc, AsrAbortCallback, AsrInfoV1, AsrModel, AsrResult, AsrSegmentV1, AsrTranscribeParamsV1, BackendDevice, CacheGenRecordV1, ClefInfoV1, ClefModel, Error, - GenerationSignalWindow, IterationRequest, KvPageDesc, LayaInfoV1, LayaMemoryV1, LayaModel, - LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, LlamaPerfContextFn, Model, ModelInfo, - MtmdBitmap, MtmdContext, MtmdContextParams, MtmdDecoderPos, MtmdGenAudioInfo, - MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, MtmdHelperGenAudio, MtmdHelperGenAudioInput, - MtmdHelperInitOpt, MtmdHelperVideo, MtmdInputChunkType, MtmdInputChunks, MtmdInputText, - NativeMtpDraft, NativeRuntimeLoadError, NgramCache, Opaque, RuntimeConfig, SamplingConfig, - Session, SkippyDecodeStepSampledMtpFn, SkippyModelAttachMtpDraftModelFn, - SkippyRuntimeEventReporterV1, StagePlan, StagePlanDescV1, StagePlanProfileDescV1, - StagePlanStateDescV1, StagePlanStringRefV1, StagePlanValueDescV1, StagePlanValueKind, - StagePlanner, StagePlannerConfigV1, Status, SystemOneSlot, TensorInfo, TokenLogprobs, - TokenSignal, WorkloadInfoV1, runtime_abi_supported, + GenerationSignalWindow, IterationRequest, KvPageChunk, KvPageComponentRole, KvPageDesc, + LayaInfoV1, LayaMemoryV1, LayaModel, LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, + LlamaPerfContextFn, Model, ModelInfo, MtmdBitmap, MtmdContext, MtmdContextParams, + MtmdDecoderPos, MtmdGenAudioInfo, MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, + MtmdHelperGenAudio, MtmdHelperGenAudioInput, MtmdHelperInitOpt, MtmdHelperVideo, + MtmdInputChunkType, MtmdInputChunks, MtmdInputText, NativeMtpDraft, NativeRuntimeLoadError, + NgramCache, Opaque, RuntimeConfig, SamplingConfig, Session, SkippyDecodeStepSampledMtpFn, + SkippyModelAttachMtpDraftModelFn, SkippyRuntimeEventReporterV1, StagePlan, StagePlanDescV1, + StagePlanProfileDescV1, StagePlanStateDescV1, StagePlanStringRefV1, StagePlanValueDescV1, + StagePlanValueKind, StagePlanner, StagePlannerConfigV1, Status, SystemOneSlot, TensorInfo, + TokenLogprobs, TokenSignal, WorkloadInfoV1, runtime_abi_supported, }; static SYMBOLS: OnceLock = OnceLock::new(); @@ -238,6 +238,7 @@ dynamic_symbols! { skippy_session_free(session: *mut Session, out_error: *mut *mut Error) -> Status; skippy_prefill_chunk(session: *mut Session, token_ids: *const i32, token_count: usize, input_activations: *const c_void, input_activation_bytes: usize, output_activations: *mut c_void, output_activation_capacity: usize, out_output_activation_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_verify_tokens(session: *mut Session, token_ids: *const i32, token_count: usize, output_tokens: *mut i32, output_token_capacity: usize, out_token_count: *mut usize, out_error: *mut *mut Error) -> Status; + skippy_verify_batch_sampled(requests: *const crate::bindings::skippy::skippy_verify_request, request_count: usize, out_error: *mut *mut Error) -> Status; skippy_decode_step_sampled(session: *mut Session, token_id: i32, sampling: *const SamplingConfig, input_activation: *const c_void, input_activation_bytes: usize, output_activation: *mut c_void, output_activation_capacity: usize, out_output_activation_bytes: *mut usize, out_predicted_token: *mut i32, out_error: *mut *mut Error) -> Status; skippy_decode_batch_sampled(sessions: *const *mut Session, token_ids: *const i32, sampling: *const *const SamplingConfig, request_count: usize, out_predicted_tokens: *mut i32, predicted_token_capacity: usize, out_error: *mut *mut Error) -> Status; skippy_iteration_batch_sampled(requests: *const IterationRequest, request_count: usize, output_descs: *mut ActivationDesc, output_payloads: *const *mut c_void, output_payload_capacities: *const usize, out_output_payload_bytes: *mut usize, out_sampled_request_indexes: *mut usize, out_predicted_tokens: *mut i32, sampled_output_capacity: usize, out_sampled_output_count: *mut usize, out_error: *mut *mut Error) -> Status; @@ -262,12 +263,15 @@ dynamic_symbols! { skippy_import_full_state(session: *mut Session, layer_start: i32, layer_end: i32, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; skippy_export_kv_page(session: *mut Session, 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_import_kv_page(session: *mut Session, desc: *const KvPageDesc, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; + skippy_import_kv_page_chunks(session: *mut Session, desc: *const KvPageDesc, chunks: *const KvPageChunk, chunk_count: 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_component(session: *mut Session, cache_seq_id: i32, role: KvPageComponentRole, 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_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_copy_resident_recurrent_range(session: *mut Session, cache_seq_id: i32, offset: usize, output: *mut c_void, bytes: 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; @@ -537,6 +541,34 @@ pub(crate) fn llama_draft_api() -> Option<&'static LlamaDraftApi> { .get_or_init(|| { let symbols = symbols(); Some(LlamaDraftApi { + device_features: (|| { + Some(crate::llama_draft::LlamaDraftDeviceApi { + set_capture: symbols + .lookup_optional(b"llama_set_embeddings_layer_inp_dev\0")?, + supports_rows: symbols.lookup_optional(b"llama_supports_embd_row\0")?, + add_row: symbols.lookup_optional(b"llama_batch_ext_add_embd_row\0")?, + batch_init: symbols.lookup_optional(b"llama_batch_ext_init\0")?, + batch_free: symbols.lookup_optional(b"llama_batch_ext_free\0")?, + batch_clear: symbols.lookup_optional(b"llama_batch_ext_clear\0")?, + set_pos: symbols.lookup_optional(b"llama_batch_ext_set_pos\0")?, + set_output: symbols + .lookup_optional(b"llama_batch_ext_set_output_logits\0")?, + process: symbols.lookup_optional(b"llama_process\0")?, + synchronize: symbols.lookup_optional(b"llama_synchronize\0")?, + }) + })(), + sampling: (|| { + Some(crate::llama_draft::LlamaDraftSamplingApi { + chain_default_params: symbols + .lookup_optional(b"llama_sampler_chain_default_params\0")?, + chain_init: symbols.lookup_optional(b"llama_sampler_chain_init\0")?, + chain_add: symbols.lookup_optional(b"llama_sampler_chain_add\0")?, + init_greedy: symbols.lookup_optional(b"llama_sampler_init_greedy\0")?, + free: symbols.lookup_optional(b"llama_sampler_free\0")?, + set_sampler: symbols.lookup_optional(b"llama_set_sampler\0")?, + get_token: symbols.lookup_optional(b"llama_get_sampled_token_ith\0")?, + }) + })(), model_default_params: symbols.lookup_optional(b"llama_model_default_params\0")?, context_default_params: symbols .lookup_optional(b"llama_context_default_params\0")?, diff --git a/crates/skippy-ffi/src/lib.rs b/crates/skippy-ffi/src/lib.rs index 6ef8a204..5fe390f1 100644 --- a/crates/skippy-ffi/src/lib.rs +++ b/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 = 88; +pub const ABI_VERSION_PATCH: u32 = 95; // 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 @@ -140,7 +140,8 @@ pub use state::{ CACHEGEN_RECORD_F32, CACHEGEN_RECORD_F32_TRANSPOSED, CACHEGEN_RECORD_Q4_0, CACHEGEN_RECORD_Q8_0, CACHEGEN_RECORD_V1_ABI_VERSION, CacheGenRecordV1, KV_PAGE_CODEC_ISWA_COMPOSITE_V1, KV_PAGE_CODEC_SINGLE_V1, KV_PAGE_FLAG_CANONICAL_POSITIONS, - KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentDesc, KvPageDesc, + KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, KvPageChunk, KvPageComponentDesc, + KvPageComponentRole, KvPageDesc, }; #[cfg(not(feature = "dynamic-runtime"))] @@ -184,27 +185,29 @@ pub use dynamic::{ skippy_decode_step_sampled, skippy_decode_step_sampled_mtp, skippy_decode_step_sampled_mtp_fn, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, skippy_import_cachegen_kv_page_v1, - skippy_import_full_state, skippy_import_kv_page, skippy_import_recurrent_state, - skippy_import_state, skippy_iteration_batch_sampled, skippy_laya_model_free, - skippy_laya_model_info_v1, skippy_laya_model_memory_v1, skippy_laya_model_open, - 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_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_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, skippy_ngram_cache_draft, skippy_ngram_cache_free, - skippy_ngram_cache_reset, skippy_parse_chat_response_json, skippy_prefill_chunk, - skippy_prefill_chunk_frame, skippy_prefill_chunk_frame_sampled, - skippy_prefill_chunk_frame_sampled_with_positions, skippy_prefill_chunk_frame_with_positions, - skippy_retire_verify_checkpoint, skippy_session_batch_size, - skippy_session_begin_external_decode, skippy_session_configure_chat_sampling, - skippy_session_copy_output_activation_frame, skippy_session_create, + skippy_import_full_state, skippy_import_kv_page, skippy_import_kv_page_chunks, + skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, + skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, + skippy_laya_model_open, 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_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_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, + skippy_ngram_cache_draft, skippy_ngram_cache_free, skippy_ngram_cache_reset, + skippy_parse_chat_response_json, skippy_prefill_chunk, skippy_prefill_chunk_frame, + skippy_prefill_chunk_frame_sampled, skippy_prefill_chunk_frame_sampled_with_positions, + skippy_prefill_chunk_frame_with_positions, skippy_retire_verify_checkpoint, + skippy_session_batch_size, skippy_session_begin_external_decode, + skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, + skippy_session_copy_resident_recurrent_range, 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_export_resident_kv_page, skippy_session_export_resident_recurrent_state, - skippy_session_free, skippy_session_last_token_signal, skippy_session_llama_context, + skippy_session_export_resident_kv_component, 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, @@ -216,9 +219,9 @@ pub use dynamic::{ skippy_stage_plan_validate_chain_v1, skippy_stage_plan_value_at_v1, skippy_stage_planner_create_v1, skippy_stage_planner_free, skippy_stage_planner_realize_v1, skippy_system_one_canvas_length, skippy_system_one_read, skippy_token_is_eog, skippy_tokenize, - skippy_trim_session, skippy_verify_tokens, skippy_verify_tokens_frame_sampled, - skippy_write_gguf_from_parts, skippy_write_gguf_from_parts_consuming, - skippy_write_gguf_metadata_from_parts, + skippy_trim_session, skippy_verify_batch_sampled, skippy_verify_tokens, + skippy_verify_tokens_frame_sampled, skippy_write_gguf_from_parts, + skippy_write_gguf_from_parts_consuming, skippy_write_gguf_metadata_from_parts, }; #[cfg(feature = "dynamic-runtime")] @@ -257,9 +260,9 @@ pub use static_bindings::{ skippy_decode_step_sampled_mtp, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, skippy_import_cachegen_kv_page_v1, skippy_import_full_state, skippy_import_kv_page, - skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, - skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, - skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, + skippy_import_kv_page_chunks, skippy_import_recurrent_state, skippy_import_state, + skippy_iteration_batch_sampled, skippy_laya_model_free, skippy_laya_model_info_v1, + skippy_laya_model_memory_v1, 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_kv_pool_cells, skippy_model_llama_model, @@ -272,9 +275,10 @@ pub use static_bindings::{ skippy_prefill_chunk_frame_with_positions, skippy_retire_verify_checkpoint, skippy_session_batch_size, 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_export_resident_kv_page, + skippy_session_copy_resident_recurrent_range, 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_export_resident_kv_component, 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, @@ -288,7 +292,7 @@ pub use static_bindings::{ skippy_stage_plan_validate_chain_v1, skippy_stage_plan_value_at_v1, skippy_stage_planner_create_v1, skippy_stage_planner_free, skippy_stage_planner_realize_v1, skippy_system_one_canvas_length, skippy_system_one_read, skippy_token_is_eog, skippy_tokenize, - skippy_trim_session, skippy_verify_tokens, skippy_verify_tokens_frame_sampled, - skippy_write_gguf_from_parts, skippy_write_gguf_from_parts_consuming, - skippy_write_gguf_metadata_from_parts, + skippy_trim_session, skippy_verify_batch_sampled, skippy_verify_tokens, + skippy_verify_tokens_frame_sampled, skippy_write_gguf_from_parts, + skippy_write_gguf_from_parts_consuming, skippy_write_gguf_metadata_from_parts, }; diff --git a/crates/skippy-ffi/src/llama_draft.rs b/crates/skippy-ffi/src/llama_draft.rs index 4d1e8f51..2ecca1fd 100644 --- a/crates/skippy-ffi/src/llama_draft.rs +++ b/crates/skippy-ffi/src/llama_draft.rs @@ -19,6 +19,9 @@ use std::ffi::c_char; use crate::Opaque; use crate::bindings; +mod device; +pub use device::{LlamaDraftDeviceApi, LlamaProcessType}; + pub type LlamaToken = bindings::llama::llama_token; pub type LlamaPos = bindings::llama::llama_pos; pub type LlamaSeqId = bindings::llama::llama_seq_id; @@ -33,6 +36,20 @@ pub type LlamaFlashAttnType = bindings::llama::llama_flash_attn_type; pub type LlamaRopeType = bindings::llama::llama_rope_type; pub type LlamaSplitMode = bindings::llama::llama_split_mode; pub type GgmlType = bindings::llama::ggml_type; +pub type LlamaSamplerChainParams = bindings::llama::llama_sampler_chain_params; + +/// Optional backend sampler operations. Older runtime exports can still draft +/// through the original host logits readout when these symbols are absent. +#[derive(Clone, Copy)] +pub struct LlamaDraftSamplingApi { + pub chain_default_params: unsafe extern "C" fn() -> LlamaSamplerChainParams, + pub chain_init: unsafe extern "C" fn(LlamaSamplerChainParams) -> *mut Opaque, + pub chain_add: unsafe extern "C" fn(*mut Opaque, *mut Opaque), + pub init_greedy: unsafe extern "C" fn() -> *mut Opaque, + pub free: unsafe extern "C" fn(*mut Opaque), + pub set_sampler: unsafe extern "C" fn(*mut Opaque, i32, *mut Opaque) -> bool, + pub get_token: unsafe extern "C" fn(*mut Opaque, i32) -> i32, +} /// `LLAMA_CONTEXT_TYPE_DEFAULT`. pub const LLAMA_CONTEXT_TYPE_DEFAULT: LlamaContextType = LlamaContextType::Default; @@ -103,6 +120,8 @@ pub fn ggml_type_from_cache_code(code: i32) -> Option { /// `llama_vocab`, `llama_memory_t`, or `ggml_backend_dev_t`). #[derive(Clone, Copy)] pub struct LlamaDraftApi { + pub device_features: Option, + pub sampling: Option, pub model_default_params: unsafe extern "C" fn() -> LlamaModelParams, pub context_default_params: unsafe extern "C" fn() -> LlamaContextParams, pub model_load_from_file: @@ -155,6 +174,16 @@ pub fn llama_draft_api() -> Option<&'static LlamaDraftApi> { pub fn llama_draft_api() -> Option<&'static LlamaDraftApi> { use crate::static_bindings as raw; static API: LlamaDraftApi = LlamaDraftApi { + device_features: Some(device::static_api()), + sampling: Some(LlamaDraftSamplingApi { + chain_default_params: crate::bindings::llama::llama_sampler_chain_default_params, + chain_init: raw::llama_draft_sampler_chain_init, + chain_add: raw::llama_draft_sampler_chain_add, + init_greedy: raw::llama_draft_sampler_init_greedy, + free: raw::llama_draft_sampler_free, + set_sampler: raw::llama_draft_set_sampler, + get_token: raw::llama_draft_get_sampled_token, + }), model_default_params: raw::llama_model_default_params, context_default_params: raw::llama_context_default_params, model_load_from_file: raw::llama_model_load_from_file, diff --git a/crates/skippy-ffi/src/llama_draft/device.rs b/crates/skippy-ffi/src/llama_draft/device.rs new file mode 100644 index 00000000..232c99d5 --- /dev/null +++ b/crates/skippy-ffi/src/llama_draft/device.rs @@ -0,0 +1,77 @@ +//! Optional upstream device-row injection surface. +use crate::{Opaque, bindings}; + +pub type LlamaProcessType = bindings::llama::llama_process_type; + +#[derive(Clone, Copy)] +pub struct LlamaDraftDeviceApi { + pub set_capture: unsafe extern "C" fn(*mut Opaque, bool), + pub supports_rows: unsafe extern "C" fn(*const Opaque) -> bool, + pub batch_init: unsafe extern "C" fn(*mut Opaque) -> *mut Opaque, + pub batch_free: unsafe extern "C" fn(*mut Opaque), + pub batch_clear: unsafe extern "C" fn(*mut Opaque), + pub add_row: unsafe extern "C" fn(*mut Opaque, i32, i32) -> i32, + pub set_pos: unsafe extern "C" fn(*mut Opaque, i32, *const i32) -> bool, + pub set_output: unsafe extern "C" fn(*mut Opaque, i32, bool) -> bool, + pub process: unsafe extern "C" fn(*mut Opaque, LlamaProcessType, *mut Opaque) -> i32, + pub synchronize: unsafe extern "C" fn(*mut Opaque), +} + +#[cfg(not(feature = "dynamic-runtime"))] +mod linked { + use super::*; + use bindings::llama as raw; + + unsafe extern "C" { + #[link_name = "llama_set_embeddings_layer_inp_dev"] + fn set_capture(ctx: *mut Opaque, enabled: bool); + #[link_name = "llama_supports_embd_row"] + fn supports_rows(ctx: *const Opaque) -> bool; + #[link_name = "llama_batch_ext_add_embd_row"] + fn add_row(batch: *mut Opaque, seq: i32, row: i32) -> i32; + } + + unsafe extern "C" fn batch_init(ctx: *mut Opaque) -> *mut Opaque { + unsafe { raw::llama_batch_ext_init(ctx.cast()).cast() } + } + unsafe extern "C" fn batch_free(batch: *mut Opaque) { + unsafe { raw::llama_batch_ext_free(batch.cast()) } + } + unsafe extern "C" fn batch_clear(batch: *mut Opaque) { + unsafe { raw::llama_batch_ext_clear(batch.cast()) } + } + unsafe extern "C" fn set_pos(batch: *mut Opaque, idx: i32, pos: *const i32) -> bool { + unsafe { raw::llama_batch_ext_set_pos(batch.cast(), idx, pos) } + } + unsafe extern "C" fn set_output(batch: *mut Opaque, idx: i32, value: bool) -> bool { + unsafe { raw::llama_batch_ext_set_output_logits(batch.cast(), idx, value) } + } + unsafe extern "C" fn process( + ctx: *mut Opaque, + mode: LlamaProcessType, + batch: *mut Opaque, + ) -> i32 { + unsafe { raw::llama_process(ctx.cast(), mode, batch.cast()) } + } + unsafe extern "C" fn synchronize(ctx: *mut Opaque) { + unsafe { raw::llama_synchronize(ctx.cast()) } + } + + pub(super) const API: LlamaDraftDeviceApi = LlamaDraftDeviceApi { + set_capture, + supports_rows, + batch_init, + batch_free, + batch_clear, + add_row, + set_pos, + set_output, + process, + synchronize, + }; +} + +#[cfg(not(feature = "dynamic-runtime"))] +pub(super) const fn static_api() -> LlamaDraftDeviceApi { + linked::API +} diff --git a/crates/skippy-ffi/src/state.rs b/crates/skippy-ffi/src/state.rs index 1ddf5df5..69263494 100644 --- a/crates/skippy-ffi/src/state.rs +++ b/crates/skippy-ffi/src/state.rs @@ -50,7 +50,9 @@ pub const CACHEGEN_RECORD_Q4_0: u32 = bindings::skippy::skippy_cachegen_record_k pub type CacheGenRecordV1 = bindings::skippy::skippy_cachegen_record_v1; +pub type KvPageComponentRole = bindings::skippy::skippy_kv_page_component_role; pub type KvPageDesc = bindings::skippy::skippy_kv_page_desc; +pub type KvPageChunk = bindings::skippy::skippy_kv_page_chunk; #[allow(clippy::derivable_impls)] impl Default for KvPageDesc { diff --git a/crates/skippy-ffi/src/static_bindings.rs b/crates/skippy-ffi/src/static_bindings.rs index 6073a6b3..3357fa1c 100644 --- a/crates/skippy-ffi/src/static_bindings.rs +++ b/crates/skippy-ffi/src/static_bindings.rs @@ -24,6 +24,49 @@ use crate::{ pub use crate::bindings::skippy::*; +/// # Safety +/// Parameters must come from this runtime's sampler defaults. +pub unsafe extern "C" fn llama_draft_sampler_chain_init( + params: crate::llama_draft::LlamaSamplerChainParams, +) -> *mut Opaque { + unsafe { llama::llama_sampler_chain_init(params).cast() } +} + +/// # Safety +/// Both handles must be live; the chain takes ownership of the sampler. +pub unsafe extern "C" fn llama_draft_sampler_chain_add(chain: *mut Opaque, sampler: *mut Opaque) { + unsafe { llama::llama_sampler_chain_add(chain.cast(), sampler.cast()) } +} + +/// # Safety +/// Free the returned handle with the same runtime's sampler free function. +pub unsafe extern "C" fn llama_draft_sampler_init_greedy() -> *mut Opaque { + unsafe { llama::llama_sampler_init_greedy().cast() } +} + +/// # Safety +/// The sampler must be detached from any live context before freeing it. +pub unsafe extern "C" fn llama_draft_sampler_free(sampler: *mut Opaque) { + unsafe { llama::llama_sampler_free(sampler.cast()) } +} + +/// # Safety +/// Context and optional sampler must belong to this runtime. The caller retains +/// sampler ownership and must keep it live until it is detached. +pub unsafe extern "C" fn llama_draft_set_sampler( + ctx: *mut Opaque, + seq: i32, + sampler: *mut Opaque, +) -> bool { + unsafe { llama::llama_set_sampler(ctx.cast(), seq, sampler.cast()) } +} + +/// # Safety +/// The context must have decoded this output row with a backend sampler. +pub unsafe extern "C" fn llama_draft_get_sampled_token(ctx: *mut Opaque, row: i32) -> i32 { + unsafe { llama::llama_get_sampled_token_ith(ctx.cast(), row) } +} + pub use llama::{ ggml_log_set, llama_log_set, llama_model_is_diffusion, llama_model_is_hybrid, llama_model_is_recurrent, llama_model_meta_val_str, llama_model_quantize, diff --git a/crates/skippy-inference-api/README.md b/crates/skippy-inference-api/README.md index 0626531f..4ae74a54 100644 --- a/crates/skippy-inference-api/README.md +++ b/crates/skippy-inference-api/README.md @@ -182,6 +182,23 @@ perform exact string matching on requests. Resolution to a concrete Hugging Face revision, GGUF file, split-shard distribution, local runtime, or staged binary chain remains backend-owned. +## Request Tiers + +Every request carries an `InferenceRequestClass` with a tier (`local`, +`trusted` or `mesh`, highest first) and a private cache partition flag. +The public standalone router uses the default local class. An embedding +host behind a trusted upstream can enable +`InferenceFrontendConfig::with_trusted_request_class_headers` to read +`x-skippy-request-tier` and `x-skippy-cache-partition`. The upstream must +strip client-supplied values and stamp its own classification. The router +sets the class on `InferenceRequestContext`. Embedding hosts that call a +backend directly set it on the context. A backend reads the class from the context and stamps it on the +`GenerationRequest` (`request_class`) for its hooks; request bodies never set +it. `InferenceRequestClass::cache_namespace` turns the class into the cache +namespace prefix (`tier::`) that keeps each tier's, and each side +of the private line's, cached prefixes apart; a `local`, non-private request +keeps the plain namespace. + ## Backend Responsibility Matrix | Area | Frontend responsibility | Backend responsibility | Status | diff --git a/crates/skippy-inference-api/src/anthropic/routes.rs b/crates/skippy-inference-api/src/anthropic/routes.rs index e86acb40..ea9b6ac4 100644 --- a/crates/skippy-inference-api/src/anthropic/routes.rs +++ b/crates/skippy-inference-api/src/anthropic/routes.rs @@ -62,6 +62,7 @@ pub(crate) async fn messages( >, ) -> Result { let Json(request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); let mut generation_request = messages_request_to_generation(request)?; @@ -69,9 +70,23 @@ pub(crate) async fn messages( generation_request.validate()?; if generation_request.stream { - streaming_messages(&state, context, generation_request, trusted_agent_session).await + streaming_messages( + &state, + context, + generation_request, + class, + trusted_agent_session, + ) + .await } else { - non_streaming_messages(&state, context, generation_request, trusted_agent_session).await + non_streaming_messages( + &state, + context, + generation_request, + class, + trusted_agent_session, + ) + .await } } @@ -79,9 +94,10 @@ async fn non_streaming_messages( state: &FrontendState, context: InferenceLifecycleContext, request: crate::generation::GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -113,11 +129,12 @@ async fn streaming_messages( state: &FrontendState, context: InferenceLifecycleContext, request: crate::generation::GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { let model = request.model.clone(); let request_id: RequestId = context.request_id; - let backend_context = request_context(request_id, trusted_agent_session, true); + let backend_context = request_context(request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -251,8 +268,9 @@ pub(crate) async fn messages_count_tokens( >, ) -> Result, AnthropicRejection> { let Json(request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let session = agent_session_from_header(&state.config, &headers)?; - let backend_context = request_context(context.request_id, session.is_some(), false); + let backend_context = request_context(context.request_id, class, session.is_some(), false); let mut chat = messages_request_to_generation(request.into_messages())?; chat.set_agent_session(session); chat.validate()?; diff --git a/crates/skippy-inference-api/src/anthropic/translate.rs b/crates/skippy-inference-api/src/anthropic/translate.rs index 4a33a220..3dcb9a5f 100644 --- a/crates/skippy-inference-api/src/anthropic/translate.rs +++ b/crates/skippy-inference-api/src/anthropic/translate.rs @@ -177,6 +177,7 @@ pub fn messages_request_to_generation( extra: BTreeMap::new(), }), extra: request.extra, + request_class: Default::default(), }) } diff --git a/crates/skippy-inference-api/src/backend.rs b/crates/skippy-inference-api/src/backend.rs index 7eb213f4..3acbf0b1 100644 --- a/crates/skippy-inference-api/src/backend.rs +++ b/crates/skippy-inference-api/src/backend.rs @@ -75,6 +75,7 @@ pub struct InferenceRequestContext { trusted_agent_session: bool, execution_scope: Option, execution_lease: Option>, + request_class: crate::InferenceRequestClass, } impl InferenceRequestContext { @@ -133,6 +134,18 @@ impl InferenceRequestContext { self.execution_scope } + /// Set the tier and cache partition a trusted front end assigned to this + /// request. Without it a request is `local` and unpartitioned. + pub fn with_request_class(mut self, class: crate::InferenceRequestClass) -> Self { + self.request_class = class; + self + } + + /// Return the request's tier and cache partition. + pub fn request_class(&self) -> crate::InferenceRequestClass { + self.request_class + } + /// Return the frontend request identifier when the caller supplied one. pub fn request_id(&self) -> Option { self.request_id @@ -172,6 +185,7 @@ impl Default for InferenceRequestContext { trusted_agent_session: false, execution_scope: None, execution_lease: None, + request_class: crate::InferenceRequestClass::default(), } } } @@ -240,6 +254,16 @@ pub trait InferenceBackend: Send + Sync + 'static { )) } + /// Serve System One with the request's tier and isolation. The default + /// ignores the context for backends without tiered caches. + async fn system_one_with_context( + &self, + request: SystemOneRequest, + _context: InferenceRequestContext, + ) -> InferenceResult { + self.system_one(request).await + } + /// Embed text or token batches. The default rejects unsupported backends. async fn embeddings( &self, diff --git a/crates/skippy-inference-api/src/chat/generation.rs b/crates/skippy-inference-api/src/chat/generation.rs index b765066b..26db6c47 100644 --- a/crates/skippy-inference-api/src/chat/generation.rs +++ b/crates/skippy-inference-api/src/chat/generation.rs @@ -34,6 +34,8 @@ impl From for GenerationRequest { prompt_cache_retention: value.prompt_cache_retention, stream_options: value.stream_options, extra: value.extra, + // The body never names its class; the backend sets it from context. + request_class: Default::default(), } } } diff --git a/crates/skippy-inference-api/src/chat/request_view.rs b/crates/skippy-inference-api/src/chat/request_view.rs index 2b474a77..e498da85 100644 --- a/crates/skippy-inference-api/src/chat/request_view.rs +++ b/crates/skippy-inference-api/src/chat/request_view.rs @@ -39,6 +39,8 @@ impl Serialize for ChatCompletionRequestRef<'_> { prompt_cache_retention, stream_options, extra, + // Served-in metadata, not part of the request a client sent. + request_class: _, } = self.0; let mut map = serializer.serialize_map(None)?; map.serialize_entry("model", model)?; diff --git a/crates/skippy-inference-api/src/generation/request.rs b/crates/skippy-inference-api/src/generation/request.rs index dffafccb..85c79b8d 100644 --- a/crates/skippy-inference-api/src/generation/request.rs +++ b/crates/skippy-inference-api/src/generation/request.rs @@ -52,6 +52,11 @@ pub struct GenerationRequest { pub stream_options: Option, pub extra: BTreeMap, + + /// The tier and cache partition the request is served in. A backend sets + /// it from the request context when it accepts the request, so hooks see + /// it; no request body sets it. + pub request_class: crate::InferenceRequestClass, } impl GenerationRequest { diff --git a/crates/skippy-inference-api/src/guardrails/compact.rs b/crates/skippy-inference-api/src/guardrails/compact.rs index 7a6aaaec..8926d3e6 100644 --- a/crates/skippy-inference-api/src/guardrails/compact.rs +++ b/crates/skippy-inference-api/src/guardrails/compact.rs @@ -78,6 +78,14 @@ impl InferenceBackend for CompactingInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, diff --git a/crates/skippy-inference-api/src/guardrails/mod.rs b/crates/skippy-inference-api/src/guardrails/mod.rs index 0e644575..7ebf0353 100644 --- a/crates/skippy-inference-api/src/guardrails/mod.rs +++ b/crates/skippy-inference-api/src/guardrails/mod.rs @@ -322,6 +322,14 @@ impl InferenceBackend for GuardedInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, diff --git a/crates/skippy-inference-api/src/hooks.rs b/crates/skippy-inference-api/src/hooks.rs index 3dac24b7..3e8cd7ad 100644 --- a/crates/skippy-inference-api/src/hooks.rs +++ b/crates/skippy-inference-api/src/hooks.rs @@ -428,6 +428,14 @@ impl InferenceBackend for HookedInferenceBackend { self.backend.system_one(request).await } + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.backend.system_one_with_context(request, context).await + } + async fn chat_completion( &self, request: GenerationRequest, @@ -441,6 +449,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let exchange_id = crate::http_exchange::dispatch_exchange_id(); // Armed immediately after minting the exchange id — before // `before_chat_completion` and `on_effective_chat_completion` run — @@ -542,6 +551,7 @@ impl InferenceBackend for HookedInferenceBackend { mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let exchange_id = crate::http_exchange::dispatch_exchange_id(); context.publish_exchange_id(exchange_id.clone()); // Same admission-time arming as `chat_completion_with_context` above diff --git a/crates/skippy-inference-api/src/lib.rs b/crates/skippy-inference-api/src/lib.rs index 1497fd4f..c3e0c1f9 100644 --- a/crates/skippy-inference-api/src/lib.rs +++ b/crates/skippy-inference-api/src/lib.rs @@ -19,6 +19,7 @@ pub mod model_dispatch; pub mod models; pub mod realtime; mod request_lifecycle; +mod request_tier; pub mod rerank; pub mod responses; pub mod router; @@ -81,6 +82,10 @@ pub use lifecycle::{ request_id_response_header, }; pub use models::{ModelId, ModelIdError, ModelObject, ModelsResponse}; +pub use request_tier::{ + CACHE_PARTITION_HEADER, InferenceRequestClass, InferenceRequestTier, PRIVATE_CACHE_PARTITION, + REQUEST_TIER_HEADER, +}; pub use rerank::{RerankDocument, RerankRequest, RerankResponse, RerankResult}; pub use responses::{ NormalizationOutcome, ResponseAdapterMode, ResponsesRequest, StreamUsage, diff --git a/crates/skippy-inference-api/src/request_tier.rs b/crates/skippy-inference-api/src/request_tier.rs new file mode 100644 index 00000000..2f5bf715 --- /dev/null +++ b/crates/skippy-inference-api/src/request_tier.rs @@ -0,0 +1,306 @@ +//! Request tiers: whom a request is served for. The tier orders admission and +//! eviction, and each tier (and the private partition) gets its own caches. + +use axum::http::HeaderMap; + +/// Header a trusted front end sets on the loopback hop to name the tier. +/// +/// Skippy reads every value of this header and keeps the lowest one, so a +/// header can only lower a request's tier. A request without it is `local`: +/// whoever reaches the server directly is on this machine. +pub const REQUEST_TIER_HEADER: &str = "x-skippy-request-tier"; + +/// Header that moves a request into the private cache partition. +/// +/// The only accepted value is `private`. A private request never reuses, or +/// leaves behind, cache entries visible to non-private requests of its tier. +pub const CACHE_PARTITION_HEADER: &str = "x-skippy-cache-partition"; + +/// The value of [`CACHE_PARTITION_HEADER`] that selects the private partition. +pub const PRIVATE_CACHE_PARTITION: &str = "private"; + +/// Whom a request is served for, from lowest to highest precedence. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum InferenceRequestTier { + /// Anyone else on the mesh. + Mesh, + /// A node whose owner this node's operator trusts. + Trusted, + /// This machine, or a node of this node's own owner. + #[default] + Local, +} + +impl InferenceRequestTier { + /// Every tier, from lowest to highest. + pub const ALL: [Self; 3] = [Self::Mesh, Self::Trusted, Self::Local]; + + /// The lowercase name used in headers, config and metrics. + pub const fn as_str(self) -> &'static str { + match self { + Self::Mesh => "mesh", + Self::Trusted => "trusted", + Self::Local => "local", + } + } + + /// Parse a tier name, ignoring case and surrounding whitespace. + pub fn parse(value: &str) -> Option { + let value = value.trim(); + Self::ALL + .into_iter() + .find(|tier| tier.as_str().eq_ignore_ascii_case(value)) + } + + /// Scheduling priority: a higher value is admitted first. + pub const fn priority(self) -> u64 { + match self { + Self::Mesh => 0, + Self::Trusted => 1, + Self::Local => 2, + } + } + + /// Stable one-byte code for wire headers and cache identities. + pub const fn code(self) -> u8 { + match self { + Self::Mesh => 0, + Self::Trusted => 1, + Self::Local => 2, + } + } + + /// Decode [`Self::code`]; unknown codes are rejected. + pub const fn from_code(code: u8) -> Option { + match code { + 0 => Some(Self::Mesh), + 1 => Some(Self::Trusted), + 2 => Some(Self::Local), + _ => None, + } + } + + /// The lowest tier among the values of `header`, starting from `Local`. + /// + /// A value that is not a tier name counts as `Mesh`, so a malformed header + /// fails low rather than being ignored. + pub fn from_headers(headers: &HeaderMap, header: &str) -> Self { + headers + .get_all(header) + .iter() + .flat_map(|value| { + value + .to_str() + .map(|value| value.split(',').map(Self::parse).collect::>()) + .unwrap_or_else(|_| vec![None]) + }) + .map(|tier| tier.unwrap_or(Self::Mesh)) + .fold(Self::Local, Self::min) + } +} + +impl std::fmt::Display for InferenceRequestTier { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.as_str()) + } +} + +/// A request's tier plus whether it uses the private cache partition. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +pub struct InferenceRequestClass { + tier: InferenceRequestTier, + private: bool, +} + +impl InferenceRequestClass { + pub const fn new(tier: InferenceRequestTier, private: bool) -> Self { + Self { tier, private } + } + + /// Read the class a trusted front end stamped on an HTTP request. + pub fn from_headers(headers: &HeaderMap) -> Self { + // `private` is the only partition the header names, so any value, even + // an unreadable one, keeps the request out of the shared partition. + let private = headers.contains_key(CACHE_PARTITION_HEADER); + Self::new( + InferenceRequestTier::from_headers(headers, REQUEST_TIER_HEADER), + private, + ) + } + + pub const fn tier(self) -> InferenceRequestTier { + self.tier + } + + pub const fn is_private(self) -> bool { + self.private + } + + /// Lower the tier to `tier` if that is lower; never raise it. + pub fn limited_to(self, tier: InferenceRequestTier) -> Self { + Self::new(self.tier.min(tier), self.private) + } + + /// The cache partition label, or `None` for the default partition + /// (`local`, not private), which keeps cache keys unchanged for + /// standalone Skippy. + pub fn cache_partition(self) -> Option { + match (self.tier, self.private) { + (InferenceRequestTier::Local, false) => None, + (tier, false) => Some(tier.as_str().to_owned()), + (tier, true) => Some(format!("{}-{PRIVATE_CACHE_PARTITION}", tier.as_str())), + } + } + + /// Partition a cache namespace by this class. The default class returns + /// `namespace` unchanged; any other class prefixes it with + /// `tier::`, which no unpartitioned namespace starts with. + pub fn cache_namespace(self, namespace: Option) -> Option { + match self.cache_partition() { + Some(partition) => Some(format!( + "{CACHE_NAMESPACE_TIER_PREFIX}{partition}:{}", + namespace.unwrap_or_default() + )), + None => namespace, + } + } + + /// Recover the class from a namespace built by [`Self::cache_namespace`]. + /// An unpartitioned namespace is the default class; an unrecognized + /// partition is `mesh`, so a malformed one is evicted first. + pub fn from_cache_namespace(namespace: Option<&str>) -> Self { + let Some(rest) = namespace.and_then(|ns| ns.strip_prefix(CACHE_NAMESPACE_TIER_PREFIX)) + else { + return Self::default(); + }; + let partition = rest + .split_once(':') + .map_or(rest, |(partition, _)| partition); + let (tier, private) = match partition.strip_suffix(PRIVATE_CACHE_PARTITION) { + Some(tier) => (tier.strip_suffix('-').unwrap_or(tier), true), + None => (partition, false), + }; + Self::new( + InferenceRequestTier::parse(tier).unwrap_or(InferenceRequestTier::Mesh), + private, + ) + } +} + +/// Prefix that marks a cache namespace partitioned by request class. +const CACHE_NAMESPACE_TIER_PREFIX: &str = "tier:"; + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::HeaderValue; + + fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.append(*name, HeaderValue::from_static(value)); + } + headers + } + + #[test] + fn missing_header_is_local() { + assert_eq!( + InferenceRequestClass::from_headers(&HeaderMap::new()), + InferenceRequestClass::default() + ); + assert_eq!( + InferenceRequestClass::default().tier(), + InferenceRequestTier::Local + ); + } + + #[test] + fn repeated_values_keep_the_lowest_tier() { + let headers = headers(&[ + (REQUEST_TIER_HEADER, "local"), + (REQUEST_TIER_HEADER, "Trusted, local"), + ]); + assert_eq!( + InferenceRequestTier::from_headers(&headers, REQUEST_TIER_HEADER), + InferenceRequestTier::Trusted + ); + } + + #[test] + fn unknown_values_fail_low() { + let headers = headers(&[(REQUEST_TIER_HEADER, "owner")]); + assert_eq!( + InferenceRequestTier::from_headers(&headers, REQUEST_TIER_HEADER), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn limiting_never_raises() { + let class = InferenceRequestClass::new(InferenceRequestTier::Trusted, false); + assert_eq!( + class.limited_to(InferenceRequestTier::Local).tier(), + InferenceRequestTier::Trusted + ); + assert_eq!( + class.limited_to(InferenceRequestTier::Mesh).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn partitions_are_distinct_and_default_is_unpartitioned() { + let partitions = InferenceRequestTier::ALL + .into_iter() + .flat_map(|tier| [false, true].map(|private| InferenceRequestClass::new(tier, private))) + .map(InferenceRequestClass::cache_partition) + .collect::>(); + assert_eq!(partitions.iter().filter(|p| p.is_none()).count(), 1); + let named = partitions + .into_iter() + .flatten() + .collect::>(); + assert_eq!(named.len(), 5); + assert!( + InferenceRequestClass::from_headers(&headers(&[(CACHE_PARTITION_HEADER, "private")])) + .is_private() + ); + assert!( + InferenceRequestClass::from_headers(&headers(&[( + CACHE_PARTITION_HEADER, + "private, private" + )])) + .is_private() + ); + assert!(!InferenceRequestClass::from_headers(&HeaderMap::new()).is_private()); + } + + #[test] + fn cache_namespaces_round_trip_every_class() { + for tier in InferenceRequestTier::ALL { + for private in [false, true] { + let class = InferenceRequestClass::new(tier, private); + for inner in [None, Some("openai:prompt_cache_key:tier:local".to_owned())] { + let namespace = class.cache_namespace(inner); + assert_eq!( + InferenceRequestClass::from_cache_namespace(namespace.as_deref()), + class + ); + } + } + } + assert_eq!( + InferenceRequestClass::from_cache_namespace(Some("tier:owner:x")).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn codes_round_trip() { + for tier in InferenceRequestTier::ALL { + assert_eq!(InferenceRequestTier::from_code(tier.code()), Some(tier)); + } + assert_eq!(InferenceRequestTier::from_code(3), None); + } +} diff --git a/crates/skippy-inference-api/src/router.rs b/crates/skippy-inference-api/src/router.rs index 1d1db0bf..a8f77aeb 100644 --- a/crates/skippy-inference-api/src/router.rs +++ b/crates/skippy-inference-api/src/router.rs @@ -185,6 +185,7 @@ pub struct InferenceFrontendConfig { /// Header accepted as stable agent-session identity from the endpoint's /// trusted immediate upstream. `None` disables header-derived identity. pub agent_session_header: Option, + trust_request_class_headers: bool, pub(crate) lifecycle_observer: Option>, pub http_exchange_policy: Option>, } @@ -196,6 +197,10 @@ impl std::fmt::Debug for InferenceFrontendConfig { .field("max_request_body_bytes", &self.max_request_body_bytes) .field("backend_timeout", &self.backend_timeout) .field("agent_session_header", &self.agent_session_header) + .field( + "trust_request_class_headers", + &self.trust_request_class_headers, + ) .field("has_lifecycle_observer", &self.lifecycle_observer.is_some()) .field( "has_http_exchange_policy", @@ -236,6 +241,13 @@ impl InferenceFrontendConfig { self } + /// Accept request tier and cache partition headers from a trusted immediate upstream. + /// The upstream must strip client-supplied values and stamp its own classification. + pub fn with_trusted_request_class_headers(mut self) -> Self { + self.trust_request_class_headers = true; + self + } + /// Observe metadata-only lifecycle boundaries for frontend ingress. pub fn with_lifecycle_observer( mut self, @@ -261,6 +273,7 @@ impl Default for InferenceFrontendConfig { backend_timeout: configured_backend_timeout() .unwrap_or(Some(Self::DEFAULT_BACKEND_TIMEOUT)), agent_session_header: configured_agent_session_header(), + trust_request_class_headers: false, lifecycle_observer: None, http_exchange_policy: None, } @@ -382,6 +395,7 @@ async fn models( async fn system_one( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result, InferenceError> { let Json(request) = json_payload(payload)?; @@ -391,7 +405,9 @@ async fn system_one( InferenceBackendOperation::SystemOne, "system_one", state.config.backend_timeout, - state.backend.system_one(request), + state + .backend + .system_one_with_context(request, plain_request_context(context.request_id, &headers)), ) .await?; state.response_completed( @@ -405,6 +421,7 @@ async fn system_one( async fn decisions( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result, InferenceError> { let Json(request) = json_payload(payload)?; @@ -414,7 +431,10 @@ async fn decisions( InferenceBackendOperation::SystemOne, "decisions", state.config.backend_timeout, - state.backend.system_one(request.to_system_one()?), + state.backend.system_one_with_context( + request.to_system_one()?, + plain_request_context(context.request_id, &headers), + ), ) .await?; let usage = response.usage; @@ -431,11 +451,12 @@ async fn decisions( async fn embeddings( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response: EmbeddingResponse = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -459,11 +480,12 @@ async fn embeddings( async fn rerank( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response: RerankResponse = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -483,11 +505,12 @@ async fn rerank( async fn audio_speech( State(state): State, Extension(context): Extension, + headers: HeaderMap, payload: Result, JsonRejection>, ) -> Result { let Json(request) = json_payload(payload)?; request.validate()?; - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, &headers); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -516,18 +539,34 @@ fn audio_response(audio: AudioResponse) -> Result { async fn audio_transcriptions( State(state): State, Extension(context): Extension, + headers: HeaderMap, multipart: Result, ) -> Result { - audio_text_request(state, context, multipart_payload(multipart)?, false).await + audio_text_request( + state, + context, + &headers, + multipart_payload(multipart)?, + false, + ) + .await } /// Select English translation without changing the multipart upload contract. async fn audio_translations( State(state): State, Extension(context): Extension, + headers: HeaderMap, multipart: Result, ) -> Result { - audio_text_request(state, context, multipart_payload(multipart)?, true).await + audio_text_request( + state, + context, + &headers, + multipart_payload(multipart)?, + true, + ) + .await } /// Convert extractor rejection into the frontend's structured invalid-request error. @@ -552,13 +591,14 @@ fn multipart_error(error: MultipartError, field: &str) -> InferenceError { async fn audio_text_request( state: FrontendState, context: InferenceLifecycleContext, + headers: &HeaderMap, multipart: Multipart, translate: bool, ) -> Result { let request = parse_audio_multipart(multipart).await?; request.validate()?; let response_format = request.response_format.clone(); - let backend_context = InferenceRequestContext::with_request_id(context.request_id); + let backend_context = plain_request_context(context.request_id, headers); let operation = if translate { InferenceBackendOperation::AudioTranslation } else { @@ -630,13 +670,15 @@ async fn completions( payload: Result, JsonRejection>, ) -> Result { let Json(mut request) = json_payload(payload)?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); request.set_agent_session(header_session); request.validate()?; if request.stream { let include_usage = request.include_usage(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -680,7 +722,8 @@ async fn completions( })); Ok(sse_response(events, cancellation, lifecycle)) } else { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -787,12 +830,24 @@ fn resolve_agent_session( } } +/// A backend context for routes without agent sessions or stream usage, +/// carrying the tier and cache partition the front end stamped on it. +pub(crate) fn plain_request_context( + request_id: RequestId, + headers: &HeaderMap, +) -> InferenceRequestContext { + InferenceRequestContext::with_request_id(request_id) + .with_request_class(crate::InferenceRequestClass::from_headers(headers)) +} + pub(crate) fn request_context( request_id: RequestId, + class: crate::InferenceRequestClass, trusted_agent_session: bool, observe_stream_usage: bool, ) -> InferenceRequestContext { - let mut context = InferenceRequestContext::with_request_id(request_id); + let mut context = + InferenceRequestContext::with_request_id(request_id).with_request_class(class); if let Some(id) = crate::http_exchange::current_host_exchange_id() { context.publish_exchange_id(id); } @@ -863,6 +918,10 @@ async fn frontend_lifecycle_middleware( mut request: Request, next: Next, ) -> Response { + if !state.config.trust_request_class_headers { + request.headers_mut().remove(crate::REQUEST_TIER_HEADER); + request.headers_mut().remove(crate::CACHE_PARTITION_HEADER); + } let (nonce_value, nonce_origin) = apply_client_nonce_headers(&mut request); let request_id = request_id_from_headers_or_generate(request.headers()); let method = request.method().clone(); diff --git a/crates/skippy-inference-api/src/router/generation.rs b/crates/skippy-inference-api/src/router/generation.rs index d9500a01..2a01c2a2 100644 --- a/crates/skippy-inference-api/src/router/generation.rs +++ b/crates/skippy-inference-api/src/router/generation.rs @@ -10,6 +10,7 @@ pub(super) async fn chat_completions( ) -> Result { let Json(request) = json_payload(payload)?; let mut request = GenerationRequest::from(request); + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); request.set_agent_session(header_session); @@ -17,7 +18,8 @@ pub(super) async fn chat_completions( if request.stream { let include_usage = request.include_usage(); let model = request.model.clone(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let stream = call_backend_with_context( state.config.lifecycle_observer.clone(), @@ -72,7 +74,8 @@ pub(super) async fn chat_completions( } Ok(response) } else { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = + request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), &context, @@ -120,6 +123,7 @@ pub(super) async fn responses( let request: ChatCompletionRequest = serde_json::from_value(value).map_err(|error| { InferenceError::invalid_request(format!("invalid Responses request: {error}")) })?; + let class = crate::InferenceRequestClass::from_headers(&headers); let header_session = agent_session_from_header(&state.config, &headers)?; let trusted_agent_session = header_session.is_some(); let mut request = GenerationRequest::from(request); @@ -131,9 +135,9 @@ pub(super) async fn responses( request.validate()?; match normalization.response_adapter { ResponseAdapterMode::OpenAiResponsesStream => { - stream_responses(&state, &context, request, trusted_agent_session).await + stream_responses(&state, &context, request, class, trusted_agent_session).await } - _ => non_streaming_responses(&state, &context, request, trusted_agent_session).await, + _ => non_streaming_responses(&state, &context, request, class, trusted_agent_session).await, } } @@ -141,10 +145,11 @@ async fn stream_responses( state: &FrontendState, context: &InferenceLifecycleContext, request: GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { let include_usage = request.include_usage(); - let backend_context = request_context(context.request_id, trusted_agent_session, true); + let backend_context = request_context(context.request_id, class, trusted_agent_session, true); let cancellation = backend_context.cancellation_token(); let state_machine = Arc::new(Mutex::new(ResponseSseState::new(request.model.clone()))); let stream = call_backend_with_context( @@ -195,9 +200,10 @@ async fn non_streaming_responses( state: &FrontendState, context: &InferenceLifecycleContext, request: GenerationRequest, + class: crate::InferenceRequestClass, trusted_agent_session: bool, ) -> Result { - let backend_context = request_context(context.request_id, trusted_agent_session, false); + let backend_context = request_context(context.request_id, class, trusted_agent_session, false); let response = call_backend_with_context( state.config.lifecycle_observer.clone(), context, diff --git a/crates/skippy-inference-api/tests/request_context_wrappers.rs b/crates/skippy-inference-api/tests/request_context_wrappers.rs index 71b2492d..b5131641 100644 --- a/crates/skippy-inference-api/tests/request_context_wrappers.rs +++ b/crates/skippy-inference-api/tests/request_context_wrappers.rs @@ -102,3 +102,45 @@ async fn backend_wrapper_stack_preserves_authoritative_request_context() { assert_eq!(contexts[1].request_id(), Some(stream_id)); assert!(contexts[1].observes_stream_usage()); } + +#[tokio::test] +async fn only_a_trusted_http_frontend_accepts_request_class_headers() { + use axum::{body::Body, http::Request}; + use skippy_inference_api::{ + CACHE_PARTITION_HEADER, InferenceFrontendConfig, InferenceRequestClass, + InferenceRequestTier, REQUEST_TIER_HEADER, router_with_config, + }; + use tower::ServiceExt; + + let capture = Arc::new(ContextCaptureBackend::default()); + for config in [ + InferenceFrontendConfig::default(), + InferenceFrontendConfig::default().with_trusted_request_class_headers(), + ] { + let response = router_with_config(capture.clone(), config) + .oneshot( + Request::post("/v1/chat/completions") + .header("content-type", "application/json") + .header(REQUEST_TIER_HEADER, "trusted") + .header(CACHE_PARTITION_HEADER, "private") + .body(Body::from( + r#"{"model":"context-model","messages":[{"role":"user","content":"test"}]}"#, + )) + .expect("request fixture"), + ) + .await + .expect("HTTP response"); + assert!(response.status().is_success()); + } + + let contexts = capture.contexts.lock().expect("context lock"); + assert_eq!(contexts.len(), 2); + assert_eq!( + contexts[0].request_class(), + InferenceRequestClass::default() + ); + assert_eq!( + contexts[1].request_class(), + InferenceRequestClass::new(InferenceRequestTier::Trusted, true), + ); +} diff --git a/crates/skippy-model-artifact/src/kv_fixtures.rs b/crates/skippy-model-artifact/src/kv_fixtures.rs new file mode 100644 index 00000000..80bc4b1d --- /dev/null +++ b/crates/skippy-model-artifact/src/kv_fixtures.rs @@ -0,0 +1,183 @@ +//! Pinned model fixtures for KV cache correctness and parity tests. + +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use skippy_model_ref::gguf_matches_quant_selector; +use std::collections::BTreeSet; + +pub const KV_FIXTURE_MANIFEST: &str = include_str!("kv_fixtures/models.json"); + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum KvArchitectureCase { + DenseAttention, + HybridDense, + AttentionMoe, + HybridMoe, +} + +impl KvArchitectureCase { + pub const fn as_str(self) -> &'static str { + match self { + Self::DenseAttention => "dense-attention", + Self::HybridDense => "hybrid-dense", + Self::AttentionMoe => "attention-moe", + Self::HybridMoe => "hybrid-moe", + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub enum KvFixtureQuantization { + #[serde(rename = "Q4_K_M")] + Q4Km, + #[serde(rename = "UD-Q4_K_M")] + UdQ4Km, +} + +impl KvFixtureQuantization { + pub const fn as_str(self) -> &'static str { + match self { + Self::Q4Km => "Q4_K_M", + Self::UdQ4Km => "UD-Q4_K_M", + } + } +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Sidecar { + pub file: String, + pub size_bytes: u64, + pub sha256: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct KvFixture { + pub family: KvArchitectureCase, + pub repo: String, + pub revision: String, + pub file: String, + pub quantization: KvFixtureQuantization, + pub size_bytes: u64, + pub sha256: String, + pub chat_template_sha256: String, + pub license: String, + pub architecture: String, + pub layers: u32, + pub required_sidecars: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct KvFixtureManifest { + schema_version: u32, + pub models: Vec, +} + +impl KvFixtureManifest { + pub fn bundled() -> Result { + Self::parse(KV_FIXTURE_MANIFEST) + } + + pub fn parse(json: &str) -> Result { + let manifest: Self = serde_json::from_str(json).context("parse KV fixture identities")?; + let mut families = BTreeSet::new(); + let mut coordinates = BTreeSet::new(); + let mut digests = BTreeSet::new(); + for model in &manifest.models { + model + .validate() + .with_context(|| format!("validate {} fixture", model.family.as_str()))?; + ensure!( + families.insert(model.family), + "duplicate KV architecture case" + ); + ensure!( + coordinates.insert((&model.repo, &model.revision, &model.file)) + && digests.insert(&model.sha256), + "duplicate KV fixture artifact identity" + ); + } + ensure!( + manifest.schema_version == 2 && families.len() == 4, + "KV qualification requires one fixture per architecture case" + ); + Ok(manifest) + } +} + +impl KvFixture { + fn validate(&self) -> Result<()> { + let (owner, repo) = self + .repo + .split_once('/') + .context("repository requires an owner")?; + ensure!( + identifier(owner) && identifier(repo) && valid_digest(&self.revision, 40), + "expected an immutable repository revision" + ); + ensure!( + safe_filename(&self.file) + && self + .file + .ends_with(&format!("-{}.gguf", self.quantization.as_str())) + && (!matches!(self.quantization, KvFixtureQuantization::Q4Km) + || !self.file.ends_with("-UD-Q4_K_M.gguf")) + && gguf_matches_quant_selector(&self.file, self.quantization.as_str()), + "GGUF filename must match the declared quantization" + ); + ensure!( + valid_digest(&self.sha256, 64) && valid_digest(&self.chat_template_sha256, 64), + "artifact and chat template require SHA-256 digests" + ); + ensure!( + self.size_bytes > 0 + && self.layers > 0 + && identifier(&self.architecture) + && identifier(&self.license), + "layout and model license must be declared" + ); + let mut files = BTreeSet::from([self.file.as_str()]); + for sidecar in &self.required_sidecars { + ensure!( + safe_filename(&sidecar.file) + && files.insert(&sidecar.file) + && sidecar.size_bytes > 0 + && valid_digest(&sidecar.sha256, 64), + "sidecar filename, length, or SHA-256 is invalid or duplicated" + ); + } + Ok(()) + } +} + +pub fn valid_sha256(value: &str) -> bool { + valid_digest(value, 64) +} + +fn valid_digest(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + && value.bytes().any(|byte| byte != b'0') +} + +fn identifier(value: &str) -> bool { + value + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) +} + +fn safe_filename(value: &str) -> bool { + identifier(value) && !value.ends_with('.') +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-model-artifact/src/kv_fixtures/models.json b/crates/skippy-model-artifact/src/kv_fixtures/models.json new file mode 100644 index 00000000..bfb07d97 --- /dev/null +++ b/crates/skippy-model-artifact/src/kv_fixtures/models.json @@ -0,0 +1,61 @@ +{ + "schema_version": 2, + "models": [ + { + "family": "dense-attention", + "repo": "unsloth/Qwen3-4B-GGUF", + "revision": "22c9fc8a8c7700b76a1789366280a6a5a1ad1120", + "file": "Qwen3-4B-Q4_K_M.gguf", + "quantization": "Q4_K_M", + "size_bytes": 2497281312, + "sha256": "f6f851777709861056efcdad3af01da38b31223a3ba26e61a4f8bf3a2195813a", + "chat_template_sha256": "5da44855ab7e0641774d5ed0ff0b4f89671d01df7d316e54d06557a962211cb4", + "license": "Apache-2.0", + "architecture": "qwen3", + "layers": 36, + "required_sidecars": [] + }, + { + "family": "hybrid-dense", + "repo": "unsloth/Qwen3.5-4B-GGUF", + "revision": "e87f176479d0855a907a41277aca2f8ee7a09523", + "file": "Qwen3.5-4B-Q4_K_M.gguf", + "quantization": "Q4_K_M", + "size_bytes": 2740937888, + "sha256": "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4", + "chat_template_sha256": "7f0e529032c25183bcd66c7f238da2d377f43be754a94e2725a58c4e16d2ed67", + "license": "Apache-2.0", + "architecture": "qwen35", + "layers": 32, + "required_sidecars": [] + }, + { + "family": "attention-moe", + "repo": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", + "revision": "b17cb02dd882d5b6ab62fc777ad2995f19668350", + "file": "Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf", + "quantization": "Q4_K_M", + "size_bytes": 18556689568, + "sha256": "fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad", + "chat_template_sha256": "87710339d25b4e789c1d723f93c91ee861a86d305bb3d20a845536f251d6ea8a", + "license": "Apache-2.0", + "architecture": "qwen3moe", + "layers": 48, + "required_sidecars": [] + }, + { + "family": "hybrid-moe", + "repo": "unsloth/Qwen3.6-35B-A3B-GGUF", + "revision": "a483e9e6cbd595906af30beda3187c2663a1118c", + "file": "Qwen3.6-35B-A3B-UD-Q4_K_M.gguf", + "quantization": "UD-Q4_K_M", + "size_bytes": 22134528992, + "sha256": "ac0e2c1189e055faa36eff361580e79c5bd6f8e76bffb4ce547f167d53e31a61", + "chat_template_sha256": "55d4931433fe502b794226ee7f4d206a6bdd436ac9f80eb7d8ebb4c639f9ea0c", + "license": "Apache-2.0", + "architecture": "qwen35moe", + "layers": 40, + "required_sidecars": [] + } + ] +} diff --git a/crates/skippy-model-artifact/src/kv_fixtures/tests.rs b/crates/skippy-model-artifact/src/kv_fixtures/tests.rs new file mode 100644 index 00000000..a1efdc1c --- /dev/null +++ b/crates/skippy-model-artifact/src/kv_fixtures/tests.rs @@ -0,0 +1,33 @@ +use super::*; +use serde_json::{Value, json}; + +#[test] +fn kv_fixtures_require_complete_distinct_immutable_identities() { + let manifest = KvFixtureManifest::bundled().unwrap(); + assert_eq!(manifest.models.len(), 4); + let source: Value = serde_json::from_str(KV_FIXTURE_MANIFEST).unwrap(); + for (field, bad) in [ + ("revision", json!("main")), + ("sha256", json!("0".repeat(64))), + ("chat_template_sha256", Value::Null), + ("quantization", json!("Q5_K_M")), + ( + "required_sidecars", + json!([{"file":"mtp.gguf", "size_bytes":12}]), + ), + ("file", json!("../model-Q4_K_M.gguf")), + ] { + let mut modified = source.clone(); + modified["models"][0][field] = bad; + assert!( + KvFixtureManifest::parse(&modified.to_string()).is_err(), + "accepted {field}" + ); + } + let mut modified = source.clone(); + modified["models"][1]["sha256"] = source["models"][0]["sha256"].clone(); + assert!(KvFixtureManifest::parse(&modified.to_string()).is_err()); + let mut modified = source; + modified["models"][3]["quantization"] = json!("Q4_K_M"); + assert!(KvFixtureManifest::parse(&modified.to_string()).is_err()); +} diff --git a/crates/skippy-model-artifact/src/lib.rs b/crates/skippy-model-artifact/src/lib.rs index 4c65a74f..e5c8166d 100644 --- a/crates/skippy-model-artifact/src/lib.rs +++ b/crates/skippy-model-artifact/src/lib.rs @@ -3,6 +3,7 @@ pub mod sizes; pub mod checkpoint; pub mod gguf; +pub mod kv_fixtures; pub mod selection; use std::path::Path; diff --git a/crates/skippy-protocol/README.md b/crates/skippy-protocol/README.md index 1b2c8e11..7d1e6d06 100644 --- a/crates/skippy-protocol/README.md +++ b/crates/skippy-protocol/README.md @@ -62,16 +62,11 @@ DFlash status lists the encodings it reads (`bf16`, `q8`, `q4`), and the DFlash plan sent to every earlier stage names the one they send. A final stage that lists none attaches no split DFlash. -Generation 17 removes the obsolete family-certification fields from load and -status messages. It uses a 64 MiB stage frame budget, so a +Generation 16 raised the stage frame budget from 8 MiB to 64 MiB, so a prefill chunk of a wide boundary crosses as one frame; a chunk whose output still exceeds the budget is sent as consecutive prefill frames. -Generation 18 keeps node-local paths and endpoint addresses out of load, -topology, and neighbour descriptors. Status and inventory carry source -identities without local paths. The receiver resolves its own files and -selects its own listening address. All participants must advertise -`stage-generation-18`; older peers fail closed. +Generation 19 combines node-local load, topology, and neighbour descriptors with request-tier and private-cache claims. The receiver resolves its own files and listening address. Wire header version 18 carries the request tier in bits 17–18 and private-cache isolation in bit 19. A stage lowers the tier to its host-assigned `StageConfig.max_request_tier` before partitioning the cache. All participants advertise `stage-generation-19`. Admission requires mesh-subprotocol control, list-valued status responses, strict local-content identity, canonical stage-admission descriptors, and stale diff --git a/crates/skippy-protocol/src/binary/types.rs b/crates/skippy-protocol/src/binary/types.rs index f5d323b8..834c1845 100644 --- a/crates/skippy-protocol/src/binary/types.rs +++ b/crates/skippy-protocol/src/binary/types.rs @@ -5,8 +5,9 @@ use crate::StageActivationCodec; use super::invalid_data; // v17 adds unsampled prefill readouts and bounded selected-score replies. +// v18 adds the request tier and private-partition flags on stage messages. // Stage peers must be upgraded together; the Mesh gossip envelope stays additive. -pub const STAGE_STATE_VERSION: i32 = 17; +pub const STAGE_STATE_VERSION: i32 = 18; pub const MAX_STAGE_LOGIT_BIAS: usize = 256; pub const MAX_STAGE_SAMPLERS: usize = 16; pub const MAX_STAGE_DRY_SEQUENCE_BREAKERS: usize = 8; @@ -219,6 +220,14 @@ pub mod state_flags { /// attention window. Stages forward no DFlash feature rows for them, and /// the draft does not ingest them; its context starts after them. pub const SPLIT_DFLASH_UNATTENDED_ROWS: i32 = 1 << 16; + /// Bits 17..=18: how many tiers below `local` the request is served at + /// (0 local, 1 trusted, 2 mesh; 3 is read as mesh). A stage caps this at + /// its own classification of the coordinator, partitions its caches by + /// it, and evicts lower tiers first. + pub const REQUEST_TIER_DEMOTION_SHIFT: u32 = 17; + pub const REQUEST_TIER_DEMOTION_MASK: i32 = 0x3 << REQUEST_TIER_DEMOTION_SHIFT; + /// The request uses the private cache partition of its tier. + pub const PRIVATE_CACHE_PARTITION: i32 = 1 << 19; } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -424,6 +433,34 @@ impl StageStateHeader { | state_flags::NATIVE_MTP_DRAFT_TOKENS_SET; } + /// How many tiers below `local` the request is served at: 0 local, + /// 1 trusted, 2 mesh. The unused value 3 reads as mesh. + pub fn request_tier_demotion(self) -> u8 { + let value = (self.flags & state_flags::REQUEST_TIER_DEMOTION_MASK) + >> state_flags::REQUEST_TIER_DEMOTION_SHIFT; + (value as u8).min(2) + } + + /// Stamp the request tier as tiers below `local`, saturating at mesh. + pub fn set_request_tier_demotion(&mut self, demotion: u8) { + let value = i32::from(demotion.min(2)); + self.flags = (self.flags & !state_flags::REQUEST_TIER_DEMOTION_MASK) + | (value << state_flags::REQUEST_TIER_DEMOTION_SHIFT); + } + + /// Whether the request uses its tier's private cache partition. + pub fn private_cache_partition(self) -> bool { + self.flags & state_flags::PRIVATE_CACHE_PARTITION != 0 + } + + pub fn set_private_cache_partition(&mut self, private: bool) { + if private { + self.flags |= state_flags::PRIVATE_CACHE_PARTITION; + } else { + self.flags &= !state_flags::PRIVATE_CACHE_PARTITION; + } + } + /// Whether the sender accepts drafts that follow a rejected window's correction. pub fn accepts_native_mtp_draft_after_correction(self) -> bool { self.flags & state_flags::NATIVE_MTP_DRAFT_AFTER_CORRECTION != 0 diff --git a/crates/skippy-protocol/src/config.rs b/crates/skippy-protocol/src/config.rs index 2577d58a..2c9971cb 100644 --- a/crates/skippy-protocol/src/config.rs +++ b/crates/skippy-protocol/src/config.rs @@ -1,7 +1,7 @@ //! Stage configuration, topology, and activation contracts. use serde::{Deserialize, Deserializer, Serialize, de}; -use std::num::NonZeroU32; +use std::num::{NonZeroU32, NonZeroU64}; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub struct StageIdentity { pub run_id: String, @@ -570,6 +570,12 @@ pub struct StageConfig { pub upstream: Option, #[serde(default)] pub downstream: Option, + /// The highest request tier (`local`, `trusted` or `mesh`) this stage + /// serves. The host sets it from its own classification of the node that + /// loaded the stage; a wire claim above it is lowered to it. `None` means + /// `local`: the stage trusts the tier its coordinator stamps. + #[serde(default)] + pub max_request_tier: Option, } impl StageConfig { @@ -647,12 +653,13 @@ pub struct StageKvCacheConfig { pub max_entries: usize, #[serde(default)] pub max_bytes: u64, - /// 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. + /// Host-RAM byte budget for the L2 mirror. Zero disables the mirror. #[serde(default)] pub l2_max_bytes: u64, + /// Host-RAM byte limit for resident recurrent checkpoints and metadata. + /// When unset, the runtime uses its bounded resident default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub l1_checkpoint_max_bytes: Option, /// Exact-state retention ceiling; None derives eight times max_bytes. /// One indivisible snapshot may exceed it. Some(0) disables the ceiling. #[serde(default)] diff --git a/crates/skippy-protocol/src/lib.rs b/crates/skippy-protocol/src/lib.rs index 9123e65e..49c6a7d8 100644 --- a/crates/skippy-protocol/src/lib.rs +++ b/crates/skippy-protocol/src/lib.rs @@ -43,7 +43,7 @@ pub use validation::{ STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1, STAGE_SUBPROTOCOL_FEATURE_PERSISTENT_LANE_MARKER, STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL, STAGE_SUBPROTOCOL_FEATURE_STAGE_GENERATION, - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V19, STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST, STAGE_SUBPROTOCOL_MAJOR, STAGE_SUBPROTOCOL_NAME, StageFrameError, validate_stage_admission_descriptor, validate_stage_artifact_transfer_request, validate_stage_artifact_transfer_response, validate_stage_control_request, @@ -304,7 +304,7 @@ mod tests { ); } use super::{ - STAGE_PROTOCOL_GENERATION, STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, + STAGE_PROTOCOL_GENERATION, STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V19, StageFrameError, validate_stage_admission_descriptor, validate_stage_artifact_transfer_request, validate_stage_artifact_transfer_response, validate_stage_control_request, validate_stage_control_response, @@ -315,7 +315,7 @@ mod tests { #[test] fn stage_protocol_generation_feature_names_current_generation() { assert_eq!( - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18, + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V19, format!("stage-generation-{STAGE_PROTOCOL_GENERATION}") ); } diff --git a/crates/skippy-protocol/src/validation.rs b/crates/skippy-protocol/src/validation.rs index 5989b802..829b1528 100644 --- a/crates/skippy-protocol/src/validation.rs +++ b/crates/skippy-protocol/src/validation.rs @@ -10,13 +10,13 @@ pub const STAGE_SUBPROTOCOL_NAME: &str = "skippy-stage"; pub const STAGE_SUBPROTOCOL_MAJOR: u32 = 2; pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_CONTROL: &str = "stage-control"; pub const STAGE_SUBPROTOCOL_FEATURE_PERSISTENT_LANE_MARKER: &str = "persistent-lane-marker"; -pub const STAGE_PROTOCOL_GENERATION: u32 = 18; +pub const STAGE_PROTOCOL_GENERATION: u32 = 19; /// Generation-scoped stage capability. A peer can advertise `stage-control` /// while still rejecting current-generation frames, so split planning gates on /// this exact token before sending current-generation control requests. -pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18: &str = "stage-generation-18"; +pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V19: &str = "stage-generation-19"; pub const STAGE_SUBPROTOCOL_FEATURE_STAGE_GENERATION: &str = - STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V18; + STAGE_SUBPROTOCOL_FEATURE_STAGE_PROTOCOL_GENERATION_V19; pub const STAGE_SUBPROTOCOL_FEATURE_ARTIFACT_TRANSFER: &str = "artifact-transfer"; pub const STAGE_SUBPROTOCOL_FEATURE_STATUS_LIST: &str = "status-list"; pub const STAGE_SUBPROTOCOL_FEATURE_LOCAL_GGUF_CONTENT_ID_V1: &str = "local-gguf-content-id-v1"; diff --git a/crates/skippy-runtime/README.md b/crates/skippy-runtime/README.md index 4cfc711b..06364a71 100644 --- a/crates/skippy-runtime/README.md +++ b/crates/skippy-runtime/README.md @@ -11,6 +11,65 @@ into typed runtime structures. diagnostic prompt clients, benchmarks, correctness checks, and slicing tools. It does not own TCP transport, mesh lifecycle, or telemetry export. +### Experimental draft readout + +`SKIPPY_DFLASH_GPU_READOUT=1` attaches stateless greedy backend samplers to +DFlash/DSpark draft lanes. Supported backends select token IDs on the device, +but the current native greedy sampler also retains its logits output, so this +does not eliminate vocabulary-sized readback. Missing optional sampler exports, +refused attachments, or a backend returning processed logits retain host +argmax. DFlash2 continues to read its selector lattice. The target sampler and +verification semantics are unchanged. + +`SKIPPY_DFLASH_DEVICE_FEATURES=1` enables direct device-row feature injection +for a complete local target with strictly ordered capture layers. The draft +consumes the capture buffer before the next target forward; upstream device +events protect its lifetime. Unsupported layouts or missing optional exports +keep the host feature path. Native graph admission validates auxiliary capture writes. Both optimizations +remain opt-in pending repeatable end-to-end gains. + +`StageSession::verify_batch_sampled` accepts requests from +`verification_batch::VerifyBatchRequest` and shares a target forward across +equal-length speculative windows. Each lane retains its own sampling history, +checkpoint and rejection boundary. Callers must resolve every window through +trim or retirement. The concurrent DFlash diagnostic exercises this API. +Serving coalesces compatible windows by default; +`SKIPPY_SHARED_VERIFY=0` retains independent submissions for diagnostics. +See the serving crate's README. + +`StageSession::dflash_propose_batch` accepts +`dflash::proposal_batch::DFlashBatchRequest` values. Compatible lanes share +one noise-block forward, including different requested block lengths. Each +lane keeps its own feature context, and every scratch block is removed after +readout. Batches exceeding native capacity and lanes using separate draft +models retain independent submissions. Draft failure clears the +affected draft contexts and returns empty proposals without changing target +state. `DFlashDraftStats::shared_proposals` counts observed shared submissions. + +Selector and convolution heads group noise rows into one block per sequence. +They can share a forward when the actual block widths are equal; differing +widths fall back to independent forwards before any draft state changes. +Heads with independent rows retain ragged batching. Markov heads remain +independent. Capacity and duplicate-sequence checks apply to every layout. + +The optional real-checkpoint isolation proof compares independent and shared +selector proposals, reverses lane order, checks scratch removal, and exercises +ragged fallback. It requires local GGUF paths and a packaged Metal runtime: + +```sh +SKIPPY_DRAFT_LAYOUT_TARGET_MODEL=/path/to/target.gguf \ +SKIPPY_DRAFT_LAYOUT_DRAFT_MODEL=/path/to/selector-draft.gguf \ +SKIPPY_NATIVE_RUNTIME_BUNDLE_DIR="$PWD/dist/native-runtimes" \ +just with-lld cargo test -p skippy-runtime --features dynamic-native-runtime \ + --lib selector_noise_blocks_match_independent_lanes_and_remove_scratch -- --ignored +``` + +The default remains host readout until matched parity and performance trials +qualify the backend path. `StageModel::dflash_backend_readout_rows` distinguishes +observed token rows from host fallbacks; attachment alone is not evidence of +offload. Compare `llama-spec-bench --dflash` with the variable unset and set to +`1`, using the same models, prompt corpus, draft window and native build. + ```mermaid flowchart TB Host["embedding application
embedded serving + lifecycle"] --> R["skippy-runtime"] diff --git a/crates/skippy-runtime/src/dflash.rs b/crates/skippy-runtime/src/dflash.rs index e363d225..fbc2585e 100644 --- a/crates/skippy-runtime/src/dflash.rs +++ b/crates/skippy-runtime/src/dflash.rs @@ -13,9 +13,17 @@ //! than through the Skippy model ABI. Draft state is advisory: a failed draft //! operation clears that lane's draft cache and never fails the target. +mod backend_readout; mod context; +mod device_features; mod draft_batch; +mod draft_tensors; mod feature_wire; +#[cfg(test)] +mod head_isolation_tests; +mod heads; +mod noise_blocks; +pub mod proposal_batch; mod readout; mod split; @@ -37,6 +45,8 @@ use crate::{RuntimeConfig, StageModel, StageSession, ensure_ok, write_native_log use context::{DraftContext, IngestPlan}; use draft_batch::{DraftBatch, target_feature_row}; +use draft_tensors::{DraftTensors, inspect_draft_tensors}; +use noise_blocks::NoiseBlock; use readout::{BlockLayout, argmax_token, walk_dflash2_lattice}; #[cfg(target_os = "macos")] use skippy_ane::dflash::AneDraft; @@ -114,6 +124,7 @@ pub struct DFlashProposal { pub tokens: Vec, /// Draft time for this block: the block decode, plus the feature rows of /// the last decode when their injection was deferred to it. + /// A shared forward charges each active block an equal share of its time. pub proposal_compute_us: u64, } @@ -124,6 +135,8 @@ pub struct DFlashProposal { pub struct DFlashDraftStats { /// Block drafts, including empty ones from a draft without context. pub proposals: u64, + /// Proposals whose noise block shared a forward with another lane. + pub shared_proposals: u64, /// Time in block decodes. pub propose_us: u64, /// Feature injections of decode rows, and the time they took. @@ -172,7 +185,10 @@ pub(crate) struct DFlashDraft { mask_token: i32, mrope: bool, layout: BlockLayout, + noise_batch_layout: heads::NoiseBatchLayout, batch: DraftBatch, + backend_readout: Option, + device_features: Option, #[cfg(target_os = "macos")] ane: Option, } @@ -232,19 +248,15 @@ impl DFlashDraft { mask_token: -1, mrope: false, layout: BlockLayout::BonusAnchor, + noise_batch_layout: heads::NoiseBatchLayout::Independent, batch: DraftBatch::default(), + backend_readout: None, + device_features: None, #[cfg(target_os = "macos")] ane: None, }; // From here the Drop impl owns the native handles. - draft.configure( - target_model, - options, - config, - tensors.markov, - path, - target_path, - )?; + draft.configure(target_model, options, config, &tensors, path, target_path)?; Ok(draft) } @@ -253,7 +265,7 @@ impl DFlashDraft { target_model: *const Opaque, options: &DFlashDraftOptions, config: &RuntimeConfig, - markov: bool, + tensors: &DraftTensors, draft_path: &Path, target_path: Option<&Path>, ) -> Result<()> { @@ -338,7 +350,7 @@ impl DFlashDraft { self.info.block_size ); } - self.select_variant(markov)?; + self.select_variant(tensors)?; self.info.max_draft_tokens = self.layout.capacity( self.info.block_size, options.max_draft_tokens.unwrap_or(usize::MAX), @@ -356,7 +368,7 @@ impl DFlashDraft { #[cfg(not(target_os = "macos"))] let use_native_context = true; if use_native_context { - self.configure_native_context(config, causal)?; + self.configure_native_context(options, config, causal)?; } unsafe { for (&lid, &local) in self.info.target_layer_ids.iter().zip(&self.local_layers) { @@ -365,6 +377,33 @@ impl DFlashDraft { } } } + if device_features::enabled() + && let Some(ctx) = self.native_ctx + && device_features::eligible( + config.layer_start, + config.layer_end, + target_layers, + &self.local_layers, + &self.info.target_layer_ids, + ) + { + self.device_features = api.device_features.and_then(|device| { + device_features::DeviceFeatures::attach( + device, + self.target_ctx, + ctx.as_ptr(), + device_features::FeatureShape { + ubatch: self.n_ubatch, + capacity: self.target_n_batch, + mrope: self.mrope, + }, + ) + }); + write_native_log_note(format!( + "dflash device features enabled={}", + self.device_features.is_some() + )); + } write_native_log_note(format!( "dflash draft attached variant={} block_size={} max_draft_tokens={} target_layers={:?} local_layers={:?} input_layer={:?} mask_token={} causal={causal} mrope={}", self.info.variant.as_str(), @@ -379,9 +418,24 @@ impl DFlashDraft { Ok(()) } - fn configure_native_context(&mut self, config: &RuntimeConfig, causal: bool) -> Result<()> { + fn configure_native_context( + &mut self, + options: &DFlashDraftOptions, + config: &RuntimeConfig, + causal: bool, + ) -> Result<()> { let api = self.api; - let params = draft_context_params(api, self.target_ctx, config, self.lanes)?; + let mut params = draft_context_params(api, self.target_ctx, config, self.lanes)?; + if backend_readout::enabled() && api.sampling.is_some() { + // Reserve only the allowed noise block, rather than the full prefill + // batch. Anchor-first blocks need no additional row, but reserving it + // is harmless and keeps both layouts within the trained block bound. + params.n_outputs_max_per_seq = options + .max_draft_tokens + .unwrap_or(MAX_BLOCK_SIZE - 1) + .saturating_add(1) + .clamp(1, MAX_BLOCK_SIZE) as u32; + } let ctx = NonNull::new(unsafe { (api.init_from_model)(self.model, params) }) .with_context(|| { format!( @@ -394,6 +448,15 @@ impl DFlashDraft { .context("draft n_ubatch exceeds usize")? .max(1); let dflash2 = self.info.variant == DFlashVariant::DFlash2; + if !dflash2 && backend_readout::enabled() { + self.backend_readout = api.sampling.and_then(|sampling| { + backend_readout::BackendReadout::attach(sampling, ctx.as_ptr(), self.lanes) + }); + write_native_log_note(format!( + "dflash backend readout enabled={}", + self.backend_readout.is_some() + )); + } unsafe { // DFlash2 reads its lattice from every row of the nextn output. (api.set_embeddings_nextn)(ctx.as_ptr(), true, !dflash2); @@ -402,35 +465,6 @@ impl DFlashDraft { Ok(()) } - /// Picks the draft family and its block layout: DSpark when the draft has - /// a Markov head, DFlash2 when it has a selector lattice, else DFlash. - fn select_variant(&mut self, markov: bool) -> Result<()> { - let selector_top_k = unsafe { (self.api.model_dflash_selector_top_k)(self.model) }; - if markov { - if selector_top_k > 0 { - bail!( - "a draft with both a DSpark Markov head and a DFlash2 selector is not supported" - ); - } - self.info.variant = DFlashVariant::DSpark; - let anchor_first = unsafe { - skippy_ffi::llama_model_meta_val_str(self.model, DSPARK_SAMPLE_FROM_ANCHOR_KEY) - } - .is_none_or(|value| value == "true"); - if anchor_first { - self.layout = BlockLayout::AnchorFirst; - } - } else if selector_top_k > 0 { - self.info.variant = DFlashVariant::DFlash2; - self.info.selector_top_k = positive_usize(selector_top_k, "selector top-k")?; - let row_used = self.info.selector_top_k * (self.info.selector_top_k + 1); - if row_used > self.n_embd_draft { - bail!("draft hidden size is too small for the DFlash2 selector lattice"); - } - } - Ok(()) - } - pub(crate) fn info(&self) -> &DFlashDraftInfo { &self.info } @@ -460,6 +494,9 @@ impl DFlashDraft { return ane.ingest(seq_id, &features, positions); } } + if let Some(device) = self.device_features.as_mut() { + return device.ingest(seq_id, first_row, positions); + } let layers = self.feature_layers(first_row, positions.len(), remote)?; let n_embd = self.n_embd_target; self.inject_rows(seq_id, positions, |row| { @@ -614,89 +651,13 @@ impl DFlashDraft { unsafe { (self.api.memory_seq_rm)(memory, seq_id, -1, -1) }; } } - - /// Drafts up to `max_tokens` tokens that follow `anchor`, the token the - /// target will consume next at `anchor_position`. - pub(crate) fn propose( - &mut self, - seq_id: i32, - anchor_position: i32, - anchor: i32, - max_tokens: usize, - ) -> Result> { - let draft_tokens = max_tokens.min(self.info.max_draft_tokens); - if draft_tokens == 0 { - return Ok(Vec::new()); - } - #[cfg(target_os = "macos")] - if let Some(ane) = self.ane.as_mut() { - ane.truncate(seq_id, anchor_position); - return ane.propose(seq_id, anchor_position, anchor, draft_tokens); - } - let ctx = self - .native_ctx - .context("DFlash has no native draft context")?; - let dflash2 = self.info.variant == DFlashVariant::DFlash2; - // Rows a split final stage verified past the anchor are still cached. - self.truncate(seq_id, anchor_position); - // Every block row is an output, as upstream requests: marking only the - // mask rows returns logits shifted by one row. DFlash2 reads its - // lattice from the nextn output instead and needs no logits. A DSpark - // block is never longer than its trained block, past which the draft - // graph leaves out the Markov head. - self.batch.clear(); - for index in 0..self.layout.block_tokens(draft_tokens) { - let token = if index == 0 { anchor } else { self.mask_token }; - let position = anchor_position - .checked_add(i32::try_from(index).context("draft index exceeds i32")?) - .context("draft position overflow")?; - self.batch.push_token(token, position, seq_id, !dflash2); - } - let rc = unsafe { (self.api.decode)(ctx.as_ptr(), self.batch.as_raw(self.mrope)) }; - let tokens = if rc == 0 { - self.read_block(ctx, draft_tokens) - } else { - Err(anyhow!("draft block decode failed with status {rc}")) - }; - // The noise block is scratch; only target features persist. - self.truncate(seq_id, anchor_position); - tokens - } - - fn read_block(&self, ctx: NonNull, draft_tokens: usize) -> Result> { - if self.info.variant == DFlashVariant::DFlash2 { - let lattice = unsafe { (self.api.get_embeddings_nextn)(ctx.as_ptr()) }; - if lattice.is_null() { - bail!("DFlash2 selector produced no lattice"); - } - let rows = draft_tokens + 1; - let lattice = unsafe { - std::slice::from_raw_parts(lattice.cast_const(), rows * self.n_embd_draft) - }; - let draft_rows = lattice.chunks_exact(self.n_embd_draft).skip(1); - return Ok(walk_dflash2_lattice( - draft_rows, - self.info.selector_top_k, - self.n_vocab, - )); - } - let mut tokens = Vec::with_capacity(draft_tokens); - let first = self.layout.first_draft_row(); - for row in first..first + draft_tokens { - let row = i32::try_from(row).context("draft row exceeds i32")?; - let logits = unsafe { (self.api.get_logits_ith)(ctx.as_ptr(), row) }; - if logits.is_null() { - bail!("draft produced no logits for block row {row}"); - } - let logits = unsafe { std::slice::from_raw_parts(logits.cast_const(), self.n_vocab) }; - tokens.push(argmax_token(logits).context("draft logits row is empty")?); - } - Ok(tokens) - } } impl Drop for DFlashDraft { fn drop(&mut self) { + // Detach/free samplers before their borrowed context is destroyed. + self.backend_readout.take(); + self.device_features.take(); unsafe { for (&lid, &local) in self.info.target_layer_ids.iter().zip(&self.local_layers) { if local { @@ -757,25 +718,6 @@ fn lilicorr_headless_enabled_by(value: Option<&str>) -> bool { matches!(value.map(str::trim), Some("1" | "true")) } -/// What a draft's tensors say about how it runs. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct DraftTensors { - /// The draft carries its own token embeddings. - embeds: bool, - /// The draft is a DSpark draft with a Markov head. - markov: bool, -} - -fn inspect_draft_tensors(path: &Path) -> Result { - let catalog = skippy_model::gguf_catalog::read_gguf_tensor_catalog(path) - .with_context(|| format!("read draft GGUF {}", path.display()))?; - let has = |name: &str| catalog.tensors.iter().any(|tensor| tensor.name == name); - Ok(DraftTensors { - embeds: has(DFLASH_BORROWED_TARGET_TENSOR), - markov: has(DSPARK_MARKOV_TENSOR), - }) -} - /// Refuses a runtime whose upstream parameter defaults do not match the /// pinned layout mirrored in `skippy_ffi::llama_draft`. fn validate_default_params(api: &LlamaDraftApi) -> Result<()> { @@ -1379,7 +1321,12 @@ impl StageSession { } }; let remote = remote.as_ref().map(|(rows, consumed)| (rows, *consumed)); - if defer && phase == TargetPhase::Decode && span_count <= MAX_BLOCK_SIZE { + // Device rows borrow the current capture buffer. Consume them now; + // deferred host rows instead own a copy that survives another decode. + let device_rows = link + .with_draft(|draft, _| draft.device_features.is_some()) + .unwrap_or(false); + if defer && !device_rows && phase == TargetPhase::Decode && span_count <= MAX_BLOCK_SIZE { let gathered = link.with_draft(|draft, _| draft.gather_features(first_row, positions, remote)); match gathered { @@ -1602,6 +1549,34 @@ impl StageModel { let draft = self.dflash_draft()?; Some(lock_draft(draft).info().clone()) } + + /// Whether the attached draft uses backend sampling rather than requesting + /// host logits. DFlash2's lattice readout is independent of this path. + pub fn dflash_backend_readout_enabled(&self) -> bool { + self.dflash_draft() + .is_some_and(|draft| lock_draft(draft).backend_readout.is_some()) + } + + /// Observed backend token rows and rows that fell back to host logits for + /// the attached draft's lifetime. Attachment alone does not prove offload. + pub fn dflash_backend_readout_rows(&self) -> (u64, u64) { + self.dflash_draft().map_or((0, 0), |draft| { + lock_draft(draft) + .backend_readout + .as_ref() + .map_or((0, 0), backend_readout::BackendReadout::rows) + }) + } + + /// Feature rows consumed directly from the target's device capture buffer. + pub fn dflash_device_feature_rows(&self) -> u64 { + self.dflash_draft().map_or(0, |draft| { + lock_draft(draft) + .device_features + .as_ref() + .map_or(0, device_features::DeviceFeatures::rows) + }) + } } /// Reinstalls a stage program after layer capture changed the target's @@ -1770,53 +1745,6 @@ mod tests { assert_eq!(missing_borrowed_tensor(&with_embeddings), None); } - /// A GGUF holding one-float tensors named `names`. - fn gguf_with_tensors(names: &[&str]) -> tempfile::NamedTempFile { - use std::io::Write; - let mut bytes = b"GGUF".to_vec(); - bytes.extend_from_slice(&3u32.to_le_bytes()); - bytes.extend_from_slice(&(names.len() as u64).to_le_bytes()); - bytes.extend_from_slice(&0u64.to_le_bytes()); - for (index, name) in names.iter().enumerate() { - bytes.extend_from_slice(&(name.len() as u64).to_le_bytes()); - bytes.extend_from_slice(name.as_bytes()); - bytes.extend_from_slice(&1u32.to_le_bytes()); - bytes.extend_from_slice(&1u64.to_le_bytes()); - bytes.extend_from_slice(&0u32.to_le_bytes()); // f32 - bytes.extend_from_slice(&(32 * index as u64).to_le_bytes()); - } - bytes.resize(bytes.len().next_multiple_of(32), 0); - bytes.resize(bytes.len() + 32 * names.len(), 0); - let mut file = tempfile::NamedTempFile::new().unwrap(); - file.write_all(&bytes).unwrap(); - file - } - - #[test] - fn a_markov_head_marks_a_dspark_draft() { - let dflash = gguf_with_tensors(&["blk.0.attn_q.weight", "fc.weight"]); - assert_eq!( - inspect_draft_tensors(dflash.path()).unwrap(), - DraftTensors { - embeds: false, - markov: false - } - ); - let dspark = gguf_with_tensors(&[ - "blk.0.attn_q.weight", - "token_embd.weight", - "markov_w1.weight", - "markov_w2.weight", - ]); - assert_eq!( - inspect_draft_tensors(dspark.path()).unwrap(), - DraftTensors { - embeds: true, - markov: true - } - ); - } - #[test] fn a_lilicorr_draft_runs_headless_only_when_asked() { for (value, enabled) in [ diff --git a/crates/skippy-runtime/src/dflash/backend_readout.rs b/crates/skippy-runtime/src/dflash/backend_readout.rs new file mode 100644 index 00000000..86a04990 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/backend_readout.rs @@ -0,0 +1,186 @@ +//! Owns the stateless greedy chains attached to a draft context. + +use std::{cell::Cell, ptr}; + +use anyhow::{Result, bail}; +use skippy_ffi::Opaque; +use skippy_ffi::llama_draft::LlamaDraftSamplingApi; + +pub(super) struct BackendReadout { + api: LlamaDraftSamplingApi, + ctx: *mut Opaque, + samplers: Vec<*mut Opaque>, + token_rows: Cell, + fallback_rows: Cell, +} + +impl BackendReadout { + /// The context must outlive the readout. Each chain is initialized exactly + /// once; resetting a draft's KV does not detach or reattach its sampler. + pub(super) fn attach(api: LlamaDraftSamplingApi, ctx: *mut Opaque, lanes: i32) -> Option { + let mut readout = Self { + api, + ctx, + samplers: Vec::new(), + token_rows: Cell::new(0), + fallback_rows: Cell::new(0), + }; + for seq in 0..lanes { + unsafe { + let chain = (api.chain_init)((api.chain_default_params)()); + if chain.is_null() { + return None; + } + let greedy = (api.init_greedy)(); + if greedy.is_null() { + (api.free)(chain); + return None; + } + (api.chain_add)(chain, greedy); + readout.samplers.push(chain); + if !(api.set_sampler)(ctx, seq, chain) { + return None; + } + } + } + Some(readout) + } + + pub(super) fn token(&self, row: i32, n_vocab: usize) -> Result> { + let token = unsafe { (self.api.get_token)(self.ctx, row) }; + // Upstream can attach a chain whose backend prefix is empty. In that + // case it returns processed logits instead of a sampled token, and its + // logits getter supplies those rows to the existing CPU argmax path. + if token == -1 { + self.fallback_rows + .set(self.fallback_rows.get().saturating_add(1)); + return Ok(None); + } + if usize::try_from(token) + .ok() + .is_none_or(|token| token >= n_vocab) + { + bail!("draft backend returned an invalid token for row {row}"); + } + self.token_rows.set(self.token_rows.get().saturating_add(1)); + Ok(Some(token)) + } + + pub(super) fn rows(&self) -> (u64, u64) { + (self.token_rows.get(), self.fallback_rows.get()) + } +} + +impl Drop for BackendReadout { + fn drop(&mut self) { + for (seq, sampler) in self.samplers.iter().enumerate() { + unsafe { + (self.api.set_sampler)(self.ctx, seq as i32, ptr::null_mut()); + (self.api.free)(*sampler); + } + } + } +} + +/// Keep host readout available for matched benchmarks and backends where +/// sampling dispatch overhead outweighs the vocabulary transfer saved. +pub(super) fn enabled() -> bool { + std::env::var("SKIPPY_DFLASH_GPU_READOUT").as_deref() == Ok("1") +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_ffi::llama_draft::LlamaSamplerChainParams; + + struct Context { + attached: Vec<*mut Opaque>, + reject: Option, + tokens: Vec, + } + + struct Chain { + greedy: *mut u8, + } + + unsafe extern "C" fn defaults() -> LlamaSamplerChainParams { + LlamaSamplerChainParams { no_perf: true } + } + + unsafe extern "C" fn chain_init(_: LlamaSamplerChainParams) -> *mut Opaque { + Box::into_raw(Box::new(Chain { + greedy: ptr::null_mut(), + })) + .cast() + } + + unsafe extern "C" fn greedy() -> *mut Opaque { + Box::into_raw(Box::new(0u8)).cast() + } + + unsafe extern "C" fn add(chain: *mut Opaque, greedy: *mut Opaque) { + unsafe { (*chain.cast::()).greedy = greedy.cast() }; + } + + unsafe extern "C" fn free(chain: *mut Opaque) { + let chain = unsafe { Box::from_raw(chain.cast::()) }; + if !chain.greedy.is_null() { + drop(unsafe { Box::from_raw(chain.greedy) }); + } + } + + unsafe extern "C" fn set(ctx: *mut Opaque, seq: i32, chain: *mut Opaque) -> bool { + let ctx = unsafe { &mut *ctx.cast::() }; + if !chain.is_null() && ctx.reject == Some(seq) { + return false; + } + ctx.attached[seq as usize] = chain; + true + } + + unsafe extern "C" fn token(ctx: *mut Opaque, row: i32) -> i32 { + let ctx = unsafe { &*ctx.cast::() }; + ctx.tokens.get(row as usize).copied().unwrap_or(-1) + } + + fn api() -> LlamaDraftSamplingApi { + LlamaDraftSamplingApi { + chain_default_params: defaults, + chain_init, + chain_add: add, + init_greedy: greedy, + free, + set_sampler: set, + get_token: token, + } + } + + #[test] + fn reads_each_block_row_and_detaches_every_lane() { + let mut ctx = Context { + attached: vec![ptr::null_mut(); 2], + reject: None, + tokens: vec![5, 8, 9, -1, 10], + }; + let readout = BackendReadout::attach(api(), (&raw mut ctx).cast(), 2).unwrap(); + assert!(ctx.attached.iter().all(|p| !p.is_null())); + assert_eq!(readout.token(1, 10).unwrap(), Some(8)); + assert_eq!(readout.token(2, 10).unwrap(), Some(9)); + assert_eq!(readout.token(3, 10).unwrap(), None); + assert!(readout.token(4, 10).is_err()); + assert_eq!(readout.rows(), (2, 1)); + drop(readout); + assert!(ctx.attached.iter().all(|p| p.is_null())); + } + + #[test] + fn partial_backend_refusal_detaches_previously_attached_lanes() { + let mut ctx = Context { + attached: vec![ptr::null_mut(); 2], + reject: Some(1), + tokens: vec![], + }; + assert!(BackendReadout::attach(api(), (&raw mut ctx).cast(), 2).is_none()); + assert!(ctx.attached.iter().all(|p| p.is_null())); + } +} diff --git a/crates/skippy-runtime/src/dflash/device_features.rs b/crates/skippy-runtime/src/dflash/device_features.rs new file mode 100644 index 00000000..f2e1d394 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/device_features.rs @@ -0,0 +1,257 @@ +//! Device-owned target capture rows, consumed before the next target decode. +use anyhow::{Context, Result, bail}; +use skippy_ffi::{ + Opaque, + llama_draft::{LlamaDraftDeviceApi, LlamaProcessType}, +}; + +pub(super) struct DeviceFeatures { + api: LlamaDraftDeviceApi, + target: *mut Opaque, + draft: *mut Opaque, + batch: *mut Opaque, + rows: u64, + shape: FeatureShape, +} + +#[derive(Clone, Copy)] +pub(super) struct FeatureShape { + pub(super) ubatch: usize, + pub(super) capacity: usize, + pub(super) mrope: bool, +} + +impl DeviceFeatures { + pub(super) fn attach( + api: LlamaDraftDeviceApi, + target: *mut Opaque, + draft: *mut Opaque, + shape: FeatureShape, + ) -> Option { + unsafe { + (api.set_capture)(target, true); + if !(api.supports_rows)(draft) { + (api.set_capture)(target, false); + return None; + } + let batch = (api.batch_init)(draft); + if batch.is_null() { + (api.set_capture)(target, false); + return None; + } + Some(Self { + api, + target, + draft, + batch, + rows: 0, + shape, + }) + } + } + + pub(super) fn ingest(&mut self, seq: i32, first: usize, positions: &[i32]) -> Result<()> { + let FeatureShape { + ubatch, + capacity, + mrope, + } = self.shape; + if first + .checked_add(positions.len()) + .is_none_or(|end| end > capacity) + { + bail!("draft device features exceed the target capture buffer"); + } + for (chunk, positions) in positions.chunks(ubatch.max(1)).enumerate() { + unsafe { (self.api.batch_clear)(self.batch) }; + for (offset, &position) in positions.iter().enumerate() { + let row = first + chunk * ubatch.max(1) + offset; + let row = i32::try_from(row).context("draft feature row exceeds i32")?; + let idx = unsafe { (self.api.add_row)(self.batch, seq, row) }; + if idx < 0 { + bail!("draft device feature row refused: {idx}"); + } + let axes = if mrope { + [position, position, position, 0] + } else { + [position, 0, 0, 0] + }; + if !unsafe { (self.api.set_pos)(self.batch, idx, axes.as_ptr()) } + || !unsafe { (self.api.set_output)(self.batch, idx, false) } + { + bail!("draft device feature position/output refused"); + } + } + let rc = + unsafe { (self.api.process)(self.draft, LlamaProcessType::Decode, self.batch) }; + if rc != 0 { + bail!("draft device feature injection failed: {rc}"); + } + self.rows = self.rows.saturating_add(positions.len() as u64); + } + Ok(()) + } + + pub(super) fn rows(&self) -> u64 { + self.rows + } +} + +impl Drop for DeviceFeatures { + fn drop(&mut self) { + unsafe { + // The target buffer must outlive all queued draft reads. + (self.api.synchronize)(self.draft); + (self.api.batch_free)(self.batch); + (self.api.set_capture)(self.target, false); + } + } +} + +pub(super) fn eligible( + start: u32, + end: u32, + target_layers: i32, + local: &[bool], + ids: &[u32], +) -> bool { + start == 0 + && i32::try_from(end).is_ok_and(|end| end >= target_layers) + && !ids.is_empty() + && local.len() == ids.len() + && local.iter().all(|local| *local) + && ids.windows(2).all(|ids| ids[0] < ids[1]) +} + +pub(super) fn enabled() -> bool { + std::env::var("SKIPPY_DFLASH_DEVICE_FEATURES").as_deref() == Ok("1") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Fixture { + capture: bool, + supported: bool, + batch_live: bool, + rows: Vec, + positions: Vec<[i32; 4]>, + consumed: Vec<(i32, [i32; 4])>, + calls: usize, + waits: usize, + } + unsafe extern "C" fn capture(ctx: *mut Opaque, enabled: bool) { + unsafe { (*ctx.cast::()).capture = enabled }; + } + unsafe extern "C" fn supported(ctx: *const Opaque) -> bool { + unsafe { (*ctx.cast::()).supported } + } + unsafe extern "C" fn init(ctx: *mut Opaque) -> *mut Opaque { + unsafe { (*ctx.cast::()).batch_live = true }; + ctx + } + unsafe extern "C" fn free(ctx: *mut Opaque) { + unsafe { (*ctx.cast::()).batch_live = false }; + } + unsafe extern "C" fn clear(ctx: *mut Opaque) { + let ctx = unsafe { &mut *ctx.cast::() }; + ctx.rows.clear(); + ctx.positions.clear(); + } + unsafe extern "C" fn add(ctx: *mut Opaque, seq: i32, row: i32) -> i32 { + assert_eq!(seq, 1); + let ctx = unsafe { &mut *ctx.cast::() }; + let idx = ctx.rows.len() as i32; + ctx.rows.push(row); + ctx.positions.push([0; 4]); + idx + } + unsafe extern "C" fn pos(ctx: *mut Opaque, idx: i32, axes: *const i32) -> bool { + let ctx = unsafe { &mut *ctx.cast::() }; + ctx.positions[idx as usize] = unsafe { *axes.cast::<[i32; 4]>() }; + true + } + unsafe extern "C" fn output(_: *mut Opaque, _: i32, enabled: bool) -> bool { + assert!(!enabled); + true + } + unsafe extern "C" fn process(ctx: *mut Opaque, mode: LlamaProcessType, _: *mut Opaque) -> i32 { + assert_eq!(mode, LlamaProcessType::Decode); + let ctx = unsafe { &mut *ctx.cast::() }; + ctx.calls += 1; + ctx.consumed + .extend(ctx.rows.iter().copied().zip(ctx.positions.iter().copied())); + 0 + } + unsafe extern "C" fn sync(ctx: *mut Opaque) { + unsafe { (*ctx.cast::()).waits += 1 }; + } + fn api() -> LlamaDraftDeviceApi { + LlamaDraftDeviceApi { + set_capture: capture, + supports_rows: supported, + batch_init: init, + batch_free: free, + batch_clear: clear, + add_row: add, + set_pos: pos, + set_output: output, + process, + synchronize: sync, + } + } + fn shape() -> FeatureShape { + FeatureShape { + ubatch: 2, + capacity: 10, + mrope: true, + } + } + + #[test] + fn device_rows_preserve_offsets_positions_and_reader_lifetime() { + let mut fixture = Fixture { + supported: true, + ..Default::default() + }; + let ctx = (&raw mut fixture).cast(); + let mut device = DeviceFeatures::attach(api(), ctx, ctx, shape()).unwrap(); + device.ingest(1, 3, &[40, 41, 42]).unwrap(); + assert_eq!( + fixture.consumed, + vec![ + (3, [40, 40, 40, 0]), + (4, [41, 41, 41, 0]), + (5, [42, 42, 42, 0]) + ] + ); + assert_eq!(fixture.calls, 2); + assert_eq!(device.rows(), 3); + assert!(device.ingest(1, 9, &[43, 44]).is_err()); + assert_eq!(fixture.calls, 2); + assert!(fixture.capture && fixture.batch_live); + drop(device); + assert!(!fixture.capture && !fixture.batch_live); + assert_eq!(fixture.waits, 1); + } + + #[test] + fn unsupported_device_restores_host_capture() { + let mut fixture = Fixture::default(); + let ctx = (&raw mut fixture).cast(); + assert!(DeviceFeatures::attach(api(), ctx, ctx, shape()).is_none()); + assert!(!fixture.capture && !fixture.batch_live); + } + #[test] + fn only_complete_local_ordered_captures_are_eligible() { + assert!(eligible(0, 40, 40, &[true, true], &[3, 8])); + assert!(!eligible(1, 40, 40, &[true, true], &[3, 8])); + assert!(!eligible(0, 20, 40, &[true, true], &[3, 8])); + assert!(!eligible(0, 40, 40, &[true, false], &[3, 8])); + assert!(!eligible(0, 40, 40, &[true, true], &[8, 3])); + assert!(!eligible(0, 40, 40, &[true, true], &[3, 3])); + assert!(!eligible(0, 40, 40, &[], &[])); + } +} diff --git a/crates/skippy-runtime/src/dflash/draft_tensors.rs b/crates/skippy-runtime/src/dflash/draft_tensors.rs new file mode 100644 index 00000000..74a6fd04 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/draft_tensors.rs @@ -0,0 +1,105 @@ +//! Tensor-backed draft head and borrowed-embedding contracts. +use std::path::Path; + +use anyhow::{Context, Result}; + +use super::{DFLASH_BORROWED_TARGET_TENSOR, DSPARK_MARKOV_TENSOR}; + +/// What a draft's tensors say about how it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct DraftTensors { + /// The draft carries its own token embeddings. + pub(super) embeds: bool, + /// The draft is a DSpark draft with a Markov head. + pub(super) markov: bool, + /// The complete predecessor/successor/hidden selector projection set. + pub(super) selector: bool, +} + +pub(super) fn inspect_draft_tensors(path: &Path) -> Result { + let catalog = skippy_model::gguf_catalog::read_gguf_tensor_catalog(path) + .with_context(|| format!("read draft GGUF {}", path.display()))?; + let has = |name: &str| catalog.tensors.iter().any(|tensor| tensor.name == name); + Ok(DraftTensors { + embeds: has(DFLASH_BORROWED_TARGET_TENSOR), + markov: has(DSPARK_MARKOV_TENSOR), + selector: [ + "selector_predecessor.weight", + "selector_successor.weight", + "selector_hidden.weight", + ] + .into_iter() + .all(has), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A GGUF holding one-float tensors named `names`. + fn gguf_with_tensors(names: &[&str]) -> tempfile::NamedTempFile { + use std::io::Write; + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&(names.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + for (index, name) in names.iter().enumerate() { + bytes.extend_from_slice(&(name.len() as u64).to_le_bytes()); + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&1u32.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); // f32 + bytes.extend_from_slice(&(32 * index as u64).to_le_bytes()); + } + bytes.resize(bytes.len().next_multiple_of(32), 0); + bytes.resize(bytes.len() + 32 * names.len(), 0); + let mut file = tempfile::NamedTempFile::new().unwrap(); + file.write_all(&bytes).unwrap(); + file + } + + #[test] + fn a_markov_head_marks_a_dspark_draft() { + let dflash = gguf_with_tensors(&["blk.0.attn_q.weight", "fc.weight"]); + assert_eq!( + inspect_draft_tensors(dflash.path()).unwrap(), + DraftTensors { + embeds: false, + markov: false, + selector: false + } + ); + let dspark = gguf_with_tensors(&[ + "blk.0.attn_q.weight", + "token_embd.weight", + "markov_w1.weight", + "markov_w2.weight", + ]); + assert_eq!( + inspect_draft_tensors(dspark.path()).unwrap(), + DraftTensors { + embeds: true, + markov: true, + selector: false + } + ); + } + + #[test] + fn selector_admission_requires_the_complete_projection_set() { + for names in [ + vec!["selector_hidden.weight"], + vec!["selector_hidden.weight", "selector_predecessor.weight"], + ] { + let partial = gguf_with_tensors(&names); + assert!(!inspect_draft_tensors(partial.path()).unwrap().selector); + } + let complete = gguf_with_tensors(&[ + "selector_hidden.weight", + "selector_predecessor.weight", + "selector_successor.weight", + ]); + assert!(inspect_draft_tensors(complete.path()).unwrap().selector); + } +} diff --git a/crates/skippy-runtime/src/dflash/head_isolation_tests.rs b/crates/skippy-runtime/src/dflash/head_isolation_tests.rs new file mode 100644 index 00000000..5a0b9025 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/head_isolation_tests.rs @@ -0,0 +1,138 @@ +//! Opt-in proof against real selector/convolution weights and target features. +use super::*; +use crate::{ModelInfo, MtpSource}; +use proposal_batch::DFlashBatchRequest; + +struct ReferenceLanes { + // Native sessions borrow the model: drop them before the owning target. + sessions: Vec, + anchors: Vec, + _target: StageModel, +} + +fn reference_lanes() -> Result { + crate::test_support::require_native_runtime(); + let target_path = std::env::var_os("SKIPPY_DRAFT_LAYOUT_TARGET_MODEL") + .context("set SKIPPY_DRAFT_LAYOUT_TARGET_MODEL")?; + let draft_path = std::env::var_os("SKIPPY_DRAFT_LAYOUT_DRAFT_MODEL") + .context("set SKIPPY_DRAFT_LAYOUT_DRAFT_MODEL")?; + let target_path = Path::new(&target_path); + let layers = ModelInfo::open(target_path)? + .tensors()? + .iter() + .filter_map(|tensor| tensor.layer_index) + .max() + .context("target has no layers")? + + 1; + let config = RuntimeConfig { + layer_end: layers, + ctx_size: 8192, + lane_count: 3, + n_gpu_layers: 99, + selected_backend_device: Some("MTL0".to_owned()), + n_batch: Some(512), + n_ubatch: Some(512), + mtp_source: MtpSource::Disabled, + ..RuntimeConfig::default() + }; + let mut target = StageModel::open(target_path, &config)?; + let info = target.attach_dflash_draft( + Path::new(&draft_path), + &DFlashDraftOptions { + max_draft_tokens: Some(6), + ..DFlashDraftOptions::default() + }, + &config, + )?; + assert_eq!(info.variant, DFlashVariant::DFlash2); + let mut sessions = Vec::new(); + let mut anchors = Vec::new(); + for prompt in [ + "Complete this sequence: one, two, three,", + "Write a Python function that finds the longest increasing subsequence in a list of integers.", + "Explain why a database transaction needs isolation when several clients update the same account balance, with a concrete example.", + ] { + let tokens = target.tokenize(prompt, true)?; + let mut session = target.create_session()?; + session.prefill_chunked(&tokens[..tokens.len() - 1])?; + anchors.push(*tokens.last().context("empty prompt")?); + sessions.push(session); + } + Ok(ReferenceLanes { + _target: target, + sessions, + anchors, + }) +} + +fn serial(lanes: &mut ReferenceLanes, widths: &[usize]) -> Result>> { + lanes + .sessions + .iter_mut() + .zip(&lanes.anchors) + .zip(widths) + .map(|((session, &anchor), &width)| { + Ok(session + .dflash_propose(anchor, width)? + .context("draft is not attached")? + .tokens) + }) + .collect() +} + +fn shared(lanes: &mut ReferenceLanes, widths: &[usize], reverse: bool) -> Result>> { + let mut requests: Vec<_> = lanes + .sessions + .iter_mut() + .zip(&lanes.anchors) + .zip(widths) + .map(|((session, &anchor), &max_tokens)| DFlashBatchRequest { + session, + anchor, + max_tokens, + }) + .collect(); + if reverse { + requests.reverse(); + } + let mut tokens = StageSession::dflash_propose_batch(&mut requests)? + .into_iter() + .map(|proposal| Ok(proposal.context("draft is not attached")?.tokens)) + .collect::>>()?; + if reverse { + tokens.reverse(); + } + Ok(tokens) +} + +#[test] +#[ignore = "requires local selector draft/target GGUF paths and a Metal runtime"] +fn selector_noise_blocks_match_independent_lanes_and_remove_scratch() -> Result<()> { + let mut lanes = reference_lanes()?; + for width in [1, 3, 6] { + let widths = [width; 3]; + let expected = serial(&mut lanes, &widths)?; + assert_eq!(shared(&mut lanes, &widths, false)?, expected); + assert_eq!(shared(&mut lanes, &widths, true)?, expected); + assert_eq!(serial(&mut lanes, &widths)?, expected); + } + let before: Vec<_> = lanes + .sessions + .iter() + .map(|session| session.dflash_draft_stats().unwrap().shared_proposals) + .collect(); + assert!(before.iter().all(|&count| count > 0)); + let widths = [1, 3, 6]; + let expected = serial(&mut lanes, &widths)?; + assert_eq!(shared(&mut lanes, &widths, false)?, expected); + let after: Vec<_> = lanes + .sessions + .iter() + .map(|session| session.dflash_draft_stats().unwrap().shared_proposals) + .collect(); + assert_eq!( + after, before, + "ragged selector blocks must run independently" + ); + Ok(()) +} diff --git a/crates/skippy-runtime/src/dflash/heads.rs b/crates/skippy-runtime/src/dflash/heads.rs new file mode 100644 index 00000000..70b24b48 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/heads.rs @@ -0,0 +1,100 @@ +//! Draft head selection and the sequence layout its noise graph accepts. +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum NoiseBatchLayout { + Independent, + Uniform, + Single, +} + +impl NoiseBatchLayout { + pub(super) fn from_head(serial_head: bool, block_local: bool) -> Self { + if serial_head { + Self::Single + } else if block_local { + Self::Uniform + } else { + Self::Independent + } + } + + pub(super) fn permits(self, rows: impl IntoIterator) -> bool { + let mut active = rows.into_iter().filter(|&count| count > 0); + let Some(first) = active.next() else { + return true; + }; + match self { + Self::Independent => true, + Self::Uniform => active.all(|count| count == first), + Self::Single => active.next().is_none(), + } + } +} + +impl DFlashDraft { + /// Picks the draft family and its block layout: DSpark when the draft has + /// a Markov head, DFlash2 when it has a selector lattice, else DFlash. + pub(super) fn select_variant(&mut self, tensors: &DraftTensors) -> Result<()> { + let markov = tensors.markov; + let selector_top_k = unsafe { (self.api.model_dflash_selector_top_k)(self.model) }; + // Convolution taps and selector transitions reshape rows into one + // equally sized block per sequence. Heads without those operations + // may retain independent, differently sized noise blocks. + let convolution = meta_usize(self.model, "dflash.conv_kernel_size")?.unwrap_or(0) > 0; + // Other lattice heads may publish a top-k count too. Without the + // proven projection set, retain independent submissions. + self.noise_batch_layout = NoiseBatchLayout::from_head( + markov || (selector_top_k > 0 && !tensors.selector), + tensors.selector || convolution, + ); + if markov { + if selector_top_k > 0 { + bail!( + "a draft with both a DSpark Markov head and a DFlash2 selector is not supported" + ); + } + self.info.variant = DFlashVariant::DSpark; + let anchor_first = unsafe { + skippy_ffi::llama_model_meta_val_str(self.model, DSPARK_SAMPLE_FROM_ANCHOR_KEY) + } + .is_none_or(|value| value == "true"); + if anchor_first { + self.layout = BlockLayout::AnchorFirst; + } + } else if selector_top_k > 0 { + self.info.variant = DFlashVariant::DFlash2; + self.info.selector_top_k = positive_usize(selector_top_k, "selector top-k")?; + let row_used = self.info.selector_top_k * (self.info.selector_top_k + 1); + if row_used > self.n_embd_draft { + bail!("draft hidden size is too small for the DFlash2 selector lattice"); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::NoiseBatchLayout; + + #[test] + fn selector_rows_keep_sequence_boundaries_and_ignore_absent_blocks() { + let selector = NoiseBatchLayout::from_head(false, true); + assert!(selector.permits([0, 7, 7, 0])); + assert!(selector.permits([2, 2, 2])); + assert!(selector.permits([0, 0])); + assert!(!selector.permits([7, 4])); + assert!(!selector.permits([0, 7, 6])); + } + + #[test] + fn independent_heads_accept_ragged_blocks_but_markov_heads_stay_serial() { + assert!(NoiseBatchLayout::from_head(false, false).permits([7, 0, 4])); + let markov = NoiseBatchLayout::from_head(true, false); + assert!(markov.permits([0, 7, 0])); + assert!(!markov.permits([7, 7])); + // A rejected mixed head must never gain the selector's batch admission. + assert!(!NoiseBatchLayout::from_head(true, true).permits([7, 7])); + } +} diff --git a/crates/skippy-runtime/src/dflash/noise_blocks.rs b/crates/skippy-runtime/src/dflash/noise_blocks.rs new file mode 100644 index 00000000..55b70710 --- /dev/null +++ b/crates/skippy-runtime/src/dflash/noise_blocks.rs @@ -0,0 +1,308 @@ +//! Decodes independent lanes' noise blocks together, then removes scratch KV. +use super::*; + +pub(super) struct NoiseBlock { + pub seq_id: i32, + pub position: i32, + pub anchor: i32, + pub max_tokens: usize, +} + +#[derive(Debug, PartialEq, Eq)] +struct BlockSpan { + offset: usize, + drafts: usize, + rows: usize, +} + +fn plan_blocks( + blocks: &[NoiseBlock], + max_drafts: usize, + layout: BlockLayout, + lanes: i32, + capacity: usize, +) -> Option> { + let mut sequences = std::collections::BTreeSet::new(); + let mut spans = Vec::with_capacity(blocks.len()); + let mut offset = 0usize; + for block in blocks { + if !(0..lanes).contains(&block.seq_id) + || !sequences.insert(block.seq_id) + || block.position < 0 + { + return None; + } + let drafts = block.max_tokens.min(max_drafts); + let rows = if drafts == 0 { + 0 + } else { + drafts.checked_add(1)?; + layout.block_tokens(drafts) + }; + block + .position + .checked_add(i32::try_from(rows.saturating_sub(1)).ok()?)?; + spans.push(BlockSpan { + offset, + drafts, + rows, + }); + offset = offset + .checked_add(rows) + .filter(|total| *total <= capacity)?; + } + Some(spans) +} + +impl DFlashDraft { + pub(super) fn propose( + &mut self, + seq_id: i32, + position: i32, + anchor: i32, + max_tokens: usize, + ) -> Result> { + #[cfg(target_os = "macos")] + if let Some(ane) = self.ane.as_mut() { + let draft_tokens = max_tokens.min(self.info.max_draft_tokens); + if draft_tokens == 0 { + return Ok(Vec::new()); + } + ane.truncate(seq_id, position); + return ane.propose(seq_id, position, anchor, draft_tokens); + } + let mut outputs = self.propose_blocks(&[NoiseBlock { + seq_id, + position, + anchor, + max_tokens, + }])?; + Ok(outputs.remove(0)) + } + + pub(super) fn blocks_fit(&self, blocks: &[NoiseBlock]) -> bool { + let Some(ctx) = self.native_ctx else { + return false; + }; + let capacity = self + .n_ubatch + .min(unsafe { (self.api.n_batch)(ctx.as_ptr()) } as usize); + plan_blocks( + blocks, + self.info.max_draft_tokens, + self.layout, + self.lanes, + capacity, + ) + .is_some_and(|spans| { + self.noise_batch_layout + .permits(spans.iter().map(|span| span.rows)) + }) + } + + pub(super) fn propose_blocks(&mut self, blocks: &[NoiseBlock]) -> Result>> { + anyhow::ensure!( + self.blocks_fit(blocks), + "draft blocks exceed native capacity or repeat a sequence" + ); + let spans = plan_blocks( + blocks, + self.info.max_draft_tokens, + self.layout, + self.lanes, + self.n_ubatch, + ) + .context("invalid draft block layout")?; + let ctx = self + .native_ctx + .context("DFlash has no native draft context")? + .as_ptr(); + self.batch.clear(); + for (block, span) in blocks.iter().zip(&spans) { + if span.drafts == 0 { + continue; + } + self.truncate(block.seq_id, block.position); + for index in 0..span.rows { + let token = if index == 0 { + block.anchor + } else { + self.mask_token + }; + self.batch.push_token( + token, + block.position + index as i32, + block.seq_id, + self.info.variant != DFlashVariant::DFlash2, + ); + } + } + let outputs = if spans.iter().all(|span| span.rows == 0) { + Ok(vec![Vec::new(); blocks.len()]) + } else { + let rc = unsafe { (self.api.decode)(ctx, self.batch.as_raw(self.mrope)) }; + if rc == 0 { + spans + .into_iter() + .map(|span| self.read_block_at(ctx, span.offset, span.drafts)) + .collect() + } else { + Err(anyhow!("draft block decode failed with status {rc}")) + } + }; + // Remove noise even when decoding or readout failed. Only captured + // target features may survive a proposal, independently in each lane. + for block in blocks.iter().filter(|block| block.max_tokens > 0) { + self.truncate(block.seq_id, block.position); + } + outputs + } + + fn read_block_at(&self, ctx: *mut Opaque, offset: usize, drafts: usize) -> Result> { + if drafts == 0 { + return Ok(Vec::new()); + } + if self.info.variant == DFlashVariant::DFlash2 { + let lattice = unsafe { (self.api.get_embeddings_nextn)(ctx) }; + anyhow::ensure!(!lattice.is_null(), "DFlash2 selector produced no lattice"); + let lattice = unsafe { + std::slice::from_raw_parts( + lattice.add(offset * self.n_embd_draft), + (drafts + 1) * self.n_embd_draft, + ) + }; + return Ok(walk_dflash2_lattice( + lattice.chunks_exact(self.n_embd_draft).skip(1), + self.info.selector_top_k, + self.n_vocab, + )); + } + let mut tokens = Vec::with_capacity(drafts); + let first = offset + self.layout.first_draft_row(); + for row in first..first + drafts { + let row = i32::try_from(row).context("draft row exceeds i32")?; + if let Some(readout) = &self.backend_readout + && let Some(token) = readout.token(row, self.n_vocab)? + { + tokens.push(token); + continue; + } + let logits = unsafe { (self.api.get_logits_ith)(ctx, row) }; + anyhow::ensure!( + !logits.is_null(), + "draft produced no logits for block row {row}" + ); + let logits = unsafe { std::slice::from_raw_parts(logits.cast_const(), self.n_vocab) }; + tokens.push(argmax_token(logits).context("draft logits row is empty")?); + } + Ok(tokens) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(seq_id: i32, max_tokens: usize) -> NoiseBlock { + NoiseBlock { + seq_id, + max_tokens, + position: 10, + anchor: 1, + } + } + + #[test] + fn ragged_blocks_have_disjoint_output_spans_and_empty_blocks_have_no_rows() { + let spans = plan_blocks( + &[block(0, 6), block(1, 0), block(2, 3)], + 6, + BlockLayout::BonusAnchor, + 3, + 11, + ) + .unwrap(); + assert_eq!( + spans, + vec![ + BlockSpan { + offset: 0, + drafts: 6, + rows: 7 + }, + BlockSpan { + offset: 7, + drafts: 0, + rows: 0 + }, + BlockSpan { + offset: 7, + drafts: 3, + rows: 4 + } + ] + ); + assert!( + plan_blocks( + &[block(0, 6), block(1, 3)], + 6, + BlockLayout::BonusAnchor, + 2, + 10 + ) + .is_none() + ); + } + + #[test] + fn duplicate_or_foreign_lanes_and_overflow_are_rejected_before_mutation() { + for blocks in [ + vec![block(0, 2), block(0, 2)], + vec![block(-1, 2)], + vec![block(2, 2)], + ] { + assert!(plan_blocks(&blocks, 6, BlockLayout::BonusAnchor, 2, 32).is_none()); + } + let mut overflow = block(0, 2); + overflow.position = i32::MAX; + assert!(plan_blocks(&[overflow], 6, BlockLayout::BonusAnchor, 2, 32).is_none()); + assert!( + plan_blocks( + &[block(0, usize::MAX)], + usize::MAX, + BlockLayout::BonusAnchor, + 2, + usize::MAX + ) + .is_none() + ); + } + + #[test] + fn anchor_first_blocks_keep_their_trained_width() { + let spans = plan_blocks( + &[block(0, 9), block(1, 3)], + 6, + BlockLayout::AnchorFirst, + 2, + 9, + ) + .unwrap(); + assert_eq!( + spans[0], + BlockSpan { + offset: 0, + drafts: 6, + rows: 6 + } + ); + assert_eq!( + spans[1], + BlockSpan { + offset: 6, + drafts: 3, + rows: 3 + } + ); + } +} diff --git a/crates/skippy-runtime/src/dflash/proposal_batch.rs b/crates/skippy-runtime/src/dflash/proposal_batch.rs new file mode 100644 index 00000000..d98a05df --- /dev/null +++ b/crates/skippy-runtime/src/dflash/proposal_batch.rs @@ -0,0 +1,196 @@ +//! Shared draft submissions with independent target-feature contexts. +use super::*; + +/// One lane's next draft. Every session must be exclusively borrowed while +/// its proposal runs, just as for [`StageSession::dflash_propose`]. +pub struct DFlashBatchRequest<'a> { + pub session: &'a mut StageSession, + pub anchor: i32, + pub max_tokens: usize, +} + +fn independent(requests: &mut [DFlashBatchRequest<'_>]) -> Result>> { + requests + .iter_mut() + .map(|request| { + request + .session + .dflash_propose(request.anchor, request.max_tokens) + }) + .collect() +} + +impl StageSession { + /// Runs compatible noise blocks in one draft forward. Unattached drafts, + /// different draft models, unsupported heads and excess native capacity + /// retain independent submissions. A draft failure clears its affected + /// draft lanes and returns empty proposals; target state is untouched. + pub fn dflash_propose_batch( + requests: &mut [DFlashBatchRequest<'_>], + ) -> Result>> { + if requests.len() < 2 { + return independent(requests); + } + let drafts = requests + .iter() + .map(|request| { + request + .session + .dflash + .as_ref() + .and_then(|link| link.draft.upgrade()) + }) + .collect::>>(); + let Some(drafts) = drafts else { + return independent(requests); + }; + if drafts.iter().any(|draft| !Arc::ptr_eq(draft, &drafts[0])) { + return independent(requests); + } + // Validate positions before ingesting features or changing any lane. + let positions = requests + .iter() + .map(|request| { + i32::try_from(request.session.native_position()?) + .context("anchor position exceeds i32") + }) + .collect::>>()?; + let started = Instant::now(); + let mut blocks = Vec::new(); + let mut order = Vec::new(); + for (index, request) in requests.iter_mut().enumerate() { + let link = request + .session + .dflash + .as_mut() + .expect("checked attached draft"); + link.flush_pending(); + if link.context.can_propose(positions[index] as u64) && request.max_tokens > 0 { + order.push(index); + blocks.push(NoiseBlock { + seq_id: link.seq_id, + position: positions[index], + anchor: request.anchor, + max_tokens: request.max_tokens, + }); + } else if request.max_tokens == 0 && link.context.can_propose(positions[index] as u64) { + link.context.truncated(positions[index] as u64); + } + } + let mut draft = lock_draft(&drafts[0]); + if !draft.blocks_fit(&blocks) { + drop(draft); + return independent(requests); + } + let proposed = draft.propose_blocks(&blocks); + let shared = blocks.len() > 1; + if proposed.is_err() { + for block in &blocks { + draft.clear(block.seq_id); + } + } + drop(draft); + let elapsed = elapsed_us(started); + let compute_share = elapsed / blocks.len().max(1) as u64; + let mut outputs = vec![ + Some(DFlashProposal { + tokens: Vec::new(), + proposal_compute_us: elapsed + }); + requests.len() + ]; + for request in requests.iter_mut() { + let link = request + .session + .dflash + .as_mut() + .expect("checked attached draft"); + link.stats.proposals += 1; + } + if shared { + for &index in &order { + requests[index] + .session + .dflash + .as_mut() + .expect("checked attached draft") + .stats + .shared_proposals += 1; + } + } + match proposed { + Ok(tokens) => { + for (index, tokens) in order.into_iter().zip(tokens) { + let link = requests[index] + .session + .dflash + .as_mut() + .expect("checked attached draft"); + link.context.truncated(positions[index] as u64); + link.stats.propose_us = link.stats.propose_us.saturating_add(elapsed); + outputs[index] = Some(DFlashProposal { + tokens, + proposal_compute_us: compute_share, + }); + } + } + Err(error) => { + write_native_log_note(format!( + "dflash shared proposal failed, draft contexts cleared: {error:#}" + )); + for index in order { + let link = requests[index] + .session + .dflash + .as_mut() + .expect("checked attached draft"); + link.context.cleared(positions[index] as u64); + link.stats.propose_us = link.stats.propose_us.saturating_add(elapsed); + } + } + } + Ok(outputs) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn without_draft() -> StageSession { + StageSession { + raw: ptr::null_mut(), + token_count: 11, + terminal_stage: true, + batched_activation_exports: true, + dflash: None, + dflash_split: None, + } + } + + #[test] + fn requests_without_drafts_do_not_call_native_or_change_target_positions() { + let mut a = without_draft(); + let mut b = without_draft(); + let outputs = StageSession::dflash_propose_batch(&mut [ + DFlashBatchRequest { + session: &mut a, + anchor: 1, + max_tokens: 6, + }, + DFlashBatchRequest { + session: &mut b, + anchor: 2, + max_tokens: 3, + }, + ]) + .unwrap(); + assert_eq!(outputs, [None, None]); + assert_eq!((a.token_count(), b.token_count()), (11, 11)); + assert!( + StageSession::dflash_propose_batch(&mut []) + .unwrap() + .is_empty() + ); + } +} diff --git a/crates/skippy-runtime/src/kv_pages.rs b/crates/skippy-runtime/src/kv_pages.rs index cb5a1408..1211d66b 100644 --- a/crates/skippy-runtime/src/kv_pages.rs +++ b/crates/skippy-runtime/src/kv_pages.rs @@ -6,7 +6,7 @@ use skippy_cache::cachegen::archive::{ CacheGenArchive, ComponentLayout, PageLayout, RecordKind, ValidatedArchive, ValueType, decode_page, encode_page, validate_archive, }; -use skippy_ffi::{CacheGenRecordV1, KvPageDesc as RawKvPageDesc}; +use skippy_ffi::{CacheGenRecordV1, KvPageChunk, KvPageDesc as RawKvPageDesc}; use crate::error::{ensure_ok, free_error}; use crate::session::StageSession; @@ -491,12 +491,63 @@ impl StageSession { )) }; ensure_ok(status, error)?; + self.finish_kv_page_import(desc); + Ok(()) + } + + /// Imports a raw page from borrowed chunks. Returns false when this + /// layout or backend needs the contiguous importer. + pub fn try_import_kv_page_chunks<'a>( + &mut self, + desc: &RuntimeKvPageDesc, + chunks: impl ExactSizeIterator, + ) -> Result { + if chunks.len() < 2 || desc.has_sliding_window_component() { + return Ok(false); + } + let mut raw_chunks = Vec::with_capacity(chunks.len()); + let mut bytes = 0usize; + for chunk in chunks.filter(|chunk| !chunk.is_empty()) { + bytes = bytes + .checked_add(chunk.len()) + .ok_or_else(|| anyhow::anyhow!("KV page chunk lengths overflow"))?; + raw_chunks.push(KvPageChunk { + data: chunk.as_ptr().cast(), + bytes: chunk.len(), + }); + } + desc.validate_payload(bytes)?; + if raw_chunks.len() < 2 { + return Ok(false); + } + let raw = desc.as_raw(); + let mut error = ptr::null_mut(); + // SAFETY: the slices and descriptor array stay alive for the call. + // The native importer synchronously copies the bytes into KV storage. + let status = unsafe { + native_call!(skippy_import_kv_page_chunks( + self.raw, + &raw, + raw_chunks.as_ptr(), + raw_chunks.len(), + &mut error, + )) + }; + if status == crate::Status::Unsupported { + free_error(error); + return Ok(false); + } + ensure_ok(status, error)?; + self.finish_kv_page_import(desc); + Ok(true) + } + + fn finish_kv_page_import(&mut self, desc: &RuntimeKvPageDesc) { self.token_count = self .token_count .max(desc.token_start.saturating_add(desc.token_count)); // Imported target state has no matching draft features. self.dflash_after_replace(); - Ok(()) } pub fn import_cachegen_kv_page( diff --git a/crates/skippy-runtime/src/lib.rs b/crates/skippy-runtime/src/lib.rs index 999a597f..2ae2de0a 100644 --- a/crates/skippy-runtime/src/lib.rs +++ b/crates/skippy-runtime/src/lib.rs @@ -9,7 +9,7 @@ pub mod clef; mod config; pub mod decision; mod devices; -mod dflash; +pub mod dflash; mod error; mod gguf_writer; mod kv_pages; @@ -34,6 +34,7 @@ mod stage_planning; #[cfg(any(test, feature = "test-support"))] pub mod test_support; mod types; +pub mod verification_batch; mod vocabulary; pub use activation::{ @@ -114,6 +115,7 @@ pub use stage_planning::{ // without taking a direct dependency on the raw ABI crate. pub use skippy_ffi::{ KV_PAGE_FLAG_CANONICAL_POSITIONS, KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, + KvPageComponentRole, }; // Native renderer identity. Re-exported so callers can fingerprint a chat-template // render (for example a rendered-prompt probe) without taking a direct dependency diff --git a/crates/skippy-runtime/src/media.rs b/crates/skippy-runtime/src/media.rs index 5a02d702..c6626012 100644 --- a/crates/skippy-runtime/src/media.rs +++ b/crates/skippy-runtime/src/media.rs @@ -216,7 +216,11 @@ impl MediaProjector { } fn marker() -> String { - let marker = unsafe { skippy_ffi::mtmd_default_marker() }; + let marker = if crate::native_runtime_loaded() { + unsafe { skippy_ffi::mtmd_default_marker() } + } else { + ptr::null() + }; if marker.is_null() { "<__media__>".to_string() } else { @@ -1010,6 +1014,11 @@ impl StageModel { #[cfg(test)] mod tests { + #[test] + fn dummy_media_marker_is_available_before_native_startup() { + assert_eq!(crate::StageModel::new_dummy().media_marker(), "<__media__>"); + } + use super::clamp_image_min_tokens; #[test] diff --git a/crates/skippy-runtime/src/native.rs b/crates/skippy-runtime/src/native.rs index 779541b5..d0839eb6 100644 --- a/crates/skippy-runtime/src/native.rs +++ b/crates/skippy-runtime/src/native.rs @@ -106,6 +106,7 @@ struct StageModelInner { raw: *mut RawModel, source_gguf: Option, terminal_stage: bool, + complete_terminal_stage: bool, capability: Option, /// External DFlash draft that borrows this model's context. Freed before /// the native model. @@ -175,6 +176,7 @@ impl StageModel { raw: std::ptr::null_mut(), source_gguf: None, terminal_stage: true, + complete_terminal_stage: true, capability: None, dflash: None, dflash_capture: None, @@ -230,6 +232,11 @@ impl StageModel { unsafe { skippy_ffi::skippy_model_supports_causal_readout(self.inner.raw) } } + /// Independent speculative windows can share a complete causal target. + pub fn supports_shared_verification(&self) -> bool { + self.inner.complete_terminal_stage && self.supports_causal_readout() + } + fn from_opened_raw( raw: *mut RawModel, source_gguf: Option, @@ -247,6 +254,7 @@ impl StageModel { raw, source_gguf, terminal_stage: config.is_terminal_stage(), + complete_terminal_stage: config.layer_start == 0 && config.is_terminal_stage(), capability, dflash: None, dflash_capture: None, diff --git a/crates/skippy-runtime/src/resident_prefix.rs b/crates/skippy-runtime/src/resident_prefix.rs index 743e782b..3f1baf08 100644 --- a/crates/skippy-runtime/src/resident_prefix.rs +++ b/crates/skippy-runtime/src/resident_prefix.rs @@ -1,9 +1,9 @@ //! 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 crate::{KvPageComponentRole, RuntimeKvPage, RuntimeKvPageDesc, Status, session::StageSession}; use anyhow::{Result, ensure}; -use std::ptr; +use std::{ops::Range, ptr}; impl StageSession { pub fn resident_kv_page_desc( @@ -12,6 +12,19 @@ impl StageSession { layers: (i32, i32), tokens: u64, ) -> Result { + self.resident_kv_range_desc(sequence, layers, 0..tokens) + } + + pub fn resident_kv_range_desc( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + ) -> Result { + let count = tokens + .end + .checked_sub(tokens.start) + .ok_or_else(|| anyhow::anyhow!("resident KV token range is reversed"))?; let mut desc = skippy_ffi::KvPageDesc::default(); let mut bytes = 0; let mut error = ptr::null_mut(); @@ -22,8 +35,8 @@ impl StageSession { sequence, layers.0, layers.1, - 0, - tokens, + tokens.start, + count, &mut desc, ptr::null_mut(), 0, @@ -46,25 +59,68 @@ impl StageSession { tokens: u64, bytes: usize, ) -> Result { + self.export_resident_kv_range(sequence, layers, 0..tokens, bytes) + } + + pub fn export_resident_kv_range( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + bytes: usize, + ) -> Result { + self.export_resident_attention_range(sequence, layers, tokens, bytes, None) + } + + /// Export a saved token range either from the whole native page or from + /// one explicitly selected sliding-window component. + pub fn export_resident_attention_range( + &mut self, + sequence: i32, + layers: (i32, i32), + tokens: Range, + bytes: usize, + component: Option, + ) -> Result { + let count = tokens + .end + .checked_sub(tokens.start) + .ok_or_else(|| anyhow::anyhow!("resident KV token range is reversed"))?; 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 { - native_call!(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, - )) + match component { + None => native_call!(skippy_session_export_resident_kv_page( + self.raw, + sequence, + layers.0, + layers.1, + tokens.start, + count, + &mut desc, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + )), + Some(role) => native_call!(skippy_session_export_resident_kv_component( + self.raw, + sequence, + role, + layers.0, + layers.1, + tokens.start, + count, + &mut desc, + payload.as_mut_ptr().cast(), + payload.len(), + &mut written, + &mut error, + )), + } }; ensure_ok(status, error)?; ensure!( @@ -96,6 +152,27 @@ impl StageSession { Ok(bytes) } + pub fn copy_resident_recurrent_range( + &mut self, + sequence: i32, + offset: usize, + output: &mut [u8], + ) -> Result<()> { + let mut error = ptr::null_mut(); + // SAFETY: The session is live and the mutable slice is writable for its entire length. + let status = unsafe { + native_call!(skippy_session_copy_resident_recurrent_range( + self.raw, + sequence, + offset, + output.as_mut_ptr().cast(), + output.len(), + &mut error, + )) + }; + ensure_ok(status, error) + } + pub fn export_resident_recurrent_state( &mut self, sequence: i32, diff --git a/crates/skippy-runtime/src/types.rs b/crates/skippy-runtime/src/types.rs index efdfbfb1..3a8c9e5c 100644 --- a/crates/skippy-runtime/src/types.rs +++ b/crates/skippy-runtime/src/types.rs @@ -447,6 +447,40 @@ pub struct RuntimeKvPageDesc { } impl RuntimeKvPageDesc { + /// Describe one component using the same layout as a native single page. + pub fn component_page(&self, role: skippy_ffi::KvPageComponentRole) -> Option { + if !self.has_sliding_window_component() || self.component_count != 2 { + return None; + } + let index = match role { + skippy_ffi::KvPageComponentRole::Base => 0, + skippy_ffi::KvPageComponentRole::Swa => 1, + }; + let component = &self.components[index]; + if component.role != role as u32 { + return None; + } + Some(Self { + version: component.version, + layer_start: self.layer_start, + layer_end: self.layer_end, + token_start: component.token_start, + token_count: component.token_count, + layer_count: component.layer_count, + k_type: component.k_type, + v_type: component.v_type, + k_row_bytes: component.k_row_bytes, + v_row_bytes: component.v_row_bytes, + v_element_bytes: component.v_element_bytes, + k_idx_row_bytes: component.k_idx_row_bytes, + payload_bytes: component.payload_bytes, + flags: component.flags, + codec: skippy_ffi::KV_PAGE_CODEC_SINGLE_V1, + component_count: 0, + components: Box::default(), + }) + } + /// Whether the page includes a sliding-window cache's rows. That cache /// reuses rows that fall out of the window as the sequence grows, so its /// rows below a position do not stay resident. diff --git a/crates/skippy-runtime/src/verification_batch.rs b/crates/skippy-runtime/src/verification_batch.rs new file mode 100644 index 00000000..c455d127 --- /dev/null +++ b/crates/skippy-runtime/src/verification_batch.rs @@ -0,0 +1,106 @@ +//! Target verification shared across independent speculative lanes. +use std::ptr; + +use anyhow::{Context, Result, ensure}; +use skippy_ffi::bindings::skippy::skippy_verify_request; + +use crate::native_timing::native_call; +use crate::{SamplingConfig, StageSession, dflash::DecodedRows, error::ensure_ok}; + +/// One equal-length window on a distinct session of a complete terminal model. +pub struct VerifyBatchRequest<'a> { + pub session: &'a mut StageSession, + pub token_ids: &'a [i32], + pub sampling: Option<&'a SamplingConfig>, +} + +impl StageSession { + /// Actual native capacity after backend allocation and batch clamping. + /// The upstream context metadata functions share the optional draft API + /// table; absent exports keep scheduler verification on its serial path. + pub fn verification_batch_capacity(&self) -> Option { + let api = skippy_ffi::llama_draft::llama_draft_api()?; + let context = unsafe { skippy_ffi::skippy_session_llama_context(self.raw) } + .cast::(); + if context.is_null() { + return None; + } + let capacity = unsafe { (api.n_ubatch)(context).min((api.n_batch)(context)) }; + usize::try_from(capacity) + .ok() + .filter(|capacity| *capacity > 0) + } + + /// Shares one target forward across compatible speculative windows. + /// Each result stops at that lane's first rejection. The caller must trim + /// or retire each window, as with single-session sampled verification. + /// The native layer rejects unsupported shapes before decoding. + pub fn verify_batch_sampled(requests: &mut [VerifyBatchRequest<'_>]) -> Result>> { + let Some(first) = requests.first() else { + return Ok(Vec::new()); + }; + let width = first.token_ids.len(); + ensure!(width > 0, "verification windows must not be empty"); + let ends = requests + .iter() + .map(|request| { + ensure!( + request.token_ids.len() == width, + "verification windows must have equal length" + ); + ensure!( + request.session.terminal_stage, + "shared verification requires terminal sessions" + ); + request + .session + .token_count + .checked_add(width as u64) + .context("session position overflow") + }) + .collect::>>()?; + let sampling = requests + .iter() + .map(|request| request.sampling.map(SamplingConfig::as_raw).transpose()) + .collect::>>()?; + let mut outputs = vec![vec![0; width]; requests.len()]; + let mut counts = vec![0; requests.len()]; + let raw: Vec<_> = requests + .iter() + .zip(&sampling) + .zip(outputs.iter_mut().zip(&mut counts)) + .map( + |((request, sampling), (output, count))| skippy_verify_request { + session: request.session.raw, + token_ids: request.token_ids.as_ptr(), + token_count: width, + sampling: sampling.as_ref().map_or(ptr::null(), ptr::from_ref), + output_tokens: output.as_mut_ptr(), + output_capacity: output.len(), + out_token_count: count, + }, + ) + .collect(); + let mut error = ptr::null_mut(); + let status = unsafe { + native_call!(skippy_verify_batch_sampled( + raw.as_ptr(), + raw.len(), + &mut error + )) + }; + ensure_ok(status, error)?; + for (index, request) in requests.iter_mut().enumerate() { + ensure!( + counts[index] > 0 && counts[index] <= width, + "invalid native verification output count" + ); + request.session.token_count = ends[index]; + request + .session + .dflash_after_decode(DecodedRows::trailing(index * width, width)); + outputs[index].truncate(counts[index]); + } + Ok(outputs) + } +} diff --git a/crates/skippy-scheduler/README.md b/crates/skippy-scheduler/README.md index abf55cf5..080a7ae3 100644 --- a/crates/skippy-scheduler/README.md +++ b/crates/skippy-scheduler/README.md @@ -52,6 +52,17 @@ enqueue-time score and is emitted as stale-fallback telemetry. New arrivals may re-rank the remaining queue. This request radix is scheduling-only and never changes unified-cache recency. +Explicit priority is the request tier when serving (`local` above `trusted` +above `mesh`). Each time `PRIORITY_AGING_TURNS` higher-priority candidates +are selected ahead of a waiting candidate, it ranks one level higher, but +only up to a level another candidate holds, so the order stays total and +age never reorders candidates of one priority. Callers count those +selections with `PriorityPassovers` and pass each candidate's +`passed_over`. For +eviction, `EvictableCacheEntry::retention_priority` ranks ahead of recompute +value: serving sets it from the tier that stored the entry, so the lowest +tier is evicted first. + ## License Licensed under Apache-2.0. diff --git a/crates/skippy-scheduler/src/cache_policy.rs b/crates/skippy-scheduler/src/cache_policy.rs index b9cd3fa9..8a306e46 100644 --- a/crates/skippy-scheduler/src/cache_policy.rs +++ b/crates/skippy-scheduler/src/cache_policy.rs @@ -56,6 +56,42 @@ impl CacheAffinity { } } +/// Times a candidate is passed over to gain one priority level. Priority is +/// strict among fresh arrivals, but a lower-priority candidate climbs one level +/// each time this many higher-priority candidates are selected ahead of it, so +/// no level starves. Waiting behind its own or a lower level does not count: +/// a busy lower level never catches up with a higher one by queueing alone. +pub const PRIORITY_AGING_TURNS: u64 = 16; + +/// Counts selections by priority, so a waiting candidate's +/// [`CacheAwareCandidate::passed_over`] can be read off at any time. +#[derive(Debug, Default, Clone)] +pub struct PriorityPassovers { + selected: std::collections::BTreeMap, +} + +impl PriorityPassovers { + /// Record that a candidate of `priority` was selected. + pub fn record_selection(&mut self, priority: u64) { + let count = self.selected.entry(priority).or_default(); + *count = count.saturating_add(1); + } + + /// The selections so far above `priority`. Keep it when a candidate of + /// `priority` starts waiting and pass it to [`Self::passed_over`] later. + pub fn mark(&self, priority: u64) -> u64 { + self.selected + .range(priority.saturating_add(1)..) + .map(|(_, count)| *count) + .fold(0, u64::saturating_add) + } + + /// How many higher-priority candidates were selected since `mark`. + pub fn passed_over(&self, priority: u64, mark: u64) -> u64 { + self.mark(priority).saturating_sub(mark) + } +} + #[derive(Debug, Clone, Copy)] pub struct CacheAwareCandidate<'a> { pub index: usize, @@ -64,6 +100,9 @@ pub struct CacheAwareCandidate<'a> { pub prompt_tokens: &'a [i32], pub enqueued_turn: u64, pub order: u64, + /// How many higher-priority candidates were selected while this one + /// waited (see [`PriorityPassovers`]); it ages the candidate's priority. + pub passed_over: u64, } /// Order cache candidates by priority, saved work plus aging, then waiting @@ -101,6 +140,10 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( anchor_prompt: Option<&[i32]>, ) -> Vec { let candidates = candidates.into_iter().collect::>(); + let levels = candidates + .iter() + .map(|candidate| candidate.priority) + .collect::>(); let mut dfs_ranks = vec![0usize; candidates.len()]; if group_waiting_prefixes { let mut dfs_order = Vec::with_capacity(candidates.len()); @@ -124,9 +167,8 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( ranked.sort_by(|(left, left_dfs_rank), (right, right_dfs_rank)| { let left_score = effective_score(left, current_turn, aging_cost_per_turn); let right_score = effective_score(right, current_turn, aging_cost_per_turn); - right - .priority - .cmp(&left.priority) + priority_rank(right, &levels) + .cmp(&priority_rank(left, &levels)) .then_with(|| { if group_waiting_prefixes { grouping_score(right, current_turn, aging_cost_per_turn).cmp(&grouping_score( @@ -154,6 +196,28 @@ pub fn order_cache_aware_candidates_with_anchor<'a>( .collect() } +/// Priority plus one level per [`PRIORITY_AGING_TURNS`] times passed over. +fn aged_priority(candidate: &CacheAwareCandidate<'_>) -> u64 { + candidate + .priority + .saturating_add(candidate.passed_over / PRIORITY_AGING_TURNS) +} + +/// The highest priority among `levels` (the candidates' own priorities) that +/// `candidate` has aged to. Age only lifts a candidate to a level another +/// candidate holds, so candidates of one level keep the cache-aware order +/// whatever their ages. +fn priority_rank( + candidate: &CacheAwareCandidate<'_>, + levels: &std::collections::BTreeSet, +) -> u64 { + levels + .range(..=aged_priority(candidate)) + .next_back() + .copied() + .unwrap_or(candidate.priority) +} + fn grouping_score( candidate: &CacheAwareCandidate<'_>, current_turn: u64, @@ -301,6 +365,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -309,6 +374,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, @@ -333,6 +399,7 @@ mod tests { prompt_tokens, enqueued_turn: 0, order: index as u64, + passed_over: 0, }), 0, 10, @@ -349,6 +416,7 @@ mod tests { prompt_tokens: prompts[index], enqueued_turn: 0, order: index as u64, + passed_over: 0, }), 1, 10, @@ -371,6 +439,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -379,6 +448,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 11, order: 1, + passed_over: 0, }, ], 11, @@ -401,6 +471,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -409,6 +480,7 @@ mod tests { prompt_tokens: &[4, 5, 6], enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, @@ -418,6 +490,82 @@ mod tests { assert_eq!(selected, Some(0)); } + #[test] + fn waiting_lower_priority_climbs_one_level_per_aging_window() { + let affinity = CacheAffinity::default(); + let candidates = |passed_over: u64| { + order_cache_aware_candidates( + [ + CacheAwareCandidate { + index: 0, + priority: 0, + affinity: &affinity, + prompt_tokens: &[1], + enqueued_turn: 0, + order: 0, + passed_over, + }, + CacheAwareCandidate { + index: 1, + priority: 2, + affinity: &affinity, + prompt_tokens: &[2], + enqueued_turn: 100, + order: 1, + passed_over: 0, + }, + ], + 100, + 10, + false, + ) + }; + // A fresh higher-priority arrival passes a waiter two levels below it + // until that waiter has been passed over two full windows; then age + // decides. + assert_eq!(candidates(2 * PRIORITY_AGING_TURNS - 1), vec![1, 0]); + assert_eq!(candidates(2 * PRIORITY_AGING_TURNS), vec![0, 1]); + } + + #[test] + fn age_never_reorders_candidates_of_one_priority() { + let affinity = CacheAffinity::default(); + let candidate = |index, passed_over| CacheAwareCandidate { + index, + priority: 1, + affinity: &affinity, + prompt_tokens: &[1], + enqueued_turn: 0, + order: index as u64, + passed_over, + }; + let levels = std::collections::BTreeSet::from([1]); + let long = 10 * PRIORITY_AGING_TURNS; + assert_eq!(priority_rank(&candidate(0, long), &levels), 1); + assert_eq!(priority_rank(&candidate(1, 0), &levels), 1); + let with_higher = std::collections::BTreeSet::from([1, 2, 4]); + assert_eq!(priority_rank(&candidate(0, long), &with_higher), 4); + assert_eq!( + priority_rank(&candidate(0, PRIORITY_AGING_TURNS), &with_higher), + 2 + ); + assert_eq!(priority_rank(&candidate(1, 0), &with_higher), 1); + } + + #[test] + fn only_higher_priority_selections_pass_a_candidate_over() { + let mut passovers = PriorityPassovers::default(); + let mark = passovers.mark(1); + passovers.record_selection(0); + passovers.record_selection(1); + assert_eq!(passovers.passed_over(1, mark), 0); + passovers.record_selection(2); + passovers.record_selection(5); + assert_eq!(passovers.passed_over(1, mark), 2); + assert_eq!(passovers.passed_over(2, passovers.mark(2)), 0); + assert_eq!(passovers.mark(u64::MAX), 0); + } + #[test] fn dfs_weight_groups_the_heaviest_equal_score_prefix_subtree() { let affinity = CacheAffinity::default(); @@ -430,6 +578,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -438,6 +587,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -446,6 +596,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -468,6 +619,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -476,6 +628,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 1, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -484,6 +637,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 2, order: 2, + passed_over: 0, }, ], 3, @@ -506,6 +660,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -514,6 +669,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 9, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -522,6 +678,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 10, order: 2, + passed_over: 0, }, ], 10, @@ -544,6 +701,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -552,6 +710,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -560,6 +719,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -583,6 +743,7 @@ mod tests { prompt_tokens: &[1, 2, 3], enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -591,6 +752,7 @@ mod tests { prompt_tokens: &[1, 2, 4], enqueued_turn: 0, order: 1, + passed_over: 0, }, CacheAwareCandidate { index: 2, @@ -599,6 +761,7 @@ mod tests { prompt_tokens: &[9, 9, 9], enqueued_turn: 0, order: 2, + passed_over: 0, }, ], 0, @@ -625,6 +788,7 @@ mod tests { prompt_tokens: &left, enqueued_turn: 0, order: 0, + passed_over: 0, }, CacheAwareCandidate { index: 1, @@ -633,6 +797,7 @@ mod tests { prompt_tokens: &right, enqueued_turn: 0, order: 1, + passed_over: 0, }, ], 0, diff --git a/crates/skippy-scheduler/src/capacity.rs b/crates/skippy-scheduler/src/capacity.rs index 7c8cfa96..6de4c32b 100644 --- a/crates/skippy-scheduler/src/capacity.rs +++ b/crates/skippy-scheduler/src/capacity.rs @@ -7,6 +7,10 @@ pub struct EvictableCacheEntry { pub units: u64, pub recompute_cost: u64, pub last_used: u64, + /// Entries with a lower retention priority are evicted first, before + /// recompute value is considered. Serving uses the request tier's + /// priority, so mesh entries go before trusted ones and those before local. + pub retention_priority: u64, } /// Current occupancy for one independently constrained memory component. @@ -144,9 +148,13 @@ pub fn rank_eviction_candidates(entries: &mut [EvictableCacheEntry]) { fn compare_eviction_value(left: &EvictableCacheEntry, right: &EvictableCacheEntry) -> Ordering { let left_units = left.units.max(1); let right_units = right.units.max(1); - u128::from(left.recompute_cost) - .saturating_mul(u128::from(right_units)) - .cmp(&u128::from(right.recompute_cost).saturating_mul(u128::from(left_units))) + left.retention_priority + .cmp(&right.retention_priority) + .then_with(|| { + u128::from(left.recompute_cost) + .saturating_mul(u128::from(right_units)) + .cmp(&u128::from(right.recompute_cost).saturating_mul(u128::from(left_units))) + }) .then_with(|| left.last_used.cmp(&right.last_used)) .then_with(|| left.recompute_cost.cmp(&right.recompute_cost)) .then_with(|| left.id.cmp(&right.id)) @@ -162,6 +170,7 @@ mod tests { units, recompute_cost, last_used, + retention_priority: 0, } } @@ -255,6 +264,27 @@ mod tests { assert!(plan.victim_ids.is_empty()); } + #[test] + fn evicts_lower_retention_priority_before_cheaper_entries() { + let mut entries = vec![ + EvictableCacheEntry { + retention_priority: 2, + ..entry("local-cheap", 30, 1, 1) + }, + entry("mesh-expensive", 30, 300, 2), + EvictableCacheEntry { + retention_priority: 1, + ..entry("trusted-cheap", 30, 1, 0) + }, + ]; + rank_eviction_candidates(&mut entries); + let order = entries + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(); + assert_eq!(order, ["mesh-expensive", "trusted-cheap", "local-cheap"]); + } + #[test] fn evicts_low_recompute_cost_before_older_expensive_entries() { let plan = plan_component_capacity( diff --git a/crates/skippy-scheduler/src/engine.rs b/crates/skippy-scheduler/src/engine.rs index c88cfa74..092d1280 100644 --- a/crates/skippy-scheduler/src/engine.rs +++ b/crates/skippy-scheduler/src/engine.rs @@ -3,7 +3,7 @@ use std::time::{Duration, Instant}; use crate::{ CacheAwareCandidate, IterationPhase, IterationPlan, IterationPrediction, IterationTelemetry, - IterationWork, SchedulerConfig, SchedulerMetrics, Sequence, SequenceStatus, + IterationWork, PriorityPassovers, SchedulerConfig, SchedulerMetrics, Sequence, SequenceStatus, order_cache_aware_candidates, }; @@ -32,6 +32,7 @@ pub struct Scheduler { metrics: SchedulerMetrics, consecutive_prefill_iterations: usize, waiting_turn: u64, + passovers: PriorityPassovers, next_waiting_order: u64, waiting_order_dirty: bool, decode_us_ewma_by_rows: BTreeMap, @@ -55,6 +56,7 @@ impl Scheduler { metrics: SchedulerMetrics::default(), consecutive_prefill_iterations: 0, waiting_turn: 0, + passovers: PriorityPassovers::default(), next_waiting_order: 0, waiting_order_dirty: false, decode_us_ewma_by_rows: BTreeMap::new(), @@ -84,6 +86,7 @@ impl Scheduler { self.metrics.prefix_misses = self.metrics.prefix_misses.saturating_add(1); } sequence.enqueued_turn = self.waiting_turn; + sequence.passover_mark = self.passovers.mark(sequence.priority); sequence.enqueue_order = self.next_waiting_order; self.next_waiting_order = self.next_waiting_order.saturating_add(1); self.waiting.push_back(sequence); @@ -482,6 +485,8 @@ impl Scheduler { }; self.release_memory(&sequence); sequence.reset_for_recompute(); + // Admissions made while it ran did not pass it over. + sequence.passover_mark = self.passovers.mark(sequence.priority); sequence.enqueue_order = self.next_waiting_order; self.next_waiting_order = self.next_waiting_order.saturating_add(1); self.waiting.push_front(sequence); @@ -534,6 +539,7 @@ impl Scheduler { fn admit_waiting(&mut self) -> usize { let mut admitted = 0; + let mut highest_admitted = None; let mut deferred = VecDeque::new(); if self.waiting_order_dirty { let order = order_cache_aware_candidates( @@ -547,6 +553,9 @@ impl Scheduler { prompt_tokens: &sequence.prompt_tokens, enqueued_turn: sequence.enqueued_turn, order: sequence.enqueue_order, + passed_over: self + .passovers + .passed_over(sequence.priority, sequence.passover_mark), }), self.waiting_turn, self.config.cache_aging_cost_per_iteration, @@ -569,12 +578,23 @@ impl Scheduler { continue; } self.reserve_memory(&sequence); + self.passovers.record_selection(sequence.priority); + highest_admitted = highest_admitted.max(Some(sequence.priority)); sequence.status = SequenceStatus::Running; sequence.admitted_at = Some(Instant::now()); self.active.insert(sequence.id.clone(), sequence); admitted += 1; } self.waiting = deferred; + // Passing lower priorities over can age them past another level. + if let Some(highest) = highest_admitted + && self + .waiting + .iter() + .any(|waiting| waiting.priority < highest) + { + self.waiting_order_dirty = true; + } self.refresh_counts(); admitted } @@ -1285,4 +1305,36 @@ mod tests { assert_eq!(scheduler.sequence("cold").unwrap().enqueued_turn, 0); } } + + #[test] + fn a_preempted_sequence_is_not_aged_by_admissions_made_while_it_ran() { + let mut scheduler = Scheduler::new(SchedulerConfig { + max_active_sequences: 1, + memory_components: vec![MemoryComponent { + name: "kv".into(), + capacity_bytes: 2, + resident_bytes: 0, + bytes_per_token: 1, + bytes_per_sequence: 0, + }], + ..SchedulerConfig::default() + }); + scheduler + .submit(sequence("mesh", 2, 4).with_admission_tokens(1)) + .unwrap(); + scheduler.plan_iteration(); + assert_eq!(scheduler.snapshot().active_ids, ["mesh"]); + for _ in 0..2 * crate::PRIORITY_AGING_TURNS { + scheduler.passovers.record_selection(2); + } + assert_eq!(scheduler.preempt_for_component_pressure(&[3]), ["mesh"]); + scheduler.preempt_for_component_pressure(&[0]); + let mut local = sequence("local", 2, 4).with_admission_tokens(1); + local.priority = 2; + scheduler.submit(local).unwrap(); + + scheduler.plan_iteration(); + + assert_eq!(scheduler.snapshot().active_ids, ["local"]); + } } diff --git a/crates/skippy-scheduler/src/lib.rs b/crates/skippy-scheduler/src/lib.rs index b4283806..c5a2bd6d 100644 --- a/crates/skippy-scheduler/src/lib.rs +++ b/crates/skippy-scheduler/src/lib.rs @@ -12,8 +12,9 @@ mod sequence; mod telemetry; pub use cache_policy::{ - CacheAffinity, CacheAwareCandidate, StageCacheAffinity, order_cache_aware_candidates, - order_cache_aware_candidates_with_anchor, select_cache_aware_candidate, + CacheAffinity, CacheAwareCandidate, PRIORITY_AGING_TURNS, PriorityPassovers, + StageCacheAffinity, order_cache_aware_candidates, order_cache_aware_candidates_with_anchor, + select_cache_aware_candidate, }; pub use capacity::{ CapacityDemand, CapacityPlan, ComponentCapacitySnapshot, EvictableCacheEntry, diff --git a/crates/skippy-scheduler/src/sequence.rs b/crates/skippy-scheduler/src/sequence.rs index 690550d8..5357faf1 100644 --- a/crates/skippy-scheduler/src/sequence.rs +++ b/crates/skippy-scheduler/src/sequence.rs @@ -47,6 +47,8 @@ pub struct Sequence { pub(crate) prefill_cursor: usize, pub(crate) enqueued_turn: u64, pub(crate) enqueue_order: u64, + /// [`crate::PriorityPassovers::mark`] when the sequence started waiting. + pub(crate) passover_mark: u64, } impl Sequence { @@ -75,6 +77,7 @@ impl Sequence { prefill_cursor: 0, enqueued_turn: 0, enqueue_order: 0, + passover_mark: 0, } } diff --git a/crates/skippy-serving/Cargo.toml b/crates/skippy-serving/Cargo.toml index 42e6a468..021b0d54 100644 --- a/crates/skippy-serving/Cargo.toml +++ b/crates/skippy-serving/Cargo.toml @@ -55,6 +55,8 @@ uuid = { version = "1", features = ["v4"] } windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] } [dev-dependencies] +reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] } skippy-runtime = { path = "../skippy-runtime", version = "0.80.0", features = ["test-support"] } tempfile = "3" +tokio = { version = "1", features = ["process", "time"] } tower = { version = "0.5", features = ["util"] } diff --git a/crates/skippy-serving/README.md b/crates/skippy-serving/README.md index 90c30671..49fbc020 100644 --- a/crates/skippy-serving/README.md +++ b/crates/skippy-serving/README.md @@ -30,6 +30,50 @@ library's ABI as well. This entry point uses local bundles/cache only; acquisiti is explicit. Static native test builds retain their existing linked-runtime path. This adds native startup, not model-reference resolution or clean-install proof. +## Shared speculative execution + +The iteration scheduler combines equal-length +verification windows from independent sessions on a complete causal target. +The combined implementation requires native ABI `0.1.88`. Each lane keeps its own sampler, checkpoint, +rejection boundary and repair. Unsupported models and batches exceeding the +actual native microbatch capacity use independent verification. + +The scheduler waits at most 300 microseconds of idle time to collect a wave; +useful draft and repair work does not consume that waiting budget. Repairs are +barriers for their own session; unscoped runtime mutations remain global +barriers. Cancellation and stale-position checks run before target execution. +`stage.shared_verification` telemetry records actual shared forwards and their +batch size. Sharing is enabled by default; +`SKIPPY_SHARED_VERIFY=0` retains independent verification for diagnostics. + +The scheduler also collects ready DFlash proposals for one draft +forward. It accepts different block lengths, checks cancellation and target +positions before submission, and uses the same 300-microsecond idle waiting +budget. `stage.shared_draft` records the number of lanes actually sharing a +forward; unsupported draft heads or excess capacity run independently. The +draft path is enabled by default; `SKIPPY_SHARED_DRAFT=0` retains independent +submissions. The two switches can be disabled separately for comparison. +Selector/convolution drafts share only equal-width blocks; different widths +run independently, while ordinary independent-row drafts retain ragged batching. +With shared drafting, adaptive sizing learns each lane's share of execution +cost for drafting, verification, repair and measured serial steps. Queue time +remains in request latency telemetry; it is excluded from the cost fit, so a +peer's work cannot be mistaken for a more expensive draft width. These +estimates are stored separately from the existing local and split estimates. + +With shared drafting, shared verification and adaptive sizing, concurrent lanes use +aggregate acceptance and keep one width for eight observed windows per lane. +This lets the target batch their verification rather than fragmenting it with +independent width choices. Request tails retain their own smaller limits, and +serial choices are reconsidered after a draft probe. Single-lane and split +requests keep the existing per-request policy. Sampling, checkpoint and repair +ownership remain per session. + +Batch geometry can change the native backend's floating-point reductions, so +greedy text need not be identical to independent execution. Every proposal is +still checked by its lane's target sampler. Use the zero-valued switches above +to compare independent execution when investigating a numerical difference. + ## Architecture Role Each embedded server or server process owns one contiguous layer range. Host @@ -142,7 +186,7 @@ deadline handling. - `serve --stage-transport binary` is the tuned binary stage-to-stage path. - Binary stages participate in the breaking generation-18 stage protocol. - Stage compatibility requires the complete `stage-generation-18` control, + Stage compatibility requires the complete `stage-generation-19` control, status-list, strict-content-identity, stage-admission, and stale-window-discard bundle, including bounded causal decision readouts. Older peers are rejected during split planning rather than being mixed into a generation-18 topology. diff --git a/crates/skippy-serving/src/binary_transport/binary_kv.rs b/crates/skippy-serving/src/binary_transport/binary_kv.rs index 6c8810e9..be8c77bd 100644 --- a/crates/skippy-serving/src/binary_transport/binary_kv.rs +++ b/crates/skippy-serving/src/binary_transport/binary_kv.rs @@ -638,7 +638,7 @@ pub(in crate::binary_transport) fn maybe_record_binary_prefill( } } } - match kv.record_resident_prefix( + match kv.record_resident_prefix_for_idle_capture( runtime, session_id, &identity, @@ -923,7 +923,7 @@ pub(in crate::binary_transport) fn maybe_record_binary_full_prefill( } } } - match kv.record_resident_prefix( + match kv.record_resident_prefix_for_idle_capture( runtime, session_id, &identity, diff --git a/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs b/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs index 2bc8b687..8522fed2 100644 --- a/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs +++ b/crates/skippy-serving/src/binary_transport/binary_messaging/prefill_recording.rs @@ -263,7 +263,7 @@ mod tests { .unwrap(); let mut config = prefix_cache_test_config(); config.source_model_sha256 = Some("ab".repeat(32)); - let kv = KvStageIntegration::from_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs b/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs index edecc633..fb4acd8a 100644 --- a/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs +++ b/crates/skippy-serving/src/binary_transport/binary_messaging/public_frontend.rs @@ -64,6 +64,7 @@ pub(super) fn start(launch: PublicFrontendLaunch) -> Result StageConfig { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-serving/src/embedded.rs b/crates/skippy-serving/src/embedded.rs index f286c8c6..e193bbfa 100644 --- a/crates/skippy-serving/src/embedded.rs +++ b/crates/skippy-serving/src/embedded.rs @@ -579,9 +579,14 @@ fn openai_backend_router_with_lifecycle_observer( backend: Arc, lifecycle_observer: Option>, ) -> Router { - let config = lifecycle_observer.map_or_else(InferenceFrontendConfig::default, |observer| { - InferenceFrontendConfig::default().with_lifecycle_observer(observer) - }); + // The embedder is the trusted upstream: it strips client-supplied request + // class headers at its own ingress and stamps its classification before + // it forwards a request to this in-process server. + let config = InferenceFrontendConfig::default().with_trusted_request_class_headers(); + let config = match lifecycle_observer { + Some(observer) => config.with_lifecycle_observer(observer), + None => config, + }; skippy_inference_api::router_for_with_config(backend, config) } @@ -772,6 +777,89 @@ mod tests { } } + #[derive(Default)] + struct ClassCaptureBackend { + classes: Mutex>, + } + + #[async_trait::async_trait] + impl InferenceBackend for ClassCaptureBackend { + async fn models( + &self, + ) -> skippy_inference_api::InferenceResult> { + Ok(vec![skippy_inference_api::ModelObject::new("class-model")]) + } + + async fn chat_completion( + &self, + request: skippy_inference_api::generation::GenerationRequest, + ) -> skippy_inference_api::InferenceResult< + skippy_inference_api::generation::GenerationResponse, + > { + Ok(skippy_inference_api::generation::GenerationResponse::new( + request.model, + "ok", + skippy_inference_api::Usage::new(1, 1), + )) + } + + async fn chat_completion_with_context( + &self, + request: skippy_inference_api::generation::GenerationRequest, + context: skippy_inference_api::InferenceRequestContext, + ) -> skippy_inference_api::InferenceResult< + skippy_inference_api::generation::GenerationResponse, + > { + self.classes.lock().unwrap().push(context.request_class()); + self.chat_completion(request).await + } + + async fn chat_completion_stream( + &self, + _request: skippy_inference_api::generation::GenerationRequest, + _context: skippy_inference_api::InferenceRequestContext, + ) -> skippy_inference_api::InferenceResult< + skippy_inference_api::generation::GenerationEventStream, + > { + Ok(Box::pin(futures_util::stream::empty())) + } + } + + /// An embedder such as MeshLLM classifies a request at its own ingress and + /// forwards it to this server with the class in headers. + #[tokio::test] + async fn embedded_openai_backend_keeps_the_embedders_request_class() { + use axum::{body::Body, http::Request}; + use skippy_inference_api::{ + CACHE_PARTITION_HEADER, InferenceRequestClass, InferenceRequestTier, + REQUEST_TIER_HEADER, + }; + use tower::ServiceExt; + + let backend = Arc::new(ClassCaptureBackend::default()); + let response = openai_backend_router_with_lifecycle_observer(backend.clone(), None) + .oneshot( + Request::post("/v1/chat/completions") + .header("content-type", "application/json") + .header(REQUEST_TIER_HEADER, "trusted") + .header(CACHE_PARTITION_HEADER, "private") + .body(Body::from( + r#"{"model":"class-model","messages":[{"role":"user","content":"test"}]}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert!(response.status().is_success()); + assert_eq!( + *backend.classes.lock().unwrap(), + [InferenceRequestClass::new( + InferenceRequestTier::Trusted, + true + )], + ); + } + #[tokio::test] async fn failed_server_load_releases_its_bound_resources() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/skippy-serving/src/frontend/admission.rs b/crates/skippy-serving/src/frontend/admission.rs index 7515380b..44df4300 100644 --- a/crates/skippy-serving/src/frontend/admission.rs +++ b/crates/skippy-serving/src/frontend/admission.rs @@ -5,6 +5,7 @@ use axum::http::StatusCode; use skippy_inference_api::InferenceError; #[cfg(test)] use skippy_inference_api::InferenceErrorKind; +use skippy_inference_api::InferenceRequestTier; use skippy_inference_api::InferenceResult; use std::sync::Arc; use std::sync::Mutex; @@ -32,6 +33,8 @@ pub const DECODE_BATCH_HEADROOM_TOKENS: usize = 512; #[derive(Debug)] pub(crate) struct GenerationTokenBudget { capacity_tokens: usize, + /// Tokens only `local` requests may reserve. Lower tiers share the rest. + local_reserve_tokens: usize, state: Mutex, #[cfg(test)] released: Condvar, @@ -47,6 +50,7 @@ struct GenerationTokenBudgetState { pub(super) struct GenerationTokenBudgetRequest { prompt_tokens: usize, max_tokens: u32, + tier: InferenceRequestTier, } #[derive(Debug)] @@ -58,14 +62,19 @@ pub(super) struct GenerationTokenReservation { impl GenerationTokenBudget { /// All frontends sharing a runtime reserve against one aggregate pool. + /// The first frontend sets the pool's `local` reserve. pub(crate) fn shared_for_runtime( runtime: &mut crate::runtime_state::RuntimeState, configured_tokens: usize, + local_reserve_percent: u8, ) -> 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)); + let budget = Arc::new( + Self::for_runtime(runtime, configured_tokens) + .with_local_reserve_percent(local_reserve_percent), + ); runtime.generation_token_budget = Some(Arc::clone(&budget)); budget } @@ -88,6 +97,7 @@ impl GenerationTokenBudget { pub(super) fn new(ctx_size: usize) -> Self { Self { capacity_tokens: ctx_size.max(1), + local_reserve_tokens: 0, state: Mutex::new(GenerationTokenBudgetState::default()), #[cfg(test)] released: Condvar::new(), @@ -95,17 +105,41 @@ impl GenerationTokenBudget { } } + /// Hold back `percent` of the pool for `local` requests. Lower tiers + /// cannot reserve into that share; `local` requests can use all of it. + /// The reserve rounds up, so lower tiers never get more than the rest. + pub(super) fn with_local_reserve_percent(mut self, percent: u8) -> Self { + let percent = usize::from(percent.min(100)); + self.local_reserve_tokens = self + .capacity_tokens + .saturating_mul(percent) + .div_ceil(100) + .min(self.capacity_tokens); + self + } + + /// The share of the pool a request at `tier` may occupy together with + /// everything already reserved. + fn capacity_for(&self, tier: InferenceRequestTier) -> usize { + match tier { + InferenceRequestTier::Local => self.capacity_tokens, + InferenceRequestTier::Trusted | InferenceRequestTier::Mesh => self + .capacity_tokens + .saturating_sub(self.local_reserve_tokens), + } + } + pub(super) fn try_reserve( self: &Arc, request: GenerationTokenBudgetRequest, ) -> InferenceResult> { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let mut state = self .state .lock() .map_err(|_| InferenceError::backend("generation token budget lock poisoned"))?; - if state.active_tokens.saturating_add(tokens) > self.capacity_tokens { + if state.active_tokens.saturating_add(tokens) > self.capacity_for(request.tier) { return Ok(None); } state.active_tokens = state.active_tokens.saturating_add(tokens); @@ -121,12 +155,12 @@ impl GenerationTokenBudget { request: GenerationTokenBudgetRequest, ) -> InferenceResult { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let state = self .state .lock() .map_err(|_| InferenceError::backend("generation token budget lock poisoned"))?; - Ok(state.active_tokens.saturating_add(tokens) <= self.capacity_tokens) + Ok(state.active_tokens.saturating_add(tokens) <= self.capacity_for(request.tier)) } pub(super) fn release_notification(&self) -> &Notify { @@ -150,7 +184,7 @@ impl GenerationTokenBudget { cancellation: Option<&skippy_inference_api::CancellationToken>, ) -> InferenceResult { let tokens = request.reservation_tokens(); - self.ensure_request_fits(tokens)?; + self.ensure_request_fits(tokens, request.tier)?; let deadline = Instant::now() + admission_timeout; let mut state = self .state @@ -160,7 +194,7 @@ impl GenerationTokenBudget { if cancellation.is_some_and(skippy_inference_api::CancellationToken::is_cancelled) { return Err(InferenceError::backend("request cancelled")); } - if state.active_tokens.saturating_add(tokens) <= self.capacity_tokens { + if state.active_tokens.saturating_add(tokens) <= self.capacity_for(request.tier) { state.active_tokens = state.active_tokens.saturating_add(tokens); return Ok(GenerationTokenReservation { budget: self.clone(), @@ -204,12 +238,26 @@ impl GenerationTokenBudget { self.capacity_tokens } - fn ensure_request_fits(&self, requested_tokens: usize) -> InferenceResult<()> { - if requested_tokens <= self.capacity_tokens { + fn ensure_request_fits( + &self, + requested_tokens: usize, + tier: InferenceRequestTier, + ) -> InferenceResult<()> { + let capacity = self.capacity_for(tier); + if requested_tokens <= capacity { return Ok(()); } + if capacity == self.capacity_tokens { + return Err(InferenceError::context_length_exceeded(format!( + "request requires {requested_tokens} KV tokens but the runtime pool holds {}", + self.capacity_tokens + ))); + } + // Worded as an overflow, so a mesh router retries it on another node. Err(InferenceError::context_length_exceeded(format!( - "request requires {requested_tokens} KV tokens but the runtime pool holds {}", + "request requires {requested_tokens} KV tokens, which exceeds the {capacity} of the \ + {}-token runtime pool that {tier} requests may use; the rest is reserved for local \ + requests", self.capacity_tokens ))) } @@ -228,9 +276,16 @@ impl GenerationTokenBudgetRequest { Self { prompt_tokens, max_tokens, + tier: InferenceRequestTier::default(), } } + /// Reserve as a request at `tier`. + pub(super) fn with_tier(mut self, tier: InferenceRequestTier) -> Self { + self.tier = tier; + self + } + pub(super) fn reservation_tokens(self) -> usize { let max_tokens = usize::try_from(self.max_tokens).unwrap_or(usize::MAX); let decode_headroom = max_tokens.min(DECODE_BATCH_HEADROOM_TOKENS); @@ -357,8 +412,8 @@ mod tests { 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); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512, 0); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, 512, 0); assert!(Arc::ptr_eq(&first, &second)); let reservation = first .try_reserve(GenerationTokenBudgetRequest::new(768, 0)) @@ -468,4 +523,13 @@ mod tests { assert!(error.to_string().contains("KV token budget")); assert_eq!(budget.active_tokens(), 800); } + + #[test] + fn the_local_reserve_rounds_up() { + let budget = GenerationTokenBudget::new(10).with_local_reserve_percent(25); + assert_eq!(budget.capacity_for(InferenceRequestTier::Mesh), 7); + assert_eq!(budget.capacity_for(InferenceRequestTier::Local), 10); + let all = GenerationTokenBudget::new(10).with_local_reserve_percent(100); + assert_eq!(all.capacity_for(InferenceRequestTier::Trusted), 0); + } } diff --git a/crates/skippy-serving/src/frontend/backend.rs b/crates/skippy-serving/src/frontend/backend.rs index 1e7b0a97..ab0fec18 100644 --- a/crates/skippy-serving/src/frontend/backend.rs +++ b/crates/skippy-serving/src/frontend/backend.rs @@ -485,6 +485,7 @@ impl GenerationAdmissionController { work: GenerationAdmissionWork, scheduling: GenerationAdmissionScheduling, ) -> InferenceResult<(GenerationAdmissionPermit, Option)> { + let scheduling = scheduling.with_tier(ids.request_tier()); let deadline = if admission_timeout.is_zero() { None } else { @@ -553,13 +554,15 @@ impl GenerationAdmissionController { if cancellation.is_cancelled() { return Err(request_cancelled_error()); } + let tier = scheduling.tier(); let claim = self.generation_limit.admission_queue().claim_or_enqueue( self.generation_limit.semaphore(), self.generation_token_budget.clone(), GenerationTokenBudgetRequest::new( usize::try_from(work.prompt_tokens).unwrap_or(usize::MAX), u32::try_from(work.decode_tokens).unwrap_or(u32::MAX), - ), + ) + .with_tier(tier), scheduling, self.generation_queue_depth.clone(), self.generation_queue_limit, @@ -581,8 +584,8 @@ impl GenerationAdmissionController { self.generation_limit.note_queued_demand(); 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); + let predicted_wait_ms = self.generation_service_estimator.predicted_wait_ms(tier); + let queued_work = self.generation_service_estimator.reserve_queued(work, tier); let resources = lease .acquire( self.generation_limit.semaphore(), @@ -902,6 +905,7 @@ impl StageOpenAiBackend { scheduling: GenerationAdmissionScheduling, ) -> InferenceResult<(GenerationAdmissionPermit, Option)> { let admission_started = Instant::now(); + let tier = ids.request_tier(); let result = GenerationAdmissionController::for_backend(self) .acquire_scheduled_work( ids, @@ -942,7 +946,9 @@ impl StageOpenAiBackend { "llama_stage.generation_admission_error".to_string(), json!(error.body().error.message), ); - if let Some(predicted_wait_ms) = self.generation_service_estimator.predicted_wait_ms() { + if let Some(predicted_wait_ms) = + self.generation_service_estimator.predicted_wait_ms(tier) + { attrs.insert( "llama_stage.generation_predicted_wait_ms".to_string(), json!(predicted_wait_ms), @@ -1053,6 +1059,7 @@ impl StageOpenAiBackend { context: InferenceRequestContext, ids: InferenceGenerationIds, ) -> InferenceResult { + let ids = ids.with_chat_template(prompt.cache_template_digest); let (prompt, prepared_text) = if prompt.has_media() { (prompt, None) } else { @@ -1150,6 +1157,7 @@ impl StageOpenAiBackend { context: InferenceRequestContext, ids: InferenceGenerationIds, ) -> InferenceResult { + let ids = ids.with_chat_template(prompt.cache_template_digest); let (prompt, prepared_text) = if prompt.has_media() { (prompt, None) } else { @@ -1306,3 +1314,5 @@ impl StageOpenAiBackend { #[cfg(test)] mod tests; +#[cfg(test)] +mod tier_admission_tests; diff --git a/crates/skippy-serving/src/frontend/backend/inference.rs b/crates/skippy-serving/src/frontend/backend/inference.rs index edc949f4..be874722 100644 --- a/crates/skippy-serving/src/frontend/backend/inference.rs +++ b/crates/skippy-serving/src/frontend/backend/inference.rs @@ -22,7 +22,17 @@ impl InferenceBackend for StageOpenAiBackend { /// Serve System One requests through the backend's selected execution path. async fn system_one(&self, request: SystemOneRequest) -> InferenceResult { - self.serve_system_one(request).await + self.serve_system_one(request, Default::default()).await + } + + /// Serve System One at the request's tier and in its cache partition. + async fn system_one_with_context( + &self, + request: SystemOneRequest, + context: InferenceRequestContext, + ) -> InferenceResult { + self.serve_system_one(request, context.request_class()) + .await } async fn chat_completion( @@ -37,9 +47,10 @@ impl InferenceBackend for StageOpenAiBackend { /// Keep the scope through prompt preparation, native request IDs and cache selection. async fn chat_completion_with_context( &self, - request: GenerationRequest, + mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let ids = generation_ids( InferenceCacheHints::from_chat_request(&request), request.agent_session(), @@ -193,9 +204,10 @@ impl InferenceBackend for StageOpenAiBackend { /// Retain the context in the native worker while producing bounded response events. async fn chat_completion_stream( &self, - request: GenerationRequest, + mut request: GenerationRequest, context: InferenceRequestContext, ) -> InferenceResult { + request.request_class = context.request_class(); let ids = generation_ids( InferenceCacheHints::from_chat_request(&request), request.agent_session(), diff --git a/crates/skippy-serving/src/frontend/backend/tests/admission.rs b/crates/skippy-serving/src/frontend/backend/tests/admission.rs index 3fad40b4..6c076ae6 100644 --- a/crates/skippy-serving/src/frontend/backend/tests/admission.rs +++ b/crates/skippy-serving/src/frontend/backend/tests/admission.rs @@ -464,7 +464,7 @@ async fn inflated_prediction_waits_for_capacity_and_preserves_queue_bounds() { let timeout = Duration::from_secs(1); let predicted = controller .generation_service_estimator - .predicted_wait_ms() + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local) .unwrap(); assert!(predicted > timeout.as_secs_f64() * 1_000.0); let ids = trusted_ids("agent-2"); @@ -499,7 +499,9 @@ async fn inflated_prediction_waits_for_capacity_and_preserves_queue_bounds() { 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(), + controller + .generation_service_estimator + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local), Some(0.0) ); assert!( @@ -546,7 +548,9 @@ async fn advisory_prediction_does_not_bypass_an_expired_admission_deadline() { 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(), + controller + .generation_service_estimator + .predicted_wait_ms(skippy_inference_api::InferenceRequestTier::Local), Some(0.0) ); } diff --git a/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs b/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs new file mode 100644 index 00000000..04eb14d9 --- /dev/null +++ b/crates/skippy-serving/src/frontend/backend/tier_admission_tests.rs @@ -0,0 +1,434 @@ +//! Admission by request tier: higher tiers are admitted first, keep their +//! room in the waiting queue and in the KV pool, and are not held behind a +//! lower tier's head-of-line reservation. + +use super::*; +use crate::frontend::generation::ADMISSION_STARVATION_BOUND_TURNS; +use skippy_inference_api::{CancellationToken, InferenceRequestClass, InferenceRequestTier}; +use skippy_scheduler::PRIORITY_AGING_TURNS; + +/// A generous bound for an event the test waits on, so a slow or busy +/// machine does not fail it. +const WAIT: Duration = Duration::from_secs(60); + +fn controller( + generation_concurrency: usize, + generation_queue_limit: usize, + token_capacity: usize, + local_reserve_percent: u8, +) -> 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) + .with_local_reserve_percent(local_reserve_percent), + ), + } +} + +fn ids(session_id: &str, tier: InferenceRequestTier) -> InferenceGenerationIds { + InferenceGenerationIds::new_with_trust( + InferenceCacheHints::default(), + Some(session_id), + true, + None, + ) + .with_request_class(InferenceRequestClass::new(tier, false)) +} + +async fn admit( + controller: &GenerationAdmissionController, + session_id: &str, + tier: InferenceRequestTier, + tokens: usize, +) -> InferenceResult<(GenerationAdmissionPermit, Option)> { + controller + .acquire_work( + &ids(session_id, tier), + &CancellationToken::new(), + Duration::ZERO, + GenerationAdmissionWork::new(tokens, 0), + ) + .await +} + +async fn wait_for_queue_depth(controller: &GenerationAdmissionController, depth: usize) { + tokio::time::timeout(WAIT, async { + while controller.generation_queue_depth.load(Ordering::Acquire) != depth { + tokio::task::yield_now().await; + } + }) + .await + .expect("waiters reached the queue"); +} + +#[tokio::test] +async fn the_local_reserve_is_kept_for_local_requests() { + let controller = controller(4, 4, 10, 50); + let too_large = admit(&controller, "mesh-large", InferenceRequestTier::Mesh, 6).await; + let error = too_large + .err() + .expect("a mesh request cannot use the reserve"); + assert!( + error.body().error.message.contains("reserved for local"), + "{}", + error.body().error.message + ); + + let mesh = admit(&controller, "mesh", InferenceRequestTier::Mesh, 5) + .await + .expect("mesh fits outside the reserve"); + let local = tokio::time::timeout( + WAIT, + admit(&controller, "local", InferenceRequestTier::Local, 5), + ) + .await + .expect("local is not queued behind mesh") + .expect("local fits in the reserve"); + assert_eq!(controller.generation_token_budget.active_tokens(), 10); + drop((mesh, local)); +} + +#[tokio::test] +async fn a_lower_tier_cannot_fill_the_waiting_room_ahead_of_local() { + let controller = controller(1, 1, 100, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + + let waiting_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&waiting_controller, "mesh-1", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + let full = admit(&controller, "mesh-2", InferenceRequestTier::Mesh, 1).await; + assert!(full.is_err(), "the mesh share of the room is full"); + + let local_controller = controller.clone(); + let local_waiter = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 1).await + }); + wait_for_queue_depth(&controller, 2).await; + + // The younger local waiter is admitted first. + drop(active); + let local = tokio::time::timeout(WAIT, local_waiter) + .await + .expect("local admitted") + .unwrap() + .expect("local admission succeeded"); + assert!(!mesh_waiter.is_finished()); + drop(local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted after local") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} + +#[tokio::test] +async fn an_unfitting_senior_mesh_waiter_does_not_hold_back_local_requests() { + // 10 tokens, 5 of them reserved for local requests. + let controller = controller(4, 4, 10, 50); + // A long local request keeps the mesh share full. + let long_local = admit(&controller, "long-local", InferenceRequestTier::Local, 6) + .await + .expect("local fits"); + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + + // Past the starvation bound, local requests that fit are still admitted. + for wave in 0..ADMISSION_STARVATION_BOUND_TURNS + 4 { + let local = tokio::time::timeout( + WAIT, + admit( + &controller, + &format!("local-{wave}"), + InferenceRequestTier::Local, + 4, + ), + ) + .await + .unwrap_or_else(|_| panic!("local request {wave} was held behind the mesh waiter")) + .expect("local admission succeeded"); + drop(local); + } + assert!(!mesh_waiter.is_finished()); + + drop(long_local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted once the pool drains") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} + +#[tokio::test] +async fn an_older_mesh_waiter_does_not_take_a_starving_local_waiters_hold() { + let controller = controller(4, 8, 10, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 6) + .await + .expect("the pool is free"); + // The oldest waiter is a mesh request; a large local one queues behind it. + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 5).await + }); + wait_for_queue_depth(&controller, 1).await; + let large_controller = controller.clone(); + let large_local = tokio::spawn(async move { + admit( + &large_controller, + "large-local", + InferenceRequestTier::Local, + 7, + ) + .await + }); + wait_for_queue_depth(&controller, 2).await; + + // Smaller local requests pass the large one until it has waited long enough. + for turn in 0..ADMISSION_STARVATION_BOUND_TURNS { + let small = tokio::time::timeout( + WAIT, + admit( + &controller, + &format!("small-{turn}"), + InferenceRequestTier::Local, + 4, + ), + ) + .await + .unwrap_or_else(|_| panic!("small local request {turn} was held")) + .expect("small local admission succeeded"); + drop(small); + } + + // Now the pool drains for the large local request, not for the older + // mesh one: a small local newcomer waits. Had it been admitted, its + // tokens would keep the large request out of the drained pool. + let small_controller = controller.clone(); + let late_small = tokio::spawn(async move { + admit( + &small_controller, + "late-small", + InferenceRequestTier::Local, + 4, + ) + .await + }); + wait_for_queue_depth(&controller, 3).await; + drop(active); + let large = tokio::time::timeout(WAIT, large_local) + .await + .expect("the large local request is admitted once the pool drains") + .unwrap() + .expect("large local admission succeeded"); + drop(large); + for waiter in [late_small, mesh_waiter] { + let admitted = tokio::time::timeout(WAIT, waiter) + .await + .expect("the remaining waiters are admitted") + .unwrap() + .expect("admission succeeded"); + drop(admitted); + } +} + +#[tokio::test] +async fn a_local_request_is_admitted_ahead_of_a_long_mesh_queue() { + const MESH_WAITERS: usize = 40; + let controller = controller(1, 64, 1_000, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + // Each mesh request holds the lane until the test releases it. + let (admitted_tx, mut admitted_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut releases = Vec::new(); + for index in 0..MESH_WAITERS { + let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); + releases.push(Some(release_tx)); + let (mesh_controller, admitted_tx) = (controller.clone(), admitted_tx.clone()); + tokio::spawn(async move { + let permit = admit( + &mesh_controller, + &format!("mesh-{index}"), + InferenceRequestTier::Mesh, + 1, + ) + .await; + // Only a request that holds the lane counts as admitted. + let _ = admitted_tx.send( + permit + .as_ref() + .map(|_| index) + .map_err(|error| error.body().error.message.clone()), + ); + let _ = release_rx.await; + drop(permit); + }); + } + wait_for_queue_depth(&controller, MESH_WAITERS).await; + + // Serve the mesh queue until every remaining mesh waiter is past the + // starvation bound, keeping the last one admitted on the lane. + drop(active); + let bound = usize::try_from(ADMISSION_STARVATION_BOUND_TURNS).unwrap(); + let mut on_lane = None; + for served in 0..bound { + let index = tokio::time::timeout(WAIT, admitted_rx.recv()) + .await + .expect("a mesh request is admitted") + .unwrap() + .expect("mesh admission succeeded"); + if served + 1 < bound { + releases[index].take().unwrap().send(()).unwrap(); + } else { + on_lane = Some(index); + } + } + + // A local request that arrives now goes next, not after the mesh queue. + let local_controller = controller.clone(); + let local = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 1).await + }); + wait_for_queue_depth(&controller, MESH_WAITERS - bound + 1).await; + releases[on_lane.unwrap()].take().unwrap().send(()).unwrap(); + let local = tokio::time::timeout(WAIT, local) + .await + .expect("the local request is admitted next") + .unwrap() + .expect("local admission succeeded"); + assert!( + admitted_rx.try_recv().is_err(), + "no mesh request went first" + ); + drop(local); + for release in releases.into_iter().flatten() { + let _ = release.send(()); + } +} + +/// Which waiter one admission wave went to. +enum Wave { + Mesh(T), + Local(T), +} + +#[tokio::test] +async fn a_mesh_request_passed_over_by_local_ones_is_admitted_in_bounded_time() { + let controller = controller(1, 8, 1_000, 0); + let mut on_lane = admit(&controller, "active", InferenceRequestTier::Local, 1) + .await + .expect("the lane is free"); + let mesh_controller = controller.clone(); + let mut mesh = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 1).await + }); + wait_for_queue_depth(&controller, 1).await; + + // A steady stream of local requests: one is always waiting with the mesh one. + let limit = 2 * PRIORITY_AGING_TURNS + 1; + for passed in 0..=limit { + let local_controller = controller.clone(); + let mut local = tokio::spawn(async move { + admit( + &local_controller, + &format!("local-{passed}"), + InferenceRequestTier::Local, + 1, + ) + .await + }); + wait_for_queue_depth(&controller, 2).await; + drop(on_lane); + let wave = tokio::time::timeout(WAIT, async { + tokio::select! { + admitted = &mut mesh => Wave::Mesh(admitted), + admitted = &mut local => Wave::Local(admitted), + } + }) + .await + .unwrap_or_else(|_| panic!("nobody was admitted in wave {passed}")); + match wave { + Wave::Mesh(admitted) => { + let mesh = admitted.unwrap().expect("mesh admission succeeded"); + assert!( + passed >= 2 * PRIORITY_AGING_TURNS, + "mesh went early after {passed}" + ); + drop(mesh); + let local = tokio::time::timeout(WAIT, &mut local) + .await + .expect("the waiting local request follows") + .unwrap() + .expect("local admission succeeded"); + drop(local); + return; + } + Wave::Local(admitted) => { + on_lane = admitted.unwrap().expect("local admission succeeded"); + } + } + assert!(passed < limit, "mesh was never admitted"); + } +} + +/// A `mesh` waiter elected while a bigger `local` waiter did not fit loses +/// the lane once a release makes room for the `local` one. +#[tokio::test] +async fn a_local_waiter_that_fits_after_a_release_goes_before_an_elected_mesh_one() { + let controller = controller(1, 8, 10, 0); + let active = admit(&controller, "active", InferenceRequestTier::Local, 6) + .await + .expect("the lane is free"); + let mesh_controller = controller.clone(); + let mesh_waiter = tokio::spawn(async move { + admit(&mesh_controller, "mesh", InferenceRequestTier::Mesh, 2).await + }); + // The mesh request queues first, so it is waiter 0. + wait_for_queue_depth(&controller, 1).await; + let local_controller = controller.clone(); + let local_waiter = tokio::spawn(async move { + admit(&local_controller, "local", InferenceRequestTier::Local, 5).await + }); + // Both wait, and the mesh waiter (id 0) is elected: only it fits the + // tokens left beside the active request. + let queue = controller.generation_limit.admission_queue(); + tokio::time::timeout(WAIT, async { + while queue.election_for_test() != (2, Some(0)) { + tokio::task::yield_now().await; + } + }) + .await + .expect("the mesh waiter was elected with both waiting"); + + drop(active); + let local = tokio::time::timeout(WAIT, local_waiter) + .await + .expect("local admitted") + .unwrap() + .expect("local admission succeeded"); + assert!(!mesh_waiter.is_finished()); + drop(local); + let mesh = tokio::time::timeout(WAIT, mesh_waiter) + .await + .expect("mesh admitted after local") + .unwrap() + .expect("mesh admission succeeded"); + drop(mesh); +} diff --git a/crates/skippy-serving/src/frontend/embedded_generation.rs b/crates/skippy-serving/src/frontend/embedded_generation.rs index 285453bc..e0a00be8 100644 --- a/crates/skippy-serving/src/frontend/embedded_generation.rs +++ b/crates/skippy-serving/src/frontend/embedded_generation.rs @@ -217,6 +217,7 @@ impl StageOpenAiBackend { tokens: chunk, request_id, session_id, + request_class: request.ids.request_class(), })?; message.state.set_split_dflash_unattended_rows(unattended); let stage0_timer = PhaseTimer::start(); @@ -796,6 +797,7 @@ impl StageOpenAiBackend { sampling: wire_sampling.clone(), sideband_capacity: skippy_protocol::binary::MAX_STAGE_SIDEBAND_VALUES, native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; decode_message.set_split_dflash(request.split_dflash()); let mut native_mtp = NativeMtpVerifier::default(); @@ -1340,6 +1342,7 @@ impl StageOpenAiBackend { tokens: &input_tokens, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); let dispatched = self.dispatch_embedded_stage_message( @@ -1740,6 +1743,7 @@ impl StageOpenAiBackend { tokens: &verify_inputs, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); let verify = self.execute_embedded_stage_message( diff --git a/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs b/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs index 6be84e1a..8ae98a53 100644 --- a/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs +++ b/crates/skippy-serving/src/frontend/embedded_generation/lifecycle.rs @@ -16,6 +16,7 @@ use crate::frontend::{ generation_receipt::GenerationLifecycleState, speculative::{InferenceSpeculativeStats, SpeculativeDecodeConfig}, util::{openai_backend_error, openai_io_error}, + wire_messages::stop_message, }; use crate::runtime_state::RuntimeState; @@ -24,14 +25,10 @@ use crate::runtime_state::RuntimeState; /// discarded. fn stop_lane_session( stream: &mut TcpStream, - request_id: u64, - session_id: u64, + stop: &StageWireMessage, draft_owed: bool, ) -> std::io::Result<()> { - write_stage_message( - &mut *stream, - &StageWireMessage::stop_with_identity(request_id, session_id), - )?; + write_stage_message(&mut *stream, stop)?; let mut kind = recv_reply(&mut *stream)?.kind; if draft_owed && kind == WireReplyKind::PredictedTokens { kind = recv_reply(&mut *stream)?.kind; @@ -52,8 +49,7 @@ fn stop_lane_session( fn settle_lane_in_background( lane_pool: Arc, lane: PersistentStageLane, - request_id: u64, - session_id: u64, + stop: StageWireMessage, ) { let lane_id = lane.id; let pool = Arc::clone(&lane_pool); @@ -61,7 +57,7 @@ fn settle_lane_in_background( .name("skippy-lane-settle".to_string()) .spawn(move || { let mut lane = lane; - match stop_lane_session(&mut lane.stream, request_id, session_id, true) { + match stop_lane_session(&mut lane.stream, &stop, true) { Ok(()) => pool.return_lane(lane), Err(error) => { tracing::debug!( @@ -564,8 +560,11 @@ impl StageOpenAiBackend { Some(pool) => settle_lane_in_background( pool, lane, - request.ids.request_id, - request.ids.session_id, + stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ), ), None => { let lane_id = lane.id; @@ -578,8 +577,11 @@ impl StageOpenAiBackend { let stop_result = stop_lane_session( &mut lane.stream, - request.ids.request_id, - request.ids.session_id, + &stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ), false, ); self.drop_embedded_runtime_session(request, session_key, SessionEnd::Completed); @@ -707,19 +709,36 @@ mod tests { #[test] fn stopping_a_lane_drains_an_owed_draft_reply_before_the_ack() { let mut stream = stop_peer(&[WireReplyKind::PredictedTokens, WireReplyKind::Ack]); - stop_lane_session(&mut stream, 1, 2, true).unwrap(); + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + true, + ) + .unwrap(); } #[test] fn stopping_a_lane_accepts_an_ack_when_the_draft_went_elsewhere() { let mut stream = stop_peer(&[WireReplyKind::Ack]); - stop_lane_session(&mut stream, 1, 2, true).unwrap(); + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + true, + ) + .unwrap(); } #[test] fn stopping_a_lane_with_no_owed_draft_refuses_a_draft_reply() { let mut stream = stop_peer(&[WireReplyKind::PredictedTokens, WireReplyKind::Ack]); - assert!(stop_lane_session(&mut stream, 1, 2, false).is_err()); + assert!( + stop_lane_session( + &mut stream, + &StageWireMessage::stop_with_identity(1, 2), + false + ) + .is_err() + ); } fn ngram_config() -> SpeculativeDecodeConfig { diff --git a/crates/skippy-serving/src/frontend/generation.rs b/crates/skippy-serving/src/frontend/generation.rs index d069ecc6..e5002460 100644 --- a/crates/skippy-serving/src/frontend/generation.rs +++ b/crates/skippy-serving/src/frontend/generation.rs @@ -10,6 +10,7 @@ mod persistent_lanes; mod queue; mod request_defaults; mod server; +mod service_estimate; mod streaming; mod timeouts; mod tool_call_stream; @@ -48,6 +49,7 @@ pub(in crate::frontend) use incremental_text::recorded_fixture; pub(in crate::frontend) use parsing::*; pub(in crate::frontend) use persistent_lanes::*; pub(in crate::frontend) use queue::*; +pub(in crate::frontend) use service_estimate::*; pub(in crate::frontend) use streaming::*; pub(in crate::frontend) use timeouts::*; pub(in crate::frontend) use types::*; diff --git a/crates/skippy-serving/src/frontend/generation/cache_hints.rs b/crates/skippy-serving/src/frontend/generation/cache_hints.rs index d347b932..661dd364 100644 --- a/crates/skippy-serving/src/frontend/generation/cache_hints.rs +++ b/crates/skippy-serving/src/frontend/generation/cache_hints.rs @@ -1,8 +1,11 @@ use crate::frontend::NativeMtpStats; use crate::frontend::util::now_unix_millis; use crate::frontend::util::stable_wire_id; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use skippy_inference_api::CompletionRequest; use skippy_inference_api::InferenceExecutionScope; +use skippy_inference_api::InferenceRequestClass; +use skippy_inference_api::InferenceRequestTier; use skippy_inference_api::generation::GenerationRequest; use skippy_protocol::binary::StageReplyStats; use std::sync::OnceLock; @@ -118,9 +121,55 @@ impl InferenceGenerationIds { self } + /// Partition native sessions and every cache identity by the request's + /// tier and private flag. The default class (local, not private) keeps + /// identities unchanged, so standalone Skippy behaves as before. + pub(in crate::frontend) fn with_request_class(mut self, class: InferenceRequestClass) -> Self { + if let Some(partition) = class.cache_partition() { + self.session_id = stable_wire_id(&[ + b"tiered-inference-session", + partition.as_bytes(), + &self.session_id.to_le_bytes(), + ]); + self.session_label = format!("{partition}-{}", self.session_label); + self.request_id = stable_wire_id(&[ + b"tiered-inference-request", + partition.as_bytes(), + &self.request_id.to_le_bytes(), + ]); + } + self.cache.request_class = class; + self + } + + /// The tier this request is served at. + pub(in crate::frontend) fn request_tier(&self) -> InferenceRequestTier { + self.cache.request_class.tier() + } + + /// The tier and cache partition this request is served in. + pub(in crate::frontend) fn request_class(&self) -> InferenceRequestClass { + self.cache.request_class + } + pub(in crate::frontend) fn request_id_string(&self) -> String { self.request_id.to_string() } + + /// Separate native session reuse and prefix lookups for explicit renderers. + pub(in crate::frontend) fn with_chat_template(mut self, digest: Option<[u8; 32]>) -> Self { + if let Some(digest) = digest { + self.session_id = stable_wire_id(&[ + b"chat-template-session-v1", + &digest, + &self.session_id.to_le_bytes(), + ]); + self.session_label = + format!("chat-template-{}-{}", self.session_id, self.session_label); + self.cache.chat_template_digest = Some(digest); + } + self + } } fn process_nonce() -> &'static str { @@ -191,6 +240,81 @@ mod tests { ); } + #[test] + fn explicit_chat_templates_stay_inside_the_request_class_partition() { + let class = InferenceRequestClass::new(InferenceRequestTier::Trusted, true); + let make = |digest| InferenceCacheHints { + request_class: class, + chat_template_digest: Some(digest), + ..Default::default() + }; + let first = make([1; 32]).namespace().expect("template namespace"); + let second = make([2; 32]).namespace().expect("template namespace"); + assert_ne!(first, second); + assert_eq!( + InferenceRequestClass::from_cache_namespace(Some(&first)), + class + ); + assert_eq!( + InferenceRequestClass::from_cache_namespace(Some(&second)), + class + ); + } + + #[test] + /// Each tier and the private partition get their own sessions and cache + /// namespace; the default local class keeps the unpartitioned identities. + fn request_classes_partition_sessions_and_cache() { + let make = |class| { + InferenceGenerationIds::new_with_trust( + InferenceCacheHints { + prompt_cache_key: Some("same-key".into()), + ..Default::default() + }, + Some("same-agent"), + true, + None, + ) + .with_request_class(class) + }; + let local = make(InferenceRequestClass::default()); + let unclassed = InferenceGenerationIds::new_with_trust( + InferenceCacheHints { + prompt_cache_key: Some("same-key".into()), + ..Default::default() + }, + Some("same-agent"), + true, + None, + ); + assert_eq!(local.session_id, unclassed.session_id); + assert_eq!(local.cache.namespace(), unclassed.cache.namespace()); + + let classes = InferenceRequestTier::ALL.into_iter().flat_map(|tier| { + [false, true].map(|private| make(InferenceRequestClass::new(tier, private))) + }); + let ids = classes.collect::>(); + let sessions = ids + .iter() + .map(|ids| ids.session_id) + .collect::>(); + let namespaces = ids + .iter() + .map(|ids| ids.cache.namespace()) + .collect::>(); + assert_eq!(sessions.len(), ids.len()); + assert_eq!(namespaces.len(), ids.len()); + let mesh = make(InferenceRequestClass::new( + InferenceRequestTier::Mesh, + false, + )); + assert_eq!(mesh.request_tier(), InferenceRequestTier::Mesh); + assert_eq!( + mesh.cache.namespace().as_deref(), + Some("tier:mesh:openai:prompt_cache_key:same-key") + ); + } + #[test] fn trusted_agent_session_reuses_native_session_but_not_request_id() { let first = InferenceGenerationIds::new_with_trust( @@ -271,6 +395,8 @@ pub(in crate::frontend) struct InferenceCacheHints { pub(in crate::frontend) prompt_cache_key: Option, pub(in crate::frontend) prompt_cache_retention: Option, execution_scope: Option, + chat_template_digest: Option<[u8; 32]>, + request_class: InferenceRequestClass, } impl InferenceCacheHints { @@ -287,7 +413,7 @@ impl InferenceCacheHints { .prompt_cache_retention .map(prompt_cache_retention_label) .map(ToString::to_string), - execution_scope: None, + ..Self::default() } } @@ -304,24 +430,33 @@ impl InferenceCacheHints { .prompt_cache_retention .map(prompt_cache_retention_label) .map(ToString::to_string), - execution_scope: None, + ..Self::default() } } - /// Derive a cache namespace from the trusted scope and optional client cache key. + /// Derive a cache namespace from the renderer, trusted scope and client cache key. /// A scoped request always has a namespace, even when the client supplies no key. pub(in crate::frontend) fn namespace(&self) -> Option { let namespace = self .prompt_cache_key .as_ref() .map(|key| format!("openai:prompt_cache_key:{key}")); - match self.execution_scope { + let namespace = match self.execution_scope { Some(scope) => Some(format!( "execution:{scope}:{}", namespace.unwrap_or_default() )), None => namespace, - } + }; + let namespace = match self.chat_template_digest { + Some(digest) => Some(format!( + "chat-template-v1:{}:{}", + URL_SAFE_NO_PAD.encode(digest), + namespace.unwrap_or_default() + )), + None => namespace, + }; + self.request_class.cache_namespace(namespace) } } diff --git a/crates/skippy-serving/src/frontend/generation/concurrency.rs b/crates/skippy-serving/src/frontend/generation/concurrency.rs index 57b1ff02..4d1d8d2f 100644 --- a/crates/skippy-serving/src/frontend/generation/concurrency.rs +++ b/crates/skippy-serving/src/frontend/generation/concurrency.rs @@ -131,6 +131,8 @@ struct AdaptiveGenerationConcurrencyState { #[derive(Default)] struct PermitRetirementState { pending: usize, + active: usize, + load_epoch: u64, } #[derive(Default)] @@ -155,6 +157,8 @@ impl Drop for GenerationConcurrencyPermit { .state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); + retirement.active -= 1; + retirement.load_epoch = retirement.load_epoch.wrapping_add(1); if retirement.pending > 0 { retirement.pending -= 1; permit.forget(); @@ -269,6 +273,15 @@ impl GenerationConcurrencyController { &self, permit: OwnedSemaphorePermit, ) -> GenerationConcurrencyPermit { + { + let mut state = self + .retirement + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.active += 1; + state.load_epoch = state.load_epoch.wrapping_add(1); + } GenerationConcurrencyPermit { permit: Some(permit), retirement: Arc::clone(&self.retirement), @@ -276,6 +289,17 @@ impl GenerationConcurrencyController { } } + /// Active generation permits and a revision that changes on every arrival + /// and departure, including a departure followed by a replacement lane. + pub(in crate::frontend) fn generation_load(&self) -> (usize, u64) { + let state = self + .retirement + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (state.active, state.load_epoch) + } + #[cfg(test)] pub(in crate::frontend) fn available_permits(&self) -> usize { self.semaphore.available_permits() @@ -706,6 +730,23 @@ mod tests { } } + #[test] + fn generation_load_counts_owned_lanes_and_detects_replacements() { + let controller = GenerationConcurrencyController::fixed(2); + assert_eq!(controller.generation_load(), (0, 0)); + let first = controller.try_acquire_owned().unwrap(); + let second = controller.try_acquire_owned().unwrap(); + let full = controller.generation_load(); + assert_eq!(full.0, 2); + drop(second); + assert_eq!(controller.generation_load().0, 1); + let replacement = controller.try_acquire_owned().unwrap(); + assert_eq!(controller.generation_load().0, 2); + assert_ne!(controller.generation_load().1, full.1); + drop((first, replacement)); + assert_eq!(controller.generation_load().0, 0); + } + #[test] fn fixed_controller_exposes_the_hard_ceiling() { let controller = GenerationConcurrencyController::fixed(4); diff --git a/crates/skippy-serving/src/frontend/generation/execution.rs b/crates/skippy-serving/src/frontend/generation/execution.rs index bd08c33c..1f07d7a3 100644 --- a/crates/skippy-serving/src/frontend/generation/execution.rs +++ b/crates/skippy-serving/src/frontend/generation/execution.rs @@ -20,6 +20,7 @@ pub(in crate::frontend) fn generation_ids( frontend_request_id, ) .with_execution_scope(context.execution_scope()) + .with_request_class(context.request_class()) } /// Run blocking inference while owning its permit and full request context. diff --git a/crates/skippy-serving/src/frontend/generation/parsing.rs b/crates/skippy-serving/src/frontend/generation/parsing.rs index b45fd053..a2fd60e8 100644 --- a/crates/skippy-serving/src/frontend/generation/parsing.rs +++ b/crates/skippy-serving/src/frontend/generation/parsing.rs @@ -133,6 +133,9 @@ pub(in crate::frontend) struct PreparedGenerationPrompt { pub(in crate::frontend) text: String, pub(in crate::frontend) media: Vec, pub(in crate::frontend) chat_parse_metadata: Option, + /// Identity of an accepted renderer override. The default embedded + /// template derives its identity from the model artifact itself. + pub(in crate::frontend) cache_template_digest: Option<[u8; 32]>, /// Rendered message-history text before an assistant-generation suffix. /// /// This is only a candidate. The generation path retokenizes it with the @@ -152,6 +155,7 @@ impl PreparedGenerationPrompt { text, media: Vec::new(), chat_parse_metadata: None, + cache_template_digest: None, recurrent_cache_prefix_text: None, recurrent_system_prefix_text: None, shape: crate::generation_stats::RequestShape::default(), diff --git a/crates/skippy-serving/src/frontend/generation/queue.rs b/crates/skippy-serving/src/frontend/generation/queue.rs index 22886d56..6d8b5029 100644 --- a/crates/skippy-serving/src/frontend/generation/queue.rs +++ b/crates/skippy-serving/src/frontend/generation/queue.rs @@ -17,11 +17,14 @@ use serde_json::json; use skippy_inference_api::CancellationToken; use skippy_inference_api::InferenceError; use skippy_inference_api::InferenceErrorKind; +use skippy_inference_api::InferenceRequestTier; use skippy_inference_api::InferenceResult; use skippy_protocol::StageConfig; -use skippy_scheduler::{CacheAffinity, CacheAwareCandidate, order_cache_aware_candidates}; +use skippy_scheduler::{ + CacheAffinity, CacheAwareCandidate, PriorityPassovers, order_cache_aware_candidates, +}; use std::collections::BTreeMap; -use std::collections::VecDeque; +use std::collections::BTreeSet; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicUsize; @@ -32,8 +35,6 @@ use tokio::sync::Notify; use tokio::sync::OwnedSemaphorePermit; use tokio::sync::Semaphore; -const SERVICE_RATE_EWMA_ALPHA: f64 = 0.25; -const SERVICE_RATE_WINDOW: usize = 64; const ADMISSION_CACHE_AGING_COST_PER_TURN: u64 = 4_096; /// How many admissions the oldest waiter may be bypassed before the queue stops @@ -49,7 +50,8 @@ const ADMISSION_CACHE_AGING_COST_PER_TURN: u64 = 4_096; /// request fits an empty pool (`claim_or_enqueue` rejects impossible requests up /// front), so draining always makes progress. The bound trades a little /// throughput and cache locality for a hard ceiling on bypasses before drain -/// reservation begins. +/// reservation begins. Higher tiers are not held: the bound caps bypasses by +/// the waiter's own and lower tiers. pub(in crate::frontend) const ADMISSION_STARVATION_BOUND_TURNS: u64 = 32; pub(in crate::frontend) type GenerationCacheAffinityRefresh = @@ -59,6 +61,7 @@ pub(in crate::frontend) type GenerationCacheAffinityRefresh = pub(in crate::frontend) struct GenerationAdmissionScheduling { prompt_tokens: Arc<[i32]>, refresh_affinity: GenerationCacheAffinityRefresh, + tier: InferenceRequestTier, } impl GenerationAdmissionScheduling { @@ -69,8 +72,20 @@ impl GenerationAdmissionScheduling { Self { prompt_tokens, refresh_affinity, + tier: InferenceRequestTier::default(), } } + + /// Rank this work at `tier`: higher tiers are admitted first, and lower + /// tiers never take a higher tier's room in the waiting queue. + pub(in crate::frontend) fn with_tier(mut self, tier: InferenceRequestTier) -> Self { + self.tier = tier; + self + } + + pub(in crate::frontend) fn tier(&self) -> InferenceRequestTier { + self.tier + } } impl Default for GenerationAdmissionScheduling { @@ -78,6 +93,7 @@ impl Default for GenerationAdmissionScheduling { Self { prompt_tokens: Arc::from([]), refresh_affinity: Arc::new(CacheAffinity::default), + tier: InferenceRequestTier::default(), } } } @@ -88,16 +104,155 @@ struct GenerationAdmissionWaiter { token_budget_request: GenerationTokenBudgetRequest, enqueued_turn: u64, order: u64, + /// [`PriorityPassovers::mark`] when the waiter entered the room. + passover_mark: u64, +} + +/// A waiter as one election sees it. +struct WaiterSnapshot { + id: u64, + waiter: GenerationAdmissionWaiter, + /// How many higher-tier waiters were admitted while it waited. + passed_over: u64, +} + +/// What the anti-starvation head-of-line reservation asks of the next +/// election. +enum SeniorHold { + /// Hand the lane to this senior waiter, which fits now, so a higher + /// cache-value newcomer cannot re-occupy the drained pool ahead of it. + Select(u64), + /// A senior waiter of this tier does not fit yet: only higher tiers may + /// pass it, so the pool drains for it rather than letting a steady + /// stream of smaller requests of its own or a lower tier keep passing it. + HoldAtOrBelow(InferenceRequestTier), + None, +} + +/// Each tier's oldest waiter (smallest enqueued turn, then smallest order) +/// is the one at risk in that tier. From the highest tier down, the first +/// that has been bypassed `ADMISSION_STARVATION_BOUND_TURNS` times gets the +/// reservation. A higher tier is never held for a lower one: a senior is +/// handed the lane only when no higher-tier waiter fits, and a lower tier's +/// old waiter cannot remove a higher tier's protection. Across tiers, aging +/// protects only a lower-tier waiter that fits: one that does not fit waits +/// until higher-tier load leaves it room, or until its deadline. +fn senior_hold( + waiters: &[WaiterSnapshot], + turn: u64, + token_budget: &GenerationTokenBudget, +) -> InferenceResult { + let mut seniors = BTreeMap::::new(); + for snapshot in waiters { + let senior = seniors + .entry(snapshot.waiter.scheduling.tier) + .or_insert(snapshot); + let age = + |snapshot: &WaiterSnapshot| (snapshot.waiter.enqueued_turn, snapshot.waiter.order); + if age(snapshot) < age(senior) { + *senior = snapshot; + } + } + let mut higher_tier_fits = false; + for (tier, senior) in seniors.into_iter().rev() { + if turn.saturating_sub(senior.waiter.enqueued_turn) >= ADMISSION_STARVATION_BOUND_TURNS { + if !token_budget.can_reserve_now(senior.waiter.token_budget_request)? { + return Ok(SeniorHold::HoldAtOrBelow(tier)); + } + if !higher_tier_fits { + return Ok(SeniorHold::Select(senior.id)); + } + } + higher_tier_fits = + higher_tier_fits || tier_has_fitting_waiter(waiters, tier, token_budget)?; + } + Ok(SeniorHold::None) +} + +fn tier_has_fitting_waiter( + waiters: &[WaiterSnapshot], + tier: InferenceRequestTier, + token_budget: &GenerationTokenBudget, +) -> InferenceResult { + for snapshot in waiters { + if snapshot.waiter.scheduling.tier == tier + && token_budget.can_reserve_now(snapshot.waiter.token_budget_request)? + { + return Ok(true); + } + } + Ok(false) } #[derive(Default)] struct GenerationAdmissionQueueState { turn: u64, + /// Admissions by tier priority, which age the waiters they pass over. + passovers: PriorityPassovers, next_id: u64, + /// Advances whenever the waiting set changes, so an election run on an + /// older snapshot is not published. + revision: u64, selected_id: Option, + /// The published winner's tier and the waiters that fit when it won. + selection_basis: Option, waiters: BTreeMap, } +struct SelectionBasis { + tier: InferenceRequestTier, + fit: BTreeSet, +} + +/// One election's view of the waiting room. +struct ElectionSnapshot { + revision: u64, + turn: u64, + waiters: Vec, +} + +impl GenerationAdmissionQueueState { + /// A published winner is stale once a higher-tier waiter that did not + /// fit at its election fits now: a release can make room for it. + fn selection_is_stale(&self, token_budget: &GenerationTokenBudget) -> InferenceResult { + let Some(basis) = self.selection_basis.as_ref() else { + return Ok(false); + }; + for (id, waiter) in &self.waiters { + if waiter.scheduling.tier > basis.tier + && !basis.fit.contains(id) + && token_budget.can_reserve_now(waiter.token_budget_request)? + { + return Ok(true); + } + } + Ok(false) + } + + fn clear_selection(&mut self) { + self.selected_id = None; + self.selection_basis = None; + } + + fn snapshot(&self) -> ElectionSnapshot { + ElectionSnapshot { + revision: self.revision, + turn: self.turn, + waiters: self + .waiters + .iter() + .map(|(id, waiter)| WaiterSnapshot { + id: *id, + waiter: waiter.clone(), + passed_over: self + .passovers + .passed_over(waiter.scheduling.tier.priority(), waiter.passover_mark), + }) + .collect(), + } + } +} + /// Scheduler-owned waiting room in front of the finite native lane pool. /// /// Tokenized prompts enter this queue before acquiring a generation lane, so @@ -143,7 +298,9 @@ impl GenerationAdmissionQueue { { return Ok(GenerationAdmissionClaim::Acquired(resources)); } - let reservation = reserve_generation_queue(generation_queue_depth, generation_queue_limit) + let reservation = tier_has_queue_room(&state, scheduling.tier, generation_queue_limit) + .then(|| reserve_generation_queue(generation_queue_depth, usize::MAX)) + .flatten() .ok_or_else(generation_queue_full_error)?; let id = state.next_id; state.next_id = state.next_id.saturating_add(1); @@ -151,7 +308,9 @@ impl GenerationAdmissionQueue { // Claiming a lane or entering the waiting room is one queue-locked operation. A lane that // becomes free after the failed fast claim cannot be taken by a newer arrival before this // waiter is visible. - state.selected_id = None; + state.clear_selection(); + state.revision = state.revision.wrapping_add(1); + let passover_mark = state.passovers.mark(scheduling.tier.priority()); state.waiters.insert( id, GenerationAdmissionWaiter { @@ -159,6 +318,7 @@ impl GenerationAdmissionQueue { token_budget_request, enqueued_turn: turn, order: id, + passover_mark, }, ); drop(state); @@ -174,6 +334,16 @@ impl GenerationAdmissionQueue { )) } + /// The number of waiters and the published winner. + #[cfg(test)] + pub(in crate::frontend) fn election_for_test(&self) -> (usize, Option) { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (state.waiters.len(), state.selected_id) + } + pub(in crate::frontend) fn notify_lane_available(&self) { self.changed.notify_waiters(); } @@ -189,92 +359,40 @@ impl GenerationAdmissionQueue { .election .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - // Refreshing affinity consults the prefix cache and can be more - // expensive than queue bookkeeping. Snapshot under the queue lock, - // then release it before crossing that subsystem boundary. - let (turn, waiters) = { - let state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(selected_id) = state.selected_id { - return Ok(Some(selected_id)); - } - ( - state.turn, - state - .waiters - .iter() - .map(|(id, waiter)| (*id, waiter.clone())) - .collect::>(), - ) - }; - // Anti-starvation head-of-line reservation. The oldest waiter (smallest - // enqueued turn, then smallest order) is the one at risk: once it has - // been bypassed ADMISSION_STARVATION_BOUND_TURNS times, reserve the pool - // for it instead of letting a steady stream of smaller, currently-fitting - // requests keep passing it. If it now fits, hand it the lane directly so a - // higher cache-value newcomer cannot re-occupy the drained pool ahead of - // it; otherwise select nobody so active reservations keep draining. - if let Some((senior_id, senior)) = waiters - .iter() - .min_by_key(|(_, waiter)| (waiter.enqueued_turn, waiter.order)) - && turn.saturating_sub(senior.enqueued_turn) >= ADMISSION_STARVATION_BOUND_TURNS - { - let senior_id = *senior_id; - if !token_budget.can_reserve_now(senior.token_budget_request)? { - return Ok(None); - } + loop { + // Refreshing affinity consults the prefix cache and can be more + // expensive than queue bookkeeping. Snapshot under the queue + // lock, then release it before crossing that subsystem boundary. + let snapshot = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(selected_id) = state.selected_id { + if !state.selection_is_stale(token_budget)? { + return Ok(Some(selected_id)); + } + state.clear_selection(); + } + state.snapshot() + }; + let fit = fitting_waiters(&snapshot.waiters, token_budget)?; + let winner = elect(&snapshot, &fit, token_budget)?; let mut state = self .state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.selected_id.is_none() && state.waiters.contains_key(&senior_id) { - state.selected_id = Some(senior_id); + // A waiter that arrived or left during the election was not + // ranked: elect again from the current set. + if state.revision != snapshot.revision { + continue; } - return Ok(state.selected_id); - } - let mut eligible_waiters = Vec::with_capacity(waiters.len()); - for (id, waiter) in waiters { - if token_budget.can_reserve_now(waiter.token_budget_request)? { - eligible_waiters.push((id, waiter)); + if let Some((id, tier)) = winner { + state.selected_id = Some(id); + state.selection_basis = Some(SelectionBasis { tier, fit }); } + return Ok(state.selected_id); } - let affinities = eligible_waiters - .iter() - .map(|(_, waiter)| (waiter.scheduling.refresh_affinity)()) - .collect::>(); - let selected_id = order_cache_aware_candidates( - eligible_waiters - .iter() - .map(|(_, waiter)| waiter) - .zip(affinities.iter()) - .enumerate() - .map(|(index, (waiter, affinity))| CacheAwareCandidate { - index, - priority: 0, - affinity, - prompt_tokens: &waiter.scheduling.prompt_tokens, - enqueued_turn: waiter.enqueued_turn, - order: waiter.order, - }), - turn, - ADMISSION_CACHE_AGING_COST_PER_TURN, - true, - ) - .first() - .and_then(|index| eligible_waiters.get(*index).map(|(id, _)| id)) - .copied(); - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.selected_id.is_none() - && selected_id.is_some_and(|id| state.waiters.contains_key(&id)) - { - state.selected_id = selected_id; - } - Ok(state.selected_id) } fn remove(&self, id: u64) -> bool { @@ -284,8 +402,11 @@ impl GenerationAdmissionQueue { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let removed = state.waiters.remove(&id).is_some(); + if removed { + state.revision = state.revision.wrapping_add(1); + } if state.selected_id == Some(id) { - state.selected_id = None; + state.clear_selection(); } removed }; @@ -295,20 +416,125 @@ impl GenerationAdmissionQueue { removed } - fn complete_selection(&self, id: u64) { + /// Take a lane and its tokens for waiter `id` if it is the current + /// winner. Confirming the election and claiming happen under one lock, + /// so a waiter that arrives after the election is not passed by it. + fn claim_if_selected( + &self, + id: u64, + generation_limit: Arc, + token_budget: &Arc, + token_budget_request: GenerationTokenBudgetRequest, + ) -> InferenceResult> { + if self.selected_waiter(token_budget)? != Some(id) { + return Ok(None); + } let mut state = self .state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if state.waiters.remove(&id).is_some() { + if state.selected_id != Some(id) { + return Ok(None); + } + if state.selection_is_stale(token_budget)? { + // Elect again, this waiter included. + state.clear_selection(); + drop(state); + self.changed.notify_waiters(); + return Ok(None); + } + let Some(resources) = + try_acquire_generation_resources(generation_limit, token_budget, token_budget_request)? + else { + return Ok(None); + }; + Self::complete_selection(&mut state, id); + drop(state); + self.changed.notify_waiters(); + Ok(Some(resources)) + } + + fn complete_selection(state: &mut GenerationAdmissionQueueState, id: u64) { + if let Some(waiter) = state.waiters.remove(&id) { + state.revision = state.revision.wrapping_add(1); state.turn = state.turn.saturating_add(1); + state + .passovers + .record_selection(waiter.scheduling.tier.priority()); } if state.selected_id == Some(id) { - state.selected_id = None; + state.clear_selection(); } } } +/// The waiters whose token request fits the budget now. +fn fitting_waiters( + waiters: &[WaiterSnapshot], + token_budget: &GenerationTokenBudget, +) -> InferenceResult> { + let mut fit = BTreeSet::new(); + for snapshot in waiters { + if token_budget.can_reserve_now(snapshot.waiter.token_budget_request)? { + fit.insert(snapshot.id); + } + } + Ok(fit) +} + +/// The waiter the next free lane goes to, with its tier. +fn elect( + snapshot: &ElectionSnapshot, + fit: &BTreeSet, + token_budget: &GenerationTokenBudget, +) -> InferenceResult> { + let tier_of = |id: u64| { + snapshot + .waiters + .iter() + .find(|candidate| candidate.id == id) + .map(|candidate| (id, candidate.waiter.scheduling.tier)) + }; + let held_for = match senior_hold(&snapshot.waiters, snapshot.turn, token_budget)? { + SeniorHold::Select(senior_id) => return Ok(tier_of(senior_id)), + SeniorHold::HoldAtOrBelow(tier) => Some(tier), + SeniorHold::None => None, + }; + let eligible_waiters = snapshot + .waiters + .iter() + .filter(|candidate| { + fit.contains(&candidate.id) + && held_for.is_none_or(|tier| candidate.waiter.scheduling.tier > tier) + }) + .collect::>(); + let affinities = eligible_waiters + .iter() + .map(|candidate| (candidate.waiter.scheduling.refresh_affinity)()) + .collect::>(); + let winner = order_cache_aware_candidates( + eligible_waiters + .iter() + .zip(affinities.iter()) + .enumerate() + .map(|(index, (candidate, affinity))| CacheAwareCandidate { + index, + priority: candidate.waiter.scheduling.tier.priority(), + affinity, + prompt_tokens: &candidate.waiter.scheduling.prompt_tokens, + enqueued_turn: candidate.waiter.enqueued_turn, + order: candidate.waiter.order, + passed_over: candidate.passed_over, + }), + snapshot.turn, + ADMISSION_CACHE_AGING_COST_PER_TURN, + true, + ) + .first() + .and_then(|index| eligible_waiters.get(*index).map(|candidate| candidate.id)); + Ok(winner.and_then(tier_of)) +} + pub(in crate::frontend) enum GenerationAdmissionClaim { Acquired(GenerationAdmissionResources), Queued(GenerationAdmissionQueueLease), @@ -348,16 +574,13 @@ impl GenerationAdmissionQueueLease { let token_released = self.token_budget.release_notification().notified(); tokio::pin!(token_released); token_released.as_mut().enable(); - if self.queue.selected_waiter(&self.token_budget)? == Some(self.id) - && let Some(resources) = try_acquire_generation_resources( - generation_limit.clone(), - &self.token_budget, - self.token_budget_request, - )? - { - self.queue.complete_selection(self.id); + if let Some(resources) = self.queue.claim_if_selected( + self.id, + generation_limit.clone(), + &self.token_budget, + self.token_budget_request, + )? { self.reservation.take(); - self.queue.changed.notify_waiters(); return Ok(resources); } if let Some(deadline) = deadline { @@ -413,229 +636,6 @@ impl Drop for GenerationAdmissionQueueLease { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(in crate::frontend) struct GenerationAdmissionWork { - pub(in crate::frontend) prompt_tokens: u64, - pub(in crate::frontend) decode_tokens: u64, -} - -impl GenerationAdmissionWork { - pub(in crate::frontend) fn new(prompt_tokens: usize, decode_tokens: u32) -> Self { - Self { - prompt_tokens: u64::try_from(prompt_tokens).unwrap_or(u64::MAX), - decode_tokens: u64::from(decode_tokens), - } - } -} - -#[derive(Default)] -struct GenerationServiceState { - active: GenerationAdmissionWork, - queued: GenerationAdmissionWork, - prefill_ms_per_token_ewma: Option, - decode_ms_per_token_ewma: Option, - prefill_ms_per_token_samples: VecDeque, - decode_ms_per_token_samples: VecDeque, -} - -pub(in crate::frontend) struct GenerationServiceEstimator { - concurrency: AtomicUsize, - state: Mutex, -} - -impl GenerationServiceEstimator { - pub(in crate::frontend) fn new(concurrency: usize) -> Self { - Self { - concurrency: AtomicUsize::new(concurrency.max(1)), - state: Mutex::new(GenerationServiceState::default()), - } - } - - pub(in crate::frontend) fn predicted_wait_ms(&self) -> Option { - let state = self.state.lock().ok()?; - predicted_wait_ms_for_state(&state, self.concurrency.load(Ordering::Acquire)) - } - - pub(in crate::frontend) fn estimated_prefill_ms(&self, tokens: usize) -> Option { - let state = self.state.lock().ok()?; - state - .prefill_ms_per_token_ewma - .map(|per_token| per_token * tokens as f64) - .filter(|cost| cost.is_finite() && *cost >= 0.0) - } - - pub(in crate::frontend) fn set_concurrency(&self, concurrency: usize) { - self.concurrency - .store(concurrency.max(1), Ordering::Release); - } - - pub(in crate::frontend) fn reserve_queued( - self: &Arc, - work: GenerationAdmissionWork, - ) -> GenerationQueuedWorkReservation { - let Ok(mut state) = self.state.lock() else { - return GenerationQueuedWorkReservation { - estimator: self.clone(), - work, - queued: false, - }; - }; - // 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); - GenerationQueuedWorkReservation { - estimator: self.clone(), - work, - queued: true, - } - } - - pub(in crate::frontend) fn start_active( - self: &Arc, - work: GenerationAdmissionWork, - ) -> GenerationActiveWorkReservation { - if let Ok(mut state) = self.state.lock() { - state.active = add_work(state.active, work); - } - GenerationActiveWorkReservation { - estimator: self.clone(), - work, - } - } - - pub(in crate::frontend) fn observe_completed( - &self, - work: GenerationAdmissionWork, - prompt_ms: f64, - decode_ms: f64, - ) { - let Ok(mut state) = self.state.lock() else { - return; - }; - if work.prompt_tokens > 0 && prompt_ms.is_finite() && prompt_ms > 0.0 { - let sample = prompt_ms / work.prompt_tokens as f64; - state.prefill_ms_per_token_ewma = - Some(update_ewma(state.prefill_ms_per_token_ewma, sample)); - push_sample(&mut state.prefill_ms_per_token_samples, sample); - } - if work.decode_tokens > 0 && decode_ms.is_finite() && decode_ms > 0.0 { - let sample = decode_ms / work.decode_tokens as f64; - state.decode_ms_per_token_ewma = - Some(update_ewma(state.decode_ms_per_token_ewma, sample)); - push_sample(&mut state.decode_ms_per_token_samples, sample); - } - } -} - -fn predicted_wait_ms_for_state(state: &GenerationServiceState, concurrency: usize) -> Option { - let prompt_ms_per_token = conservative_ms_per_token( - state.prefill_ms_per_token_ewma, - &state.prefill_ms_per_token_samples, - ); - let decode_ms_per_token = conservative_ms_per_token( - state.decode_ms_per_token_ewma, - &state.decode_ms_per_token_samples, - ); - if prompt_ms_per_token.is_none() && decode_ms_per_token.is_none() { - return None; - } - let work = add_work(state.active, state.queued); - let prompt_ms = prompt_ms_per_token.unwrap_or(0.0) * work.prompt_tokens as f64; - let decode_ms = decode_ms_per_token.unwrap_or(0.0) * work.decode_tokens as f64; - Some((prompt_ms + decode_ms) / concurrency.max(1) as f64) -} - -pub(in crate::frontend) struct GenerationQueuedWorkReservation { - estimator: Arc, - work: GenerationAdmissionWork, - queued: bool, -} - -impl GenerationQueuedWorkReservation { - pub(in crate::frontend) fn promote(mut self) -> GenerationActiveWorkReservation { - if let Ok(mut state) = self.estimator.state.lock() { - state.queued = subtract_work(state.queued, self.work); - state.active = add_work(state.active, self.work); - } - self.queued = false; - GenerationActiveWorkReservation { - estimator: self.estimator.clone(), - work: self.work, - } - } -} - -impl Drop for GenerationQueuedWorkReservation { - fn drop(&mut self) { - if self.queued - && let Ok(mut state) = self.estimator.state.lock() - { - state.queued = subtract_work(state.queued, self.work); - } - } -} - -pub(in crate::frontend) struct GenerationActiveWorkReservation { - estimator: Arc, - work: GenerationAdmissionWork, -} - -impl Drop for GenerationActiveWorkReservation { - fn drop(&mut self) { - if let Ok(mut state) = self.estimator.state.lock() { - state.active = subtract_work(state.active, self.work); - } - } -} - -fn add_work( - left: GenerationAdmissionWork, - right: GenerationAdmissionWork, -) -> GenerationAdmissionWork { - GenerationAdmissionWork { - prompt_tokens: left.prompt_tokens.saturating_add(right.prompt_tokens), - decode_tokens: left.decode_tokens.saturating_add(right.decode_tokens), - } -} - -fn subtract_work( - left: GenerationAdmissionWork, - right: GenerationAdmissionWork, -) -> GenerationAdmissionWork { - GenerationAdmissionWork { - prompt_tokens: left.prompt_tokens.saturating_sub(right.prompt_tokens), - decode_tokens: left.decode_tokens.saturating_sub(right.decode_tokens), - } -} - -fn update_ewma(previous: Option, sample: f64) -> f64 { - previous.map_or(sample, |previous| { - previous * (1.0 - SERVICE_RATE_EWMA_ALPHA) + sample * SERVICE_RATE_EWMA_ALPHA - }) -} - -fn push_sample(samples: &mut VecDeque, sample: f64) { - if samples.len() == SERVICE_RATE_WINDOW { - samples.pop_front(); - } - samples.push_back(sample); -} - -fn conservative_ms_per_token(ewma: Option, samples: &VecDeque) -> Option { - let mut sorted = samples.iter().copied().collect::>(); - sorted.sort_by(f64::total_cmp); - let p95 = if sorted.is_empty() { - None - } else { - let index = (sorted.len() * 95).div_ceil(100).saturating_sub(1); - sorted.get(index).copied() - }; - match (ewma, p95) { - (Some(ewma), Some(p95)) => Some(ewma.max(p95)), - (Some(value), None) | (None, Some(value)) => Some(value), - (None, None) => None, - } -} #[cfg(test)] use tokio::sync::TryAcquireError; @@ -713,6 +713,23 @@ pub(in crate::frontend) async fn acquire_generation_permit_with_queue( .await } +/// Whether a request at `tier` may join the waiting room. Only waiters at the +/// same or a higher tier count against the limit, so lower-tier traffic cannot +/// fill the room ahead of a higher tier. The room holds at most one limit per +/// tier. +fn tier_has_queue_room( + state: &GenerationAdmissionQueueState, + tier: InferenceRequestTier, + generation_queue_limit: usize, +) -> bool { + state + .waiters + .values() + .filter(|waiter| waiter.scheduling.tier >= tier) + .count() + < generation_queue_limit +} + pub(in crate::frontend) fn reserve_generation_queue( generation_queue_depth: Arc, generation_queue_limit: usize, @@ -811,6 +828,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( @@ -901,52 +928,3 @@ pub(in crate::frontend) fn generation_queue_timeout_error(timeout: Duration) -> ) .with_retry_after_secs(GENERATION_RETRY_AFTER_SECS) } - -#[cfg(test)] -mod service_estimator_tests { - use super::*; - - #[test] - 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)); - 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] - fn queued_and_active_work_are_released_by_raii() { - 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); - assert_eq!(estimator.predicted_wait_ms(), Some(50.0)); - - let active = queued.promote(); - assert_eq!(estimator.predicted_wait_ms(), Some(50.0)); - drop(active); - assert_eq!(estimator.predicted_wait_ms(), Some(0.0)); - } - - #[test] - fn conservative_rate_uses_the_slower_p95_sample() { - let samples = VecDeque::from([1.0, 1.0, 1.0, 10.0]); - assert_eq!(conservative_ms_per_token(Some(1.5), &samples), Some(10.0)); - } - - #[test] - fn prefill_estimate_uses_observed_stage_rate() { - let estimator = GenerationServiceEstimator::new(1); - assert_eq!(estimator.estimated_prefill_ms(128), None); - estimator.observe_completed(GenerationAdmissionWork::new(100, 0), 25.0, 0.0); - assert_eq!(estimator.estimated_prefill_ms(40), Some(10.0)); - } -} diff --git a/crates/skippy-serving/src/frontend/generation/server.rs b/crates/skippy-serving/src/frontend/generation/server.rs index 35b644b3..218ffda8 100644 --- a/crates/skippy-serving/src/frontend/generation/server.rs +++ b/crates/skippy-serving/src/frontend/generation/server.rs @@ -98,6 +98,8 @@ pub struct EmbeddedOpenAiArgs { pub pipeline_decode_groups: Option, pub adaptive_generation_min_concurrency: Option, pub generation_queue_capacity: usize, + /// Percent of the KV token budget only `local`-tier requests may reserve. + pub local_kv_reserve_percent: u8, pub generation_admission_timeout_secs: u64, pub prefill_chunk_size: usize, pub prefill_chunk_policy: String, @@ -434,7 +436,11 @@ fn embedded_openai_backend_with_state_kind( 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, + args.local_kv_reserve_percent, + ), runtime.lane_admission(), ) }; diff --git a/crates/skippy-serving/src/frontend/generation/service_estimate.rs b/crates/skippy-serving/src/frontend/generation/service_estimate.rs new file mode 100644 index 00000000..1449dd44 --- /dev/null +++ b/crates/skippy-serving/src/frontend/generation/service_estimate.rs @@ -0,0 +1,350 @@ +//! How long queued generation work is predicted to wait, from the work +//! admitted and queued and the service rate observed so far. Predictions +//! are advisory: the queue owns capacity and deadlines. + +use skippy_inference_api::InferenceRequestTier; +use std::collections::BTreeMap; +use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +const SERVICE_RATE_EWMA_ALPHA: f64 = 0.25; +const SERVICE_RATE_WINDOW: usize = 64; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::frontend) struct GenerationAdmissionWork { + pub(in crate::frontend) prompt_tokens: u64, + pub(in crate::frontend) decode_tokens: u64, +} + +impl GenerationAdmissionWork { + pub(in crate::frontend) fn new(prompt_tokens: usize, decode_tokens: u32) -> Self { + Self { + prompt_tokens: u64::try_from(prompt_tokens).unwrap_or(u64::MAX), + decode_tokens: u64::from(decode_tokens), + } + } +} + +#[derive(Default)] +struct GenerationServiceState { + active: GenerationAdmissionWork, + /// Queued work by request tier: a request waits behind active work and + /// queued work at its own tier or higher, which is admitted first. + queued: BTreeMap, + prefill_ms_per_token_ewma: Option, + decode_ms_per_token_ewma: Option, + prefill_ms_per_token_samples: VecDeque, + decode_ms_per_token_samples: VecDeque, +} + +pub(in crate::frontend) struct GenerationServiceEstimator { + concurrency: AtomicUsize, + state: Mutex, +} + +impl GenerationServiceEstimator { + pub(in crate::frontend) fn new(concurrency: usize) -> Self { + Self { + concurrency: AtomicUsize::new(concurrency.max(1)), + state: Mutex::new(GenerationServiceState::default()), + } + } + + /// The predicted wait for a request at `tier`. + pub(in crate::frontend) fn predicted_wait_ms(&self, tier: InferenceRequestTier) -> Option { + let state = self.state.lock().ok()?; + predicted_wait_ms_for_state(&state, self.concurrency.load(Ordering::Acquire), tier) + } + + pub(in crate::frontend) fn estimated_prefill_ms(&self, tokens: usize) -> Option { + let state = self.state.lock().ok()?; + state + .prefill_ms_per_token_ewma + .map(|per_token| per_token * tokens as f64) + .filter(|cost| cost.is_finite() && *cost >= 0.0) + } + + pub(in crate::frontend) fn set_concurrency(&self, concurrency: usize) { + self.concurrency + .store(concurrency.max(1), Ordering::Release); + } + + /// Account `work` as queued for a request at `tier`. + pub(in crate::frontend) fn reserve_queued( + self: &Arc, + work: GenerationAdmissionWork, + tier: InferenceRequestTier, + ) -> GenerationQueuedWorkReservation { + let Ok(mut state) = self.state.lock() else { + return GenerationQueuedWorkReservation { + estimator: self.clone(), + work, + tier, + queued: false, + }; + }; + // Predictions include interference and unfinished requests' original + // work, so they are advisory. The queue owns capacity and deadlines. + let queued = state.queued.entry(tier).or_default(); + *queued = add_work(*queued, work); + GenerationQueuedWorkReservation { + estimator: self.clone(), + work, + tier, + queued: true, + } + } + + pub(in crate::frontend) fn start_active( + self: &Arc, + work: GenerationAdmissionWork, + ) -> GenerationActiveWorkReservation { + if let Ok(mut state) = self.state.lock() { + state.active = add_work(state.active, work); + } + GenerationActiveWorkReservation { + estimator: self.clone(), + work, + } + } + + pub(in crate::frontend) fn observe_completed( + &self, + work: GenerationAdmissionWork, + prompt_ms: f64, + decode_ms: f64, + ) { + let Ok(mut state) = self.state.lock() else { + return; + }; + if work.prompt_tokens > 0 && prompt_ms.is_finite() && prompt_ms > 0.0 { + let sample = prompt_ms / work.prompt_tokens as f64; + state.prefill_ms_per_token_ewma = + Some(update_ewma(state.prefill_ms_per_token_ewma, sample)); + push_sample(&mut state.prefill_ms_per_token_samples, sample); + } + if work.decode_tokens > 0 && decode_ms.is_finite() && decode_ms > 0.0 { + let sample = decode_ms / work.decode_tokens as f64; + state.decode_ms_per_token_ewma = + Some(update_ewma(state.decode_ms_per_token_ewma, sample)); + push_sample(&mut state.decode_ms_per_token_samples, sample); + } + } +} + +fn predicted_wait_ms_for_state( + state: &GenerationServiceState, + concurrency: usize, + tier: InferenceRequestTier, +) -> Option { + let prompt_ms_per_token = conservative_ms_per_token( + state.prefill_ms_per_token_ewma, + &state.prefill_ms_per_token_samples, + ); + let decode_ms_per_token = conservative_ms_per_token( + state.decode_ms_per_token_ewma, + &state.decode_ms_per_token_samples, + ); + if prompt_ms_per_token.is_none() && decode_ms_per_token.is_none() { + return None; + } + let work = state + .queued + .range(tier..) + .fold(state.active, |work, (_, queued)| add_work(work, *queued)); + let prompt_ms = prompt_ms_per_token.unwrap_or(0.0) * work.prompt_tokens as f64; + let decode_ms = decode_ms_per_token.unwrap_or(0.0) * work.decode_tokens as f64; + Some((prompt_ms + decode_ms) / concurrency.max(1) as f64) +} + +pub(in crate::frontend) struct GenerationQueuedWorkReservation { + estimator: Arc, + work: GenerationAdmissionWork, + tier: InferenceRequestTier, + queued: bool, +} + +impl GenerationQueuedWorkReservation { + pub(in crate::frontend) fn promote(mut self) -> GenerationActiveWorkReservation { + if let Ok(mut state) = self.estimator.state.lock() { + unqueue(&mut state, self.tier, self.work); + state.active = add_work(state.active, self.work); + } + self.queued = false; + GenerationActiveWorkReservation { + estimator: self.estimator.clone(), + work: self.work, + } + } +} + +impl Drop for GenerationQueuedWorkReservation { + fn drop(&mut self) { + if self.queued + && let Ok(mut state) = self.estimator.state.lock() + { + unqueue(&mut state, self.tier, self.work); + } + } +} + +pub(in crate::frontend) struct GenerationActiveWorkReservation { + estimator: Arc, + work: GenerationAdmissionWork, +} + +impl Drop for GenerationActiveWorkReservation { + fn drop(&mut self) { + if let Ok(mut state) = self.estimator.state.lock() { + state.active = subtract_work(state.active, self.work); + } + } +} + +fn unqueue( + state: &mut GenerationServiceState, + tier: InferenceRequestTier, + work: GenerationAdmissionWork, +) { + if let Some(queued) = state.queued.get_mut(&tier) { + *queued = subtract_work(*queued, work); + if *queued == GenerationAdmissionWork::default() { + state.queued.remove(&tier); + } + } +} + +fn add_work( + left: GenerationAdmissionWork, + right: GenerationAdmissionWork, +) -> GenerationAdmissionWork { + GenerationAdmissionWork { + prompt_tokens: left.prompt_tokens.saturating_add(right.prompt_tokens), + decode_tokens: left.decode_tokens.saturating_add(right.decode_tokens), + } +} + +fn subtract_work( + left: GenerationAdmissionWork, + right: GenerationAdmissionWork, +) -> GenerationAdmissionWork { + GenerationAdmissionWork { + prompt_tokens: left.prompt_tokens.saturating_sub(right.prompt_tokens), + decode_tokens: left.decode_tokens.saturating_sub(right.decode_tokens), + } +} + +fn update_ewma(previous: Option, sample: f64) -> f64 { + previous.map_or(sample, |previous| { + previous * (1.0 - SERVICE_RATE_EWMA_ALPHA) + sample * SERVICE_RATE_EWMA_ALPHA + }) +} + +fn push_sample(samples: &mut VecDeque, sample: f64) { + if samples.len() == SERVICE_RATE_WINDOW { + samples.pop_front(); + } + samples.push_back(sample); +} + +fn conservative_ms_per_token(ewma: Option, samples: &VecDeque) -> Option { + let mut sorted = samples.iter().copied().collect::>(); + sorted.sort_by(f64::total_cmp); + let p95 = if sorted.is_empty() { + None + } else { + let index = (sorted.len() * 95).div_ceil(100).saturating_sub(1); + sorted.get(index).copied() + }; + match (ewma, p95) { + (Some(ewma), Some(p95)) => Some(ewma.max(p95)), + (Some(value), None) | (None, Some(value)) => Some(value), + (None, None) => None, + } +} + +#[cfg(test)] +mod service_estimator_tests { + use super::*; + + #[test] + 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); + let local = InferenceRequestTier::Local; + + assert_eq!(estimator.predicted_wait_ms(local), Some(200.0)); + let queued = estimator.reserve_queued(work, local); + assert_eq!(estimator.predicted_wait_ms(local), Some(400.0)); + drop(queued); + assert_eq!(estimator.predicted_wait_ms(local), Some(200.0)); + drop(active); + assert_eq!(estimator.predicted_wait_ms(local), Some(0.0)); + } + + #[test] + fn queued_and_active_work_are_released_by_raii() { + 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, InferenceRequestTier::Local); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(50.0) + ); + + let active = queued.promote(); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(50.0) + ); + drop(active); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(0.0) + ); + } + + /// Queued mesh work is admitted after a local request, so it does not + /// count toward the local request's predicted wait. + #[test] + fn a_request_waits_only_behind_work_at_its_tier_or_higher() { + let estimator = Arc::new(GenerationServiceEstimator::new(1)); + let work = GenerationAdmissionWork::new(100, 100); + estimator.observe_completed(work, 100.0, 100.0); + let _mesh = estimator.reserve_queued(work, InferenceRequestTier::Mesh); + let _trusted = estimator.reserve_queued(work, InferenceRequestTier::Trusted); + + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Local), + Some(0.0) + ); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Trusted), + Some(200.0) + ); + assert_eq!( + estimator.predicted_wait_ms(InferenceRequestTier::Mesh), + Some(400.0) + ); + } + + #[test] + fn conservative_rate_uses_the_slower_p95_sample() { + let samples = VecDeque::from([1.0, 1.0, 1.0, 10.0]); + assert_eq!(conservative_ms_per_token(Some(1.5), &samples), Some(10.0)); + } + + #[test] + fn prefill_estimate_uses_observed_stage_rate() { + let estimator = GenerationServiceEstimator::new(1); + assert_eq!(estimator.estimated_prefill_ms(128), None); + estimator.observe_completed(GenerationAdmissionWork::new(100, 0), 25.0, 0.0); + assert_eq!(estimator.estimated_prefill_ms(40), Some(10.0)); + } +} diff --git a/crates/skippy-serving/src/frontend/generation/streaming.rs b/crates/skippy-serving/src/frontend/generation/streaming.rs index bcd2df8a..4e4ba09c 100644 --- a/crates/skippy-serving/src/frontend/generation/streaming.rs +++ b/crates/skippy-serving/src/frontend/generation/streaming.rs @@ -586,6 +586,8 @@ where .detokenize_bytes(&[token]) .map_err(openai_backend_error)?; Ok(GeneratedLogprobCandidate { + #[cfg(test)] + token_id: token, text: String::from_utf8_lossy(&bytes).into_owned(), bytes, logprob: logprob.is_finite().then_some(logprob), diff --git a/crates/skippy-serving/src/frontend/generation/types.rs b/crates/skippy-serving/src/frontend/generation/types.rs index bb35b31c..e8cee85c 100644 --- a/crates/skippy-serving/src/frontend/generation/types.rs +++ b/crates/skippy-serving/src/frontend/generation/types.rs @@ -612,6 +612,8 @@ pub(in crate::frontend) struct GeneratedTokenLogprob { #[derive(Debug, Clone, PartialEq)] pub(in crate::frontend) struct GeneratedLogprobCandidate { + #[cfg(test)] + pub(in crate::frontend) token_id: i32, pub(in crate::frontend) text: String, pub(in crate::frontend) bytes: Vec, /// `None` when the runtime could not read the logits row. diff --git a/crates/skippy-serving/src/frontend/generation_flow.rs b/crates/skippy-serving/src/frontend/generation_flow.rs index f72183c6..bdf66c50 100644 --- a/crates/skippy-serving/src/frontend/generation_flow.rs +++ b/crates/skippy-serving/src/frontend/generation_flow.rs @@ -30,6 +30,7 @@ use crate::frontend::wire_messages::ReusableDecodeMessage; use crate::frontend::wire_messages::ReusableDecodeMessageArgs; use crate::frontend::wire_messages::generation_config_message; use crate::frontend::wire_messages::multimodal_prefill_message; +use crate::frontend::wire_messages::stop_message; use crate::kv_integration::proactive_eviction_attrs; use crate::runtime_state::panic_recovery::lock_runtime; use anyhow::anyhow; @@ -37,7 +38,6 @@ use serde_json::json; use skippy_inference_api::InferenceError; use skippy_inference_api::InferenceResult; use skippy_inference_api::generation::GenerationRequest; -use skippy_protocol::binary::StageWireMessage; use skippy_protocol::binary::WireReplyKind; use skippy_protocol::binary::recv_reply; use skippy_protocol::binary::write_stage_message; @@ -856,6 +856,7 @@ impl StageOpenAiBackend { positions: chunk.positions.clone(), sampling: is_final_chunk.then_some(wire_sampling.clone()).flatten(), final_chunk: is_final_chunk, + request_class: request.ids.request_class(), })?; let forwarded = forwarded_stage_message_timed( &request.config, @@ -951,6 +952,7 @@ impl StageOpenAiBackend { sampling: wire_sampling.clone(), sideband_capacity: 1, native_mtp_draft_tokens: 0, + request_class: request.ids.request_class(), })?; while decoded_tokens < max_tokens as usize { @@ -1167,7 +1169,7 @@ impl StageOpenAiBackend { let stop_result = write_stage_message( &mut lane.stream, - &StageWireMessage::stop_with_identity(request_id, session_id), + &stop_message(request_id, session_id, request.ids.request_class()), ) .and_then(|_| recv_reply(&mut lane.stream).map(|reply| reply.kind)) .and_then(|kind| { diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler.rs b/crates/skippy-serving/src/frontend/iteration_scheduler.rs index 090c76c9..b5a9a0f0 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler.rs @@ -7,6 +7,10 @@ mod direct_batch; mod direct_execution; mod direct_reply; pub(crate) mod readout; +pub(crate) mod shared_drafts; +pub(crate) mod shared_verification; +use shared_drafts::DraftOperation; +use shared_verification::VerificationOperation; mod step_telemetry; use self::batch_policy::{ @@ -86,6 +90,8 @@ pub(crate) struct IterationScheduler { pub(super) struct ScheduledGenerationRequest<'a> { pub(super) id: &'a str, + /// Admission priority: the request tier's priority. + pub(super) priority: u64, pub(super) prompt_tokens: &'a [i32], pub(super) max_tokens: u32, pub(super) sampling: Option<&'a SamplingConfig>, @@ -95,6 +101,7 @@ pub(super) struct ScheduledGenerationRequest<'a> { pub(super) struct ScheduledResumeRequest<'a> { pub(super) id: &'a str, + pub(super) priority: u64, pub(super) prompt_tokens: &'a [i32], pub(super) generated_tokens: &'a [i32], pub(super) max_tokens: u32, @@ -136,6 +143,7 @@ struct IterationSchedulerShared { struct ScheduledRequest { id: String, + priority: u64, prompt_tokens: Vec, max_tokens: u32, sampling: Option, @@ -188,7 +196,14 @@ fn ensure_direct_iteration_active( type RuntimeOperationFn = Box>) -> Duration + Send>; type RuntimeSetupOutcome = (Vec, Vec<(String, InferenceError)>); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RuntimeOperationKind { + Mutation, + Draft, +} + struct RuntimeOperation { + kind: RuntimeOperationKind, label: &'static str, control: Option, run: RuntimeOperationFn, @@ -271,6 +286,7 @@ where let enqueued_at = Instant::now(); let origin = trace_context::current_frame(); let operation = RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label, control: None, run: Box::new(move |runtime: &Arc>| { @@ -324,6 +340,7 @@ where let worker_control = control.clone(); let origin = trace_context::current_frame(); let runtime_operation = RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label, control: Some(control.clone()), run: Box::new(move |runtime: &Arc>| { @@ -359,6 +376,9 @@ where } enum SchedulerCommand { + Draft(DraftOperation), + Verify(VerificationOperation), + ExecuteLaneRuntime(String, RuntimeOperation), Submit(ScheduledRequest), ExecuteIteration(Box), ExecuteRuntime(RuntimeOperation), @@ -398,6 +418,9 @@ struct SchedulerWorker { scheduler: Scheduler, requests: BTreeMap, direct_iterations: VecDeque, + verifications: VecDeque, + drafts: VecDeque, + max_verify_iteration_tokens: usize, cache_runtime_queue: CacheRuntimeQueue, commands: std_mpsc::Receiver, kv_capacity_tokens: usize, @@ -533,6 +556,9 @@ impl IterationScheduler { ]), ); let (commands, receiver) = std_mpsc::sync_channel(command_queue_capacity); + let max_verify_iteration_tokens = (config.n_ubatch.unwrap_or(512) as usize) + .min(max_direct_iteration_tokens) + .min(config.ctx_size as usize); // 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( @@ -551,6 +577,9 @@ impl IterationScheduler { scheduler, requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens, cache_runtime_queue, commands: receiver, kv_capacity_tokens, @@ -597,6 +626,7 @@ impl IterationScheduler { let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), + priority: request.priority, prompt_tokens: request.prompt_tokens.to_vec(), max_tokens: request.max_tokens, sampling: request.sampling.cloned(), @@ -627,6 +657,7 @@ impl IterationScheduler { let _sequence = trace_context::bind_sequence(request.id); self.enqueue_command(SchedulerCommand::Submit(ScheduledRequest { id: request.id.to_string(), + priority: request.priority, prompt_tokens: request.prompt_tokens.to_vec(), max_tokens: request.max_tokens, sampling: request.sampling.cloned(), @@ -718,6 +749,8 @@ impl IterationScheduler { } } + // Tests use one-off channels; serving retains a channel across prefill chunks. + #[cfg(test)] pub(super) fn execute_iteration( &self, session_id: &str, @@ -873,6 +906,21 @@ impl IterationScheduler { })? } + /// Runs a mutation confined to one session, after that session's queued + /// verification. Work on other lanes may still join a shared forward. + pub(crate) fn execute_lane_runtime_timed( + &self, + session_id: String, + label: &'static str, + operation: impl FnOnce(&mut RuntimeState) -> InferenceResult + Send + 'static, + ) -> InferenceResult> { + let (operation, result) = runtime_operation(label, operation); + self.enqueue_command(SchedulerCommand::ExecuteLaneRuntime(session_id, operation))?; + result.recv().map_err(|error| { + InferenceError::backend(format!("iteration scheduler stopped: {error}")) + })? + } + fn enqueue_command(&self, command: SchedulerCommand) -> InferenceResult<()> { self.shared .commands @@ -958,6 +1006,8 @@ impl SchedulerWorker { loop { if self.requests.is_empty() && self.direct_iterations.is_empty() + && self.verifications.is_empty() + && self.drafts.is_empty() && self.cache_runtime_queue.is_empty() && !self.wait_idle() { @@ -974,8 +1024,18 @@ impl SchedulerWorker { Err(std_mpsc::TryRecvError::Disconnected) => return, } } + if !self.coalesce_drafts() { + return; + } + self.run_draft_batch(); + if !self.coalesce_verifications() { + return; + } + self.run_verification_batch(); if self.requests.is_empty() && self.direct_iterations.is_empty() + && self.verifications.is_empty() + && self.drafts.is_empty() && self.cache_runtime_queue.is_empty() { continue; @@ -1003,8 +1063,13 @@ impl SchedulerWorker { if !cache_fill_wave_pending && coalesce_direct && !self.coalesce_direct_iterations() { return; } + // A speculative command received during direct gathering must run + // before another direct batch or interval can delay its lane. + if !self.drafts.is_empty() || !self.verifications.is_empty() { + continue; + } self.run_work_turn(); - if !self.wait_iteration_interval() { + if !self.run_prefix_capture_after_work() || !self.wait_iteration_interval() { return; } } @@ -1012,11 +1077,32 @@ impl SchedulerWorker { fn handle_command(&mut self, command: SchedulerCommand) { match command { + SchedulerCommand::ExecuteLaneRuntime(session_id, operation) => { + while self.has_draft_for(&session_id) { + self.run_draft_batch(); + } + while self.has_verification_for(&session_id) { + self.run_verification_batch(); + } + self.run_runtime_operation(operation, None); + } + SchedulerCommand::Verify(operation) => self.verifications.push_back(operation), + SchedulerCommand::Draft(operation) => self.drafts.push_back(operation), SchedulerCommand::Submit(request) => self.submit(request), SchedulerCommand::ExecuteIteration(request) => { self.direct_iterations.push_back(*request); } SchedulerCommand::ExecuteRuntime(operation) => { + // Draft proposals do not change target positions. Other + // mutations remain barriers after admitted verification. + if operation.kind == RuntimeOperationKind::Mutation { + while !self.drafts.is_empty() { + self.run_draft_batch(); + } + while !self.verifications.is_empty() { + self.run_verification_batch(); + } + } self.run_runtime_operation(operation, None); } SchedulerCommand::ExecuteCacheAwareRuntime( @@ -1148,7 +1234,7 @@ impl SchedulerWorker { request.prompt_tokens.clone(), request.max_tokens, request.sampling.clone(), - 0, + request.priority, ) .with_admission_tokens(admission_tokens); if !request.generated_tokens.is_empty() { @@ -1547,6 +1633,8 @@ impl SchedulerWorker { } fn fail_all(&mut self, error: InferenceError) { + self.fail_verifications(&error); + self.fail_drafts(&error); let ids = self.requests.keys().cloned().collect::>(); for id in &ids { self.scheduler.cancel(id); diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs index b95aee5a..68282cfc 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy.rs @@ -44,6 +44,11 @@ impl BatchPlatform { /// The first GPU the runtime reports, else its first device. pub(super) fn detect() -> Self { + // Model-free schedulers can exist before the dynamic runtime loads. + // Keep their fallback policy instead of calling an unbound FFI table. + if !skippy_runtime::native_runtime_loaded() { + return Self::Other; + } let Ok(devices) = skippy_runtime::backend_devices_untraced() else { return Self::Other; }; @@ -186,6 +191,14 @@ pub(super) trait BatchPolicy: Send { fn tuning(&self) -> BatchTuning; fn gather(&self, view: &BatchView<'_>) -> Gather; fn select(&self, view: &BatchView<'_>) -> Selection; + /// Speculative lanes use the same configurable decode wait, capped so + /// drafting/verification cannot each add a full direct decode window. + fn gather_speculative(&self, active: usize, queued: usize, lanes: usize) -> Gather { + Gather { + target: direct_coalesce_target(active, queued, lanes), + window: self.tuning().decode_window.min(Duration::from_micros(300)), + } + } } /// The policy a stage gets when it configures nothing, on an unnamed backend. diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs index a4b6ad57..0259cfd3 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/batch_policy/tests.rs @@ -179,3 +179,23 @@ fn a_later_request_may_not_overtake_its_own_session() { ); assert_eq!(check_selection(&view, &Selection(vec![0, 1])), Ok(())); } + +#[test] +fn speculative_gather_uses_the_configured_decode_wait_with_a_short_cap() { + for (configured, expected) in [(0, 0), (50, 50), (300, 300), (2000, 300)] { + let policy = ArrivalOrder { + tuning: BatchTuning { + decode_window: Duration::from_micros(configured), + ..default_tuning() + }, + }; + assert_eq!( + policy.gather_speculative(4, 1, 2), + Gather { + target: 2, + window: Duration::from_micros(expected), + } + ); + assert_eq!(policy.gather_speculative(4, 0, 2).target, 0); + } +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs index 43c6ea3f..48893780 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/cache_runtime.rs @@ -5,7 +5,9 @@ use super::{ 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 skippy_scheduler::{ + CacheAffinity, CacheAwareCandidate, PriorityPassovers, order_cache_aware_candidates, +}; use std::sync::Arc; use std::time::Instant; @@ -18,6 +20,7 @@ pub(super) struct CacheAwareRuntimeOperation { priority: u64, enqueued_turn: u64, order: u64, + passover_mark: u64, scheduling: CacheSchedulingPolicy, refresh_affinity: Option, affinity_initialized: bool, @@ -44,6 +47,7 @@ pub(super) struct CacheRuntimeQueue { operations: Vec, order_dirty: bool, turn: u64, + passovers: PriorityPassovers, next_order: u64, aging_cost_per_turn: u64, group_waiting_prefixes: bool, @@ -61,6 +65,7 @@ impl CacheRuntimeQueue { operations: Vec::new(), order_dirty: false, turn: 0, + passovers: PriorityPassovers::default(), next_order: 0, aging_cost_per_turn, group_waiting_prefixes, @@ -154,6 +159,7 @@ impl CacheRuntimeQueue { priority, enqueued_turn: self.turn, order, + passover_mark: self.passovers.mark(priority), scheduling: state.scheduling, refresh_affinity: state.refresh_affinity, affinity_initialized: state.affinity_initialized, @@ -178,6 +184,12 @@ impl CacheRuntimeQueue { self.refresh_affinities(); self.reorder_if_dirty(); let queued = self.operations.pop()?; + self.passovers.record_selection(queued.priority); + // Passing lower priorities over can age them past another level. + self.order_dirty |= self + .operations + .iter() + .any(|operation| operation.priority < queued.priority); let affinity = &queued.affinity; let telemetry = CacheRuntimeTelemetry { matched_tokens: affinity.matched_tokens(), @@ -233,6 +245,9 @@ impl CacheRuntimeQueue { prompt_tokens: queued.prompt_tokens.as_ref(), enqueued_turn: queued.enqueued_turn, order: queued.order, + passed_over: self + .passovers + .passed_over(queued.priority, queued.passover_mark), }), self.turn, self.aging_cost_per_turn, @@ -360,6 +375,7 @@ impl IterationScheduler { #[cfg(test)] mod tests { use super::*; + use crate::frontend::iteration_scheduler::RuntimeOperationKind; use skippy_scheduler::StageCacheAffinity; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc; @@ -368,6 +384,7 @@ mod tests { fn operation(selected: &mpsc::Sender<&'static str>, label: &'static str) -> RuntimeOperation { let selected = selected.clone(); RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label, control: None, run: Box::new(move |_| { diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs index 79fdc49a..a4864f49 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/cache_wave.rs @@ -86,6 +86,9 @@ mod tests { )), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 8192, @@ -132,6 +135,7 @@ mod tests { queue_restore( &mut worker, RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "fourth-required-restore", control: None, run: Box::new(move |_| { @@ -163,6 +167,7 @@ mod tests { queue_restore( &mut worker, RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "next-wave-restore", control: None, run: Box::new(move |_| { @@ -192,6 +197,7 @@ mod tests { let observed = next_restore.clone(); worker.cache_runtime_queue.enqueue_with_policy( RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "next-wave-required-restore", control: None, run: Box::new(move |_| { diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs index af5116eb..4c1a3a42 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/command_waits.rs @@ -4,11 +4,55 @@ //! so time the runtime sits unused between native calls has a name. use super::*; +use crate::runtime_state::panic_recovery::try_lock_runtime; impl SchedulerWorker { - /// Block for the next command while no work is queued; false once the - /// worker should stop. + /// Give already-queued requests priority over the next checkpoint copy. + pub(super) fn run_prefix_capture_after_work(&mut self) -> bool { + let Some(mut runtime) = try_lock_runtime(&self.runtime) else { + return true; + }; + if !runtime.has_prefix_capture_work() { + return true; + } + match self.commands.try_recv() { + Ok(SchedulerCommand::Shutdown) | Err(std_mpsc::TryRecvError::Disconnected) => { + drop(runtime); + self.fail_all(InferenceError::backend("iteration scheduler stopped")); + false + } + Ok(command) => { + drop(runtime); + self.handle_command(command); + true + } + Err(std_mpsc::TryRecvError::Empty) => { + runtime.run_prefix_capture_step(); + true + } + } + } + + fn advance_prefix_capture(&mut self) -> bool { + try_lock_runtime(&self.runtime).is_some_and(|mut runtime| runtime.run_prefix_capture_step()) + } + + /// Advance pending checkpoint copies while idle, checking for requests + /// before every bounded step. When no copy can run, block for commands. pub(super) fn wait_idle(&mut self) -> bool { + loop { + match self.commands.try_recv() { + Ok(SchedulerCommand::Shutdown) | Err(std_mpsc::TryRecvError::Disconnected) => { + return false; + } + Ok(command) => { + self.handle_command(command); + return true; + } + Err(std_mpsc::TryRecvError::Empty) if self.advance_prefix_capture() => {} + Err(std_mpsc::TryRecvError::Empty) => break, + } + } let span = ActiveSpan::start( self.telemetry.as_ref(), "stage.scheduler_idle", @@ -78,7 +122,12 @@ impl SchedulerWorker { let deadline = Instant::now() + window; let mut timed_out = false; let mut running = true; - while running && self.direct_iterations.len() < target { + while running + && !self.direct_iterations.is_empty() + && self.drafts.is_empty() + && self.verifications.is_empty() + && self.direct_iterations.len() < target + { let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { timed_out = true; break; @@ -145,7 +194,10 @@ impl SchedulerWorker { /// 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() { + if self.iteration_interval.is_zero() + || !self.drafts.is_empty() + || !self.verifications.is_empty() + { return true; } self.wait_for_scheduler_command("stage.scheduler_interval", self.iteration_interval) diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs index 1669eee6..9dae4b7a 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/direct_batch/coalescing_tests.rs @@ -9,6 +9,9 @@ fn worker(commands: std_mpsc::Receiver) -> SchedulerWorker { scheduler: Scheduler::new(build_scheduler_config(4, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands, kv_capacity_tokens: 64, @@ -77,6 +80,7 @@ fn planned_work_reaches_runtime_admission_without_coalescing_an_empty_direct_que let (reply, events) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "planned".into(), + priority: 0, prompt_tokens: vec![1, 2], max_tokens: 1, sampling: None, @@ -104,3 +108,27 @@ fn planned_work_reaches_runtime_admission_without_coalescing_an_empty_direct_que assert!(worker.direct_iterations.is_empty()); assert!(!worker.last_served_direct); } + +#[test] +fn verification_interrupts_direct_gather_without_waiting_for_its_target() { + let (commands, receiver) = std_mpsc::channel(); + let mut worker = worker(receiver); + worker + .direct_iterations + .push_back(tests::direct_iteration("direct", 1)); + commands + .send(SchedulerCommand::Verify( + shared_verification::tests::operation("verify", 4), + )) + .unwrap(); + commands.send(SchedulerCommand::Shutdown).unwrap(); + assert!(worker.coalesce_direct_iterations()); + assert_eq!(worker.verifications.len(), 1); + assert_eq!(worker.direct_iterations.len(), 1); + assert!(matches!( + worker.commands.try_recv(), + Ok(SchedulerCommand::Shutdown) + )); + worker.iteration_interval = Duration::from_secs(1); + assert!(worker.wait_iteration_interval()); +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts.rs new file mode 100644 index 00000000..1a7bfeb3 --- /dev/null +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts.rs @@ -0,0 +1,207 @@ +//! Collects ready draft lanes before submitting their noise blocks. +use super::*; +use crate::runtime_state::draft_batch::RuntimeDraftRequest; +use skippy_runtime::DFlashProposal; + +#[cfg(test)] +mod tests; + +type DraftResult = InferenceResult>>; + +pub(super) struct DraftOperation { + request: RuntimeDraftRequest, + cancellation: Option, + enqueued_at: Instant, + reply: std_mpsc::SyncSender, +} + +impl DraftOperation { + fn complete( + self, + result: InferenceResult>, + lock_started: Instant, + hold_started: Instant, + ) { + let outcome = result.map(|value| SchedulerRuntimeOutcome { + value, + queue_wait_ms: lock_started.duration_since(self.enqueued_at).as_secs_f64() * 1000.0, + runtime_lock_wait_ms: hold_started.duration_since(lock_started).as_secs_f64() * 1000.0, + runtime_lock_hold_ms: hold_started.elapsed().as_secs_f64() * 1000.0, + }); + let _ = self.reply.send(outcome); + } +} + +pub(crate) fn enabled() -> bool { + enabled_by(env::var("SKIPPY_SHARED_DRAFT").ok().as_deref()) +} + +/// Sharing is capability checked at submission; zero retains independent work. +fn enabled_by(setting: Option<&str>) -> bool { + setting != Some("0") +} + +impl IterationScheduler { + /// Draft work never mutates target positions; express the barrier rule in + /// the operation kind, independently of its diagnostic label. + pub(crate) fn execute_independent_draft( + &self, + operation: impl FnOnce(&mut RuntimeState) -> InferenceResult + Send + 'static, + ) -> InferenceResult { + let (mut operation, result) = runtime_operation("dflash-propose", operation); + operation.kind = RuntimeOperationKind::Draft; + self.enqueue_command(SchedulerCommand::ExecuteRuntime(operation))?; + result + .recv() + .map_err(|error| { + InferenceError::backend(format!("iteration scheduler stopped: {error}")) + })? + .map(|outcome| outcome.value) + } + + pub(crate) fn execute_draft_timed( + &self, + request: RuntimeDraftRequest, + cancellation: Option<&skippy_inference_api::CancellationToken>, + ) -> DraftResult { + let (reply, result) = std_mpsc::sync_channel(1); + self.enqueue_command(SchedulerCommand::Draft(DraftOperation { + request, + cancellation: cancellation.cloned(), + enqueued_at: Instant::now(), + reply, + }))?; + result.recv().map_err(|error| { + InferenceError::backend(format!("iteration scheduler stopped: {error}")) + })? + } +} + +fn take_drafts(queue: &mut VecDeque, lanes: usize) -> Vec { + let mut claimed = BTreeSet::new(); + let mut batch = Vec::new(); + let mut deferred = VecDeque::new(); + for _ in 0..queue.len() { + if batch.len() >= lanes.max(1) { + break; + } + let Some(operation) = queue.pop_front() else { + break; + }; + if claimed.insert(operation.request.session_id.clone()) { + batch.push(operation); + } else { + deferred.push_back(operation); + } + } + deferred.append(queue); + *queue = deferred; + batch +} + +impl SchedulerWorker { + pub(super) fn coalesce_drafts(&mut self) -> bool { + if self.drafts.is_empty() { + return true; + } + let Gather { target, window } = self.batch_policy.gather_speculative( + self.active_runtime_sessions, + self.drafts.len(), + self.max_direct_batch_size, + ); + let mut idle_budget = window; + for _ in 0..self.max_commands_per_turn { + if self.drafts.is_empty() + || !self.verifications.is_empty() + || self.drafts.len() >= target + || idle_budget.is_zero() + { + break; + } + let started = Instant::now(); + let span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_drafts_coalesce", + SpanLevel::Debug, + ); + let received = self.commands.recv_timeout(idle_budget); + span.end(); + idle_budget = idle_budget.saturating_sub(started.elapsed()); + match received { + 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, + } + } + true + } + + pub(super) fn run_draft_batch(&mut self) { + let batch = take_drafts(&mut self.drafts, self.max_direct_batch_size); + if batch.is_empty() { + return; + } + let lock_started = Instant::now(); + let mut runtime = lock_runtime(&self.runtime); + let hold_started = Instant::now(); + let mut valid = Vec::new(); + for operation in batch { + let status = ensure_direct_iteration_active(None, operation.cancellation.as_ref()); + if let Err(error) = status { + operation.complete(Err(error), lock_started, hold_started); + } else if runtime.session_token_count(&operation.request.session_id) + != Some(operation.request.base_position) + { + operation.complete(Ok(None), lock_started, hold_started); + } else { + valid.push(operation); + } + } + let mut shared_lanes = 0; + if !valid.is_empty() { + let requests: Vec<_> = valid.iter().map(|operation| &operation.request).collect(); + match runtime.dflash_propose_batch(&requests) { + Ok(output) => { + shared_lanes = output.shared_lanes; + for (operation, proposal) in valid.into_iter().zip(output.proposals) { + operation.complete(Ok(proposal), lock_started, hold_started); + } + } + Err(error) => { + let error = openai_backend_error(error); + for operation in valid { + operation.complete(Err(error.clone()), lock_started, hold_started); + } + } + } + } + self.active_runtime_sessions = runtime.active_session_count(); + drop(runtime); + self.record_compute(hold_started.elapsed()); + if shared_lanes > 1 + && let Some(telemetry) = &self.telemetry + { + telemetry.emit( + "stage.shared_draft", + BTreeMap::from([("skippy.draft.batch_size".to_string(), json!(shared_lanes))]), + ); + } + } + + pub(super) fn has_draft_for(&self, session_id: &str) -> bool { + self.drafts + .iter() + .any(|operation| operation.request.session_id == session_id) + } + + pub(super) fn fail_drafts(&mut self, error: &InferenceError) { + let now = Instant::now(); + for operation in self.drafts.drain(..) { + operation.complete(Err(error.clone()), now, now); + } + } +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts/tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts/tests.rs new file mode 100644 index 00000000..345d1d9c --- /dev/null +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_drafts/tests.rs @@ -0,0 +1,120 @@ +use super::super::shared_verification::tests::worker; +use super::*; + +#[test] +fn sharing_is_default_and_explicit_zero_retains_independent_drafts() { + for setting in [None, Some(""), Some("1")] { + assert!(enabled_by(setting)); + } + assert!(!enabled_by(Some("0"))); +} + +fn operation(id: &str, width: usize) -> (DraftOperation, std_mpsc::Receiver) { + let (reply, result) = std_mpsc::sync_channel(1); + ( + DraftOperation { + request: RuntimeDraftRequest { + session_id: id.to_string(), + anchor: 1, + max_tokens: width, + base_position: 0, + }, + cancellation: None, + enqueued_at: Instant::now(), + reply, + }, + result, + ) +} + +#[test] +fn ragged_drafts_join_without_reordering_one_sessions_work() { + let (a, _) = operation("a", 6); + let (b, _) = operation("b", 3); + let (again, _) = operation("a", 2); + let (c, _) = operation("c", 4); + let mut queue = VecDeque::from([a, again, b, c]); + let batch = take_drafts(&mut queue, 3); + assert_eq!( + batch + .iter() + .map(|op| (op.request.session_id.as_str(), op.request.max_tokens)) + .collect::>(), + [("a", 6), ("b", 3), ("c", 4)] + ); + assert_eq!(queue.front().unwrap().request.max_tokens, 2); +} + +#[test] +fn cancelled_and_stale_drafts_do_not_activate_a_native_lane() { + let mut worker = worker(); + let (mut cancelled, error) = operation("cancelled", 6); + let token = skippy_inference_api::CancellationToken::new(); + token.cancel(); + cancelled.cancellation = Some(token); + let (stale, empty) = operation("stale", 3); + worker.drafts.extend([cancelled, stale]); + worker.run_draft_batch(); + assert!(error.recv().unwrap().is_err()); + assert!(empty.recv().unwrap().unwrap().value.is_none()); + assert_eq!(lock_runtime(&worker.runtime).active_session_count(), 0); +} + +#[test] +fn mutations_respect_draft_session_barriers_and_shutdown_returns_errors() { + let mut worker = worker(); + let (waiting, result) = operation("a", 6); + worker.drafts.push_back(waiting); + let (send, receive) = std_mpsc::channel(); + let sender = send.clone(); + worker.handle_command(SchedulerCommand::ExecuteLaneRuntime( + "b".to_string(), + RuntimeOperation { + kind: RuntimeOperationKind::Mutation, + label: "repair-b", + control: None, + run: Box::new(move |_| { + sender.send("b").unwrap(); + Duration::ZERO + }), + }, + )); + assert_eq!(receive.recv().unwrap(), "b"); + assert_eq!(worker.drafts.len(), 1); + worker.handle_command(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, + label: "mutation", + control: None, + run: Box::new(move |_| { + send.send("global").unwrap(); + Duration::ZERO + }), + })); + assert_eq!(receive.recv().unwrap(), "global"); + assert!(result.recv().unwrap().unwrap().value.is_none()); + assert!(worker.drafts.is_empty()); + let (waiting, result) = operation("waiting", 4); + worker.drafts.push_back(waiting); + worker.fail_all(InferenceError::backend("stopped")); + assert!(result.recv().unwrap().is_err()); +} + +#[test] +fn ready_verification_prevents_another_draft_gather_wait() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + worker.commands = receive; + worker.active_runtime_sessions = 2; + worker.drafts.push_back(operation("draft", 4).0); + worker + .verifications + .push_back(super::super::shared_verification::tests::operation( + "verify", 4, + )); + send.send(SchedulerCommand::Shutdown).unwrap(); + assert!(worker.coalesce_drafts()); + assert!(matches!( + worker.commands.try_recv(), + Ok(SchedulerCommand::Shutdown) + )); +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification.rs new file mode 100644 index 00000000..21a6a18e --- /dev/null +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification.rs @@ -0,0 +1,252 @@ +//! Coalesces compatible speculative windows without sharing sampling state. +use super::*; +use crate::runtime_state::RuntimeVerificationRequest; + +#[cfg(test)] +pub(super) mod tests; + +struct VerifiedWindow { + predictions: Vec, + batch_size: usize, +} +type Verified = InferenceResult>; +type Completion = Box; + +pub(super) struct VerificationOperation { + request: RuntimeVerificationRequest, + cancellation: Option, + complete: Completion, +} + +pub(crate) fn enabled() -> bool { + enabled_by(env::var("SKIPPY_SHARED_VERIFY").ok().as_deref()) +} + +/// Complete causal targets share compatible windows unless explicitly disabled. +fn enabled_by(setting: Option<&str>) -> bool { + setting != Some("0") +} + +impl IterationScheduler { + pub(crate) fn execute_verification_timed( + &self, + request: RuntimeVerificationRequest, + cancellation: Option<&skippy_inference_api::CancellationToken>, + finish: impl FnOnce(&mut RuntimeState, Vec, usize) -> InferenceResult + Send + 'static, + ) -> InferenceResult>> { + let (reply, result) = std_mpsc::sync_channel(1); + let enqueued_at = Instant::now(); + let operation = VerificationOperation { + request, + cancellation: cancellation.cloned(), + complete: Box::new(move |runtime, predictions, lock_started, hold_started| { + let value = predictions.and_then(|predictions| { + predictions + .map(|window| finish(runtime, window.predictions, window.batch_size)) + .transpose() + }); + let outcome = value.map(|value| SchedulerRuntimeOutcome { + value, + queue_wait_ms: lock_started.duration_since(enqueued_at).as_secs_f64() * 1000.0, + runtime_lock_wait_ms: hold_started.duration_since(lock_started).as_secs_f64() + * 1000.0, + runtime_lock_hold_ms: hold_started.elapsed().as_secs_f64() * 1000.0, + }); + let _ = reply.send(outcome); + }), + }; + self.enqueue_command(SchedulerCommand::Verify(operation))?; + result.recv().map_err(|error| { + InferenceError::backend(format!("iteration scheduler stopped: {error}")) + })? + } +} + +fn take_batch( + queue: &mut VecDeque, + lanes: usize, + budget: usize, +) -> Vec { + let Some(first) = queue.pop_front() else { + return Vec::new(); + }; + let width = first.request.token_ids.len(); + let cap = lanes.min(budget.checked_div(width).unwrap_or(1)).max(1); + let mut claimed = BTreeSet::from([first.request.session_id.clone()]); + let mut batch = vec![first]; + let mut deferred = VecDeque::new(); + for _ in 0..queue.len() { + if batch.len() >= cap { + break; + } + let Some(operation) = queue.pop_front() else { + break; + }; + let unique = claimed.insert(operation.request.session_id.clone()); + if unique && operation.request.token_ids.len() == width { + batch.push(operation); + } else { + deferred.push_back(operation); + } + } + deferred.append(queue); + *queue = deferred; + batch +} + +impl SchedulerWorker { + pub(super) fn coalesce_verifications(&mut self) -> bool { + if self.verifications.is_empty() { + return true; + } + let Gather { target, window } = self.batch_policy.gather_speculative( + self.active_runtime_sessions, + self.verifications.len(), + self.max_direct_batch_size, + ); + let mut idle_budget = window; + for _ in 0..self.max_commands_per_turn { + if self.verifications.is_empty() + || self.verifications.len() >= target + || idle_budget.is_zero() + { + break; + } + let started = Instant::now(); + let span = ActiveSpan::start( + self.telemetry.as_ref(), + "stage.scheduler_verifications_coalesce", + SpanLevel::Debug, + ); + let received = self.commands.recv_timeout(idle_budget); + span.end(); + idle_budget = idle_budget.saturating_sub(started.elapsed()); + // Useful draft/repair work may execute here. Charge only idle + // waiting to this budget, not model work on another lane. + match received { + Ok(SchedulerCommand::Shutdown) => { + self.fail_all(InferenceError::backend("iteration scheduler stopped")); + return false; + } + Ok(command) => { + self.handle_command(command); + // A peer waiting on its draft cannot enqueue verification + // until the draft completes. Let it join this verify wave. + self.run_draft_batch(); + } + Err(std_mpsc::RecvTimeoutError::Timeout) => break, + Err(std_mpsc::RecvTimeoutError::Disconnected) => return false, + } + } + true + } + + pub(super) fn run_verification_batch(&mut self) { + let batch = take_batch( + &mut self.verifications, + self.max_direct_batch_size, + self.max_verify_iteration_tokens, + ); + if batch.is_empty() { + return; + } + let lock_started = Instant::now(); + let mut runtime = lock_runtime(&self.runtime); + let hold_started = Instant::now(); + let mut valid = Vec::new(); + for operation in batch { + let status = ensure_direct_iteration_active(None, operation.cancellation.as_ref()); + if let Err(error) = status { + (operation.complete)(&mut runtime, Err(error), lock_started, hold_started); + } else if runtime.session_token_count(&operation.request.session_id) + != Some(operation.request.base_position) + { + (operation.complete)(&mut runtime, Ok(None), lock_started, hold_started); + } else { + valid.push(operation); + } + } + let shared = valid.len() > 1 + && runtime.shared_verification_fits( + &valid + .iter() + .map(|operation| &operation.request) + .collect::>(), + ); + let batch_size = valid.len(); + if shared { + let requests: Vec<_> = valid.iter().map(|operation| &operation.request).collect(); + match runtime.verify_batch_sampled(&requests) { + Ok(outputs) => { + for (operation, output) in valid.into_iter().zip(outputs) { + (operation.complete)( + &mut runtime, + Ok(Some(VerifiedWindow { + predictions: output, + batch_size, + })), + lock_started, + hold_started, + ); + } + } + Err(error) => { + let error = openai_backend_error(error); + for operation in valid { + (operation.complete)( + &mut runtime, + Err(error.clone()), + lock_started, + hold_started, + ); + } + } + } + } else { + for operation in valid { + let request = &operation.request; + let output = runtime + .verify_tokens_sampled( + &request.session_id, + &request.token_ids, + request.sampling.as_ref(), + ) + .map(|predictions| { + Some(VerifiedWindow { + predictions, + batch_size: 1, + }) + }) + .map_err(openai_backend_error); + (operation.complete)(&mut runtime, output, lock_started, hold_started); + } + } + let active = runtime.active_session_count(); + drop(runtime); + self.active_runtime_sessions = active; + self.record_compute(hold_started.elapsed()); + if shared && let Some(telemetry) = &self.telemetry { + telemetry.emit( + "stage.shared_verification", + BTreeMap::from([ + ("skippy.verify.shared".to_string(), json!(true)), + ("skippy.verify.batch_size".to_string(), json!(batch_size)), + ]), + ); + } + } + + pub(super) fn has_verification_for(&self, session_id: &str) -> bool { + self.verifications + .iter() + .any(|operation| operation.request.session_id == session_id) + } + + pub(super) fn fail_verifications(&mut self, error: &InferenceError) { + let mut runtime = lock_runtime(&self.runtime); + let now = Instant::now(); + for operation in self.verifications.drain(..) { + (operation.complete)(&mut runtime, Err(error.clone()), now, now); + } + } +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification/tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification/tests.rs new file mode 100644 index 00000000..f9baa275 --- /dev/null +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/shared_verification/tests.rs @@ -0,0 +1,214 @@ +use super::*; + +#[test] +fn sharing_is_default_and_explicit_zero_retains_independent_verification() { + for setting in [None, Some(""), Some("1")] { + assert!(enabled_by(setting)); + } + assert!(!enabled_by(Some("0"))); +} + +pub(in crate::frontend::iteration_scheduler) fn operation( + id: &str, + width: usize, +) -> VerificationOperation { + VerificationOperation { + request: RuntimeVerificationRequest { + session_id: id.to_string(), + token_ids: vec![1; width], + sampling: None, + base_position: 0, + }, + cancellation: None, + complete: Box::new(|_, _, _, _| {}), + } +} + +pub(in crate::frontend::iteration_scheduler) fn worker() -> SchedulerWorker { + let (_commands, receiver) = std_mpsc::channel(); + SchedulerWorker { + runtime: Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(2))), + compute_meter: Arc::default(), + scheduler: Scheduler::new(build_scheduler_config(2, 64, 0, Some(8), Some(8), 8, false)), + requests: BTreeMap::new(), + direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, + cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), + commands: receiver, + kv_capacity_tokens: 64, + max_direct_batch_size: 2, + direct_group_batch_size: 2, + 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, + active_runtime_sessions: 0, + cache_wave_sessions: 0, + direct_wave_full: false, + telemetry: None, + last_served_direct: false, + last_served_cache_runtime: false, + last_emitted_lifecycle_counters: (0, 0, 0, 0), + } +} + +#[test] +fn incompatible_windows_keep_session_fifo_while_other_lanes_join() { + let mut queue = VecDeque::from([ + operation("a", 4), + operation("b", 2), + operation("b", 4), + operation("c", 4), + ]); + let batch = take_batch(&mut queue, 4, 32); + assert_eq!( + batch + .iter() + .map(|op| op.request.session_id.as_str()) + .collect::>(), + ["a", "c"] + ); + assert_eq!( + queue + .iter() + .map(|op| (op.request.session_id.as_str(), op.request.token_ids.len())) + .collect::>(), + [("b", 2), ("b", 4)] + ); +} + +#[test] +fn combined_windows_obey_the_native_microbatch_limit() { + let mut queue = VecDeque::from([operation("a", 7), operation("b", 7), operation("c", 7)]); + assert_eq!(take_batch(&mut queue, 4, 14).len(), 2); + assert_eq!(queue.front().unwrap().request.session_id, "c"); + let mut queue = VecDeque::from([operation("empty", 0), operation("a", 7)]); + assert_eq!(take_batch(&mut queue, 4, 14).len(), 1); +} + +#[test] +fn cancelled_and_stale_windows_never_activate_a_runtime_lane() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + let mut cancelled = operation("cancelled", 4); + let cancellation = skippy_inference_api::CancellationToken::new(); + cancellation.cancel(); + cancelled.cancellation = Some(cancellation); + let sender = send.clone(); + cancelled.complete = Box::new(move |_, result, _, _| sender.send(result.is_err()).unwrap()); + let mut stale = operation("stale", 4); + stale.complete = + Box::new(move |_, result, _, _| send.send(matches!(result, Ok(None))).unwrap()); + worker.verifications.extend([cancelled, stale]); + worker.run_verification_batch(); + assert!(receive.recv().unwrap()); + assert!(receive.recv().unwrap()); + assert_eq!(lock_runtime(&worker.runtime).active_session_count(), 0); +} + +#[test] +fn runtime_mutation_is_a_barrier_after_queued_verification() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + let mut stale = operation("stale", 4); + let sender = send.clone(); + stale.complete = Box::new(move |_, _, _, _| sender.send("verify").unwrap()); + worker.verifications.push_back(stale); + worker.handle_command(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, + label: "dflash-propose", + control: None, + run: Box::new(move |_| { + send.send("repair").unwrap(); + Duration::ZERO + }), + })); + assert_eq!( + [receive.recv().unwrap(), receive.recv().unwrap()], + ["verify", "repair"] + ); +} + +#[test] +fn shutdown_completes_waiting_verification_with_an_error() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + let mut operation = operation("waiting", 4); + operation.complete = Box::new(move |_, result, _, _| send.send(result.is_err()).unwrap()); + worker.verifications.push_back(operation); + worker.fail_all(InferenceError::backend("stopped")); + assert!(receive.recv().unwrap()); + assert!(worker.verifications.is_empty()); +} + +#[test] +fn repairs_on_other_lanes_do_not_flush_waiting_verification() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + let mut waiting = operation("a", 4); + let sender = send.clone(); + waiting.complete = Box::new(move |_, _, _, _| sender.send("verify-a").unwrap()); + worker.verifications.push_back(waiting); + let sender = send.clone(); + worker.handle_command(SchedulerCommand::ExecuteLaneRuntime( + "b".to_string(), + RuntimeOperation { + kind: RuntimeOperationKind::Mutation, + label: "repair-b", + control: None, + run: Box::new(move |_| { + sender.send("repair-b").unwrap(); + Duration::ZERO + }), + }, + )); + assert_eq!(receive.recv().unwrap(), "repair-b"); + assert_eq!(worker.verifications.len(), 1); + worker.handle_command(SchedulerCommand::ExecuteLaneRuntime( + "a".to_string(), + RuntimeOperation { + kind: RuntimeOperationKind::Mutation, + label: "repair-a", + control: None, + run: Box::new(move |_| { + send.send("repair-a").unwrap(); + Duration::ZERO + }), + }, + )); + assert_eq!( + [receive.recv().unwrap(), receive.recv().unwrap()], + ["verify-a", "repair-a"] + ); +} + +#[test] +fn drained_verification_queue_does_not_consume_the_next_command() { + let mut worker = worker(); + let (send, receive) = std_mpsc::channel(); + worker.commands = receive; + worker.active_runtime_sessions = 2; + worker.verifications.push_back(operation("stale", 4)); + let (mutation, _result) = runtime_operation("drain", |_| Ok(())); + send.send(SchedulerCommand::ExecuteRuntime(mutation)) + .unwrap(); + send.send(SchedulerCommand::Shutdown).unwrap(); + assert!(worker.coalesce_verifications()); + assert!(worker.verifications.is_empty()); + assert!(matches!( + worker.commands.try_recv(), + Ok(SchedulerCommand::Shutdown) + )); +} + +#[test] +fn draft_kind_does_not_depend_on_the_diagnostic_label() { + let mut worker = worker(); + worker.verifications.push_back(operation("pending", 4)); + let (mut draft, _result) = runtime_operation("renamed-diagnostic", |_| Ok(())); + draft.kind = RuntimeOperationKind::Draft; + worker.handle_command(SchedulerCommand::ExecuteRuntime(draft)); + assert_eq!(worker.verifications.len(), 1); +} diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs index 20eee41b..4b58b4ae 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/step_telemetry.rs @@ -193,6 +193,9 @@ mod tests { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, diff --git a/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs b/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs index ca3eddf9..4ff593dd 100644 --- a/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs +++ b/crates/skippy-serving/src/frontend/iteration_scheduler/tests.rs @@ -89,6 +89,9 @@ fn expired_direct_iteration_behind_blocked_worker_never_reaches_native_runtime() scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -112,6 +115,7 @@ fn expired_direct_iteration_behind_blocked_worker_never_reaches_native_runtime() let (release_worker, release_worker_rx) = std_mpsc::sync_channel(0); commands .send(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "deadline-test-gate", control: None, run: Box::new(move |_| { @@ -265,6 +269,9 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { scheduler: Scheduler::new(build_scheduler_config(2, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -286,6 +293,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { let (reply_b, events_b) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "a".into(), + priority: 0, prompt_tokens: vec![1, 2], max_tokens: 1, sampling: None, @@ -297,6 +305,7 @@ fn server_scheduler_worker_batches_and_completes_default_generations() { }); worker.submit(ScheduledRequest { id: "b".into(), + priority: 0, prompt_tokens: vec![3, 4], max_tokens: 1, sampling: None, @@ -375,6 +384,9 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -395,6 +407,7 @@ fn token_control_is_applied_without_blocking_the_scheduler_iteration() { let (reply, events) = std_mpsc::channel(); worker.submit(ScheduledRequest { id: "slow-consumer".into(), + priority: 0, prompt_tokens: vec![1], max_tokens: 2, sampling: None, @@ -488,6 +501,9 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -536,9 +552,8 @@ fn resumed_request_cancellation_leaves_runtime_for_caller_cleanup() { assert!(worker.scheduler.sequence("resumed").is_none()); } -#[test] -fn feature_runtime_operations_execute_on_the_scheduler_worker() { - let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(3))); +fn feature_test_scheduler(runtime: RuntimeState) -> IterationScheduler { + let runtime = Arc::new(Mutex::new(runtime)); let (commands, receiver) = std_mpsc::sync_channel(8); let worker = thread::spawn(move || { SchedulerWorker { @@ -547,6 +562,9 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { scheduler: Scheduler::new(build_scheduler_config(3, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -566,15 +584,19 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { } .run(); }); - let scheduler = IterationScheduler { + IterationScheduler { shared: Arc::new(IterationSchedulerShared { commands, max_direct_iteration_tokens: MAX_NATIVE_ITERATION_TOKENS, owner_count: AtomicUsize::new(1), worker: Mutex::new(Some(worker)), }), - }; + } +} +#[test] +fn feature_runtime_operations_execute_on_the_scheduler_worker() { + let scheduler = feature_test_scheduler(RuntimeState::new_modelless_for_test(3)); let outcome = scheduler .execute_runtime_timed("test-feature-runtime", |runtime| Ok(runtime.lane_count())) .unwrap(); @@ -584,6 +606,39 @@ fn feature_runtime_operations_execute_on_the_scheduler_worker() { assert!(outcome.runtime_lock_hold_ms >= 0.0); } +#[test] +fn queued_runtime_command_runs_between_prefix_capture_steps() { + let mut runtime = RuntimeState::split_dflash_final_stage_for_test(); + runtime.ensure_session_active("capture-source").unwrap(); + let (started, first_step) = std_mpsc::sync_channel(1); + let (release, resume) = std_mpsc::sync_channel(1); + let steps = Arc::new(AtomicUsize::new(0)); + let capture_steps = Arc::clone(&steps); + let timeout = Duration::from_secs(5); + runtime.offer_prefix_capture("capture-source", true, move |_, _| { + if capture_steps.fetch_add(1, Ordering::Relaxed) == 0 { + started.send(()).unwrap(); + resume.recv_timeout(timeout).unwrap(); + std::ops::ControlFlow::Continue(()) + } else { + std::ops::ControlFlow::Break(()) + } + }); + let scheduler = feature_test_scheduler(runtime); + first_step.recv_timeout(timeout).unwrap(); + + let (operation, response) = runtime_operation("queued-during-prefix-capture", move |_| { + Ok(steps.load(Ordering::Relaxed)) + }); + scheduler + .enqueue_command(SchedulerCommand::ExecuteRuntime(operation)) + .unwrap(); + release.send(()).unwrap(); + + let outcome = response.recv_timeout(timeout).unwrap().unwrap(); + assert_eq!(outcome.value, 1); +} + #[test] fn detached_runtime_operation_returns_before_work_completes() { let runtime = Arc::new(Mutex::new(RuntimeState::new_modelless_for_test(3))); @@ -595,6 +650,9 @@ fn detached_runtime_operation_returns_before_work_completes() { scheduler: Scheduler::new(build_scheduler_config(3, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -740,6 +798,9 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -759,6 +820,7 @@ fn full_direct_wave_suppresses_cache_runtime_while_direct_queue_is_temporarily_e }; worker.cache_runtime_queue.enqueue_with_policy( RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "full-wave-cache", control: None, run: Box::new(move |_| { @@ -790,6 +852,9 @@ fn resident_kv_does_not_engage_direct_wave_gate() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -809,6 +874,7 @@ fn resident_kv_does_not_engage_direct_wave_gate() { }; worker.cache_runtime_queue.enqueue( RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "resident-cache", control: None, run: Box::new(move |_| { @@ -887,6 +953,9 @@ fn worker_panic_is_contained_and_fails_active_requests() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -910,6 +979,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { let (release_worker, release_worker_rx) = std_mpsc::sync_channel(0); commands .send(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "panic-test-gate", control: None, run: Box::new(move |_| { @@ -925,6 +995,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { commands .send(SchedulerCommand::Submit(ScheduledRequest { id: "panic-contained".into(), + priority: 0, prompt_tokens: vec![1], max_tokens: 1, sampling: None, @@ -937,6 +1008,7 @@ fn worker_panic_is_contained_and_fails_active_requests() { .unwrap(); commands .send(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "panic-test", control: None, run: Box::new(|_| -> Duration { panic!("injected scheduler worker panic") }), @@ -1009,6 +1081,9 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -1033,6 +1108,7 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { let run_guard = CaptureTaskOutstandingGuard::new(run_counter); commands .send(SchedulerCommand::ExecuteRuntime(RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label: "capture-unit-run", control: None, run: Box::new(move |_| { @@ -1055,6 +1131,7 @@ fn detached_capture_unit_releases_on_completion_rejection_and_shutdown_drop() { fn capture_operation(counter: &Arc, label: &'static str) -> RuntimeOperation { let guard = CaptureTaskOutstandingGuard::new(counter.clone()); RuntimeOperation { + kind: RuntimeOperationKind::Mutation, label, control: None, run: Box::new(move |_| { @@ -1105,6 +1182,9 @@ fn scheduler_worker_keeps_serving_after_an_operation_panics() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, @@ -1169,6 +1249,9 @@ fn direct_iterations_in_a_panicking_batch_get_an_error() { scheduler: Scheduler::new(build_scheduler_config(1, 64, 0, Some(8), Some(8), 8, false)), requests: BTreeMap::new(), direct_iterations: VecDeque::new(), + verifications: VecDeque::new(), + drafts: VecDeque::new(), + max_verify_iteration_tokens: 512, cache_runtime_queue: CacheRuntimeQueue::new(CACHE_AGING_COST_PER_TURN, true), commands: receiver, kv_capacity_tokens: 64, diff --git a/crates/skippy-serving/src/frontend/linear_proposal/execution.rs b/crates/skippy-serving/src/frontend/linear_proposal/execution.rs index e4a9cb2c..d3d293c4 100644 --- a/crates/skippy-serving/src/frontend/linear_proposal/execution.rs +++ b/crates/skippy-serving/src/frontend/linear_proposal/execution.rs @@ -22,6 +22,7 @@ pub(crate) struct LinearProposalExecution { pub(crate) repair_elapsed_us: u64, pub(crate) runtime_lock_wait_us: u64, pub(crate) runtime_lock_hold_us: u64, + pub(crate) compute_share_us: u64, pub(crate) runtime_lock_acquires: usize, } @@ -168,42 +169,61 @@ impl StageOpenAiBackend { let base_position = params.base_position; let generated_len = params.generated_len; let max_new_tokens = params.max_new_tokens; - let verification = self.iteration_scheduler.execute_runtime_timed( - "linear-proposal-verify", - move |runtime| { - let observed_position = - runtime.session_token_count(&session_id).ok_or_else(|| { - InferenceError::backend("linear proposal session is not active") - })?; - if observed_position != base_position { - return Ok(None); - } - let predictions = runtime - .verify_tokens_sampled(&session_id, &owned_verify_inputs, sampling.as_ref()) - .map_err(openai_backend_error)?; - let decision = classify_native_mtp_verify_window( - &owned_proposal_tokens, - &predictions, - generated_len, - max_new_tokens, - |token| { - runtime - .model - .token_is_eog(token) - .map_err(openai_backend_error) - }, - )?; - let position_after_verification = - runtime.session_token_count(&session_id).ok_or_else(|| { - InferenceError::backend("linear proposal session disappeared") - })?; - Ok(Some((predictions, decision, position_after_verification))) - }, - )?; + let finish_session_id = session_id.clone(); + let finish = move |runtime: &mut crate::runtime_state::RuntimeState, + predictions: Vec, + batch_size: usize| { + let decision = classify_native_mtp_verify_window( + &owned_proposal_tokens, + &predictions, + generated_len, + max_new_tokens, + |token| { + runtime + .model + .token_is_eog(token) + .map_err(openai_backend_error) + }, + )?; + let position = runtime + .session_token_count(&finish_session_id) + .ok_or_else(|| InferenceError::backend("linear proposal session disappeared"))?; + Ok((predictions, decision, position, batch_size)) + }; + let verification = if crate::frontend::iteration_scheduler::shared_verification::enabled() { + self.iteration_scheduler.execute_verification_timed( + crate::runtime_state::RuntimeVerificationRequest { + session_id, + token_ids: owned_verify_inputs, + sampling, + base_position, + }, + cancellation, + finish, + )? + } else { + self.iteration_scheduler.execute_runtime_timed( + "linear-proposal-verify", + move |runtime| { + let observed_position = + runtime.session_token_count(&session_id).ok_or_else(|| { + InferenceError::backend("linear proposal session is not active") + })?; + if observed_position != base_position { + return Ok(None); + } + let predictions = runtime + .verify_tokens_sampled(&session_id, &owned_verify_inputs, sampling.as_ref()) + .map_err(openai_backend_error)?; + finish(runtime, predictions, 1).map(Some) + }, + )? + }; let verification_lock_wait_us = millis_to_micros(verification.runtime_lock_wait_ms); let verification_lock_hold_us = millis_to_micros(verification.runtime_lock_hold_ms); let execution = verification.value; - let Some((predictions, decision, position_after_verification)) = execution else { + let Some((predictions, decision, position_after_verification, batch_size)) = execution + else { return Ok(None); }; let expected_position_after_verification = params @@ -285,6 +305,8 @@ impl StageOpenAiBackend { .saturating_add(repair.runtime_lock_wait_us), runtime_lock_hold_us: verification_lock_hold_us .saturating_add(repair.runtime_lock_hold_us), + compute_share_us: (verification_lock_hold_us / batch_size.max(1) as u64) + .saturating_add(repair.runtime_lock_hold_us), runtime_lock_acquires: 1usize.saturating_add(repair.runtime_lock_acquires), })) } @@ -309,7 +331,8 @@ impl StageOpenAiBackend { let chat_sampling_metadata = chat_sampling_metadata.map(str::to_string); if canonical_position >= position_after_verification { let retire_timer = Instant::now(); - let outcome = self.iteration_scheduler.execute_runtime_timed( + let outcome = self.iteration_scheduler.execute_lane_runtime_timed( + session_id.clone(), "linear-proposal-retire", move |runtime| { runtime @@ -331,7 +354,8 @@ impl StageOpenAiBackend { } let repair_timer = Instant::now(); - let outcome = self.iteration_scheduler.execute_runtime_timed( + let outcome = self.iteration_scheduler.execute_lane_runtime_timed( + session_id.clone(), "linear-proposal-repair", move |runtime| { if let Err(error) = runtime.trim_session(&session_id, canonical_position) { diff --git a/crates/skippy-serving/src/frontend/local_generation.rs b/crates/skippy-serving/src/frontend/local_generation.rs index 39617245..96fa2579 100644 --- a/crates/skippy-serving/src/frontend/local_generation.rs +++ b/crates/skippy-serving/src/frontend/local_generation.rs @@ -9,6 +9,7 @@ mod resident_prefill; #[cfg(test)] mod tests; mod token_generation; +mod uncached_prefill; // Test-only: re-export of the outstanding-capture guard used by // iteration_scheduler tests (see token_generation::exact_state_recording). pub(in crate::frontend) use dflash_decode::AdaptiveBlocks; @@ -145,10 +146,3 @@ impl StageOpenAiBackend { } } } - -pub(super) fn prompt_fits_single_prefill_sample( - prompt_token_count: usize, - session_batch_size: usize, -) -> bool { - prompt_token_count > 1 && prompt_token_count <= session_batch_size -} diff --git a/crates/skippy-serving/src/frontend/local_generation/decode_step.rs b/crates/skippy-serving/src/frontend/local_generation/decode_step.rs index 2f14e9c6..a0a43d0e 100644 --- a/crates/skippy-serving/src/frontend/local_generation/decode_step.rs +++ b/crates/skippy-serving/src/frontend/local_generation/decode_step.rs @@ -100,6 +100,12 @@ impl StageOpenAiBackend { ) }; state.current = predicted; + if let Some(dflash) = state.dflash.as_mut() { + dflash.finish_serial_compute( + self.generation_limit.generation_load(), + token_runtime_lock_hold_ms * 1000.0 / token_batch_size.max(1) as f64, + ); + } if native_mtp_draft .as_ref() .is_some_and(|draft: &NativeMtpDraft| { diff --git a/crates/skippy-serving/src/frontend/local_generation/dflash_block_size.rs b/crates/skippy-serving/src/frontend/local_generation/dflash_block_size.rs index 7d68855d..cb8d4345 100644 --- a/crates/skippy-serving/src/frontend/local_generation/dflash_block_size.rs +++ b/crates/skippy-serving/src/frontend/local_generation/dflash_block_size.rs @@ -5,9 +5,10 @@ //! where rows are expensive or drafts miss. This picks, per window, the length //! that maximises expected committed tokens per unit of measured time. //! -//! Cost is learned per draft model and shared by every request on it, because -//! it is a property of the machine. Acceptance is learned per request, seeded -//! from the shared estimate, because it is a property of the text. +//! Cost is learned per draft model and active lane count, so concurrent +//! requests do not overwrite the lone-stream baseline. Single-stream acceptance +//! is learned per request. Concurrent shared submissions use aggregate acceptance +//! and a stable width so independent choices do not fragment verification. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -28,10 +29,13 @@ pub(super) const MIN_SERIAL_SAMPLES: f64 = 2.0; /// Weight, in windows, a request gives the shared acceptance it starts from, /// so its own text dominates within a few windows. const SEED_ACCEPTANCE_WEIGHT: f64 = 4.0; +/// Keep a concurrent cohort on one width long enough to share verification +/// and collect costs before selecting another width. +const ALIGNED_WINDOWS_PER_LANE: u64 = 8; /// Whether DFlash block lengths adapt instead of using the configured maximum. -/// On by default: on every machine measured, adaptive matched or beat the best -/// fixed length. `SKIPPY_DFLASH_ADAPTIVE=0` pins blocks at the maximum. +/// On by default; chooses widths from observed execution costs and acceptance. +/// `SKIPPY_DFLASH_ADAPTIVE=0` pins blocks at the maximum. pub(super) fn adaptive_enabled() -> bool { adaptive_enabled_by(std::env::var("SKIPPY_DFLASH_ADAPTIVE").ok().as_deref()) } @@ -227,26 +231,57 @@ pub(super) fn choose_block( pub(super) struct SharedBlockModel { pub(super) cost: BlockCost, pub(super) acceptance: Acceptance, + windows: u64, + choices: HashMap, } -fn registry() -> &'static Mutex> { - static REGISTRY: OnceLock>> = OnceLock::new(); +fn registry() -> &'static Mutex> { + static REGISTRY: OnceLock>> = OnceLock::new(); REGISTRY.get_or_init(Default::default) } /// The current shared estimates for a draft model. -pub(super) fn shared_model(draft_model_path: &Path) -> SharedBlockModel { +pub(super) fn shared_model(draft_model_path: &Path, lanes: usize) -> SharedBlockModel { registry() .lock() - .map(|models| models.get(draft_model_path).cloned().unwrap_or_default()) + .map(|models| { + models + .get(&(draft_model_path.to_path_buf(), lanes.max(1))) + .cloned() + .unwrap_or_default() + }) .unwrap_or_default() } +/// Concurrent lanes use aggregate acceptance and a stable decision rather +/// than independently selecting widths the verifier cannot batch together. +/// Cache by the caller's limit so a request tail cannot shorten its peers. +pub(super) fn aligned_block( + draft_model_path: &Path, + lanes: usize, + max_drafts: usize, +) -> Option { + let mut models = registry().lock().ok()?; + let model = models + .entry((draft_model_path.to_path_buf(), lanes.max(1))) + .or_default(); + let interval = (lanes.max(1) as u64).saturating_mul(ALIGNED_WINDOWS_PER_LANE); + let epoch = model.windows / interval; + if let Some(&(cached_epoch, choice)) = model.choices.get(&max_drafts) + && cached_epoch == epoch + { + return Some(choice); + } + let choice = choose_block(&model.cost, &model.acceptance, max_drafts, epoch); + model.choices.insert(max_drafts, (epoch, choice)); + Some(choice) +} + /// Folds one measured serial step into the shared estimates for a draft model. -pub(super) fn record_shared_serial(draft_model_path: &Path, micros: f64) { +pub(super) fn record_shared_serial(draft_model_path: &Path, lanes: usize, micros: f64) { if let Ok(mut models) = registry().lock() { models - .entry(draft_model_path.to_path_buf()) + .entry((draft_model_path.to_path_buf(), lanes.max(1))) .or_default() .cost .observe_serial(micros); @@ -256,6 +291,7 @@ pub(super) fn record_shared_serial(draft_model_path: &Path, micros: f64) { /// Folds one window into the shared estimates for a draft model. pub(super) fn record_shared( draft_model_path: &Path, + lanes: usize, verify_rows: usize, verify_micros: f64, draft_micros: f64, @@ -263,10 +299,16 @@ pub(super) fn record_shared( accepted: usize, ) { if let Ok(mut models) = registry().lock() { - let model = models.entry(draft_model_path.to_path_buf()).or_default(); + let model = models + .entry((draft_model_path.to_path_buf(), lanes.max(1))) + .or_default(); model.cost.observe_verify(verify_rows, verify_micros); model.cost.observe_draft(draft_micros); model.acceptance.observe(drafts, accepted); + model.windows = model.windows.saturating_add(1); + // A serial cohort must reconsider after its next probe, rather than + // waiting a full interval of sparse draft observations to resume. + model.choices.retain(|_, (_, choice)| *choice != 0); } } @@ -274,6 +316,65 @@ pub(super) fn record_shared( mod tests { use super::*; + #[test] + fn shared_costs_do_not_cross_lane_counts() { + let path = Path::new("/test/lane-isolation.gguf"); + record_shared_serial(path, 1, 100.0); + record_shared_serial(path, 1, 100.0); + record_shared_serial(path, 2, 400.0); + record_shared_serial(path, 2, 400.0); + assert_eq!(shared_model(path, 1).cost.serial_micros(), Some(100.0)); + assert_eq!(shared_model(path, 2).cost.serial_micros(), Some(400.0)); + assert_eq!(shared_model(path, 3).cost.serial_micros(), None); + } + + #[test] + fn concurrent_choices_stay_aligned_until_the_cohort_has_measured_a_width() { + let path = Path::new("/test/aligned-cohort.gguf"); + assert_eq!(aligned_block(path, 2, 6), Some(6)); + for _ in 0..15 { + record_shared(path, 2, 7, 20_000.0, 2_000.0, 6, 5); + assert_eq!(aligned_block(path, 2, 6), Some(6)); + } + record_shared(path, 2, 7, 20_000.0, 2_000.0, 6, 5); + // Only one row count was observed; the next whole cohort explores + // the shorter width so the fit can learn a slope. + assert_eq!(aligned_block(path, 2, 6), Some(3)); + for _ in 0..16 { + record_shared(path, 2, 4, 18_000.0, 2_000.0, 3, 3); + } + assert!(aligned_block(path, 2, 6).unwrap() > 0); + assert_eq!(aligned_block(path, 3, 6), Some(6)); + } + + #[test] + fn request_tails_do_not_replace_the_cohorts_full_width_decision() { + let path = Path::new("/test/aligned-tail.gguf"); + assert_eq!(aligned_block(path, 2, 2), Some(2)); + assert_eq!(aligned_block(path, 2, 6), Some(6)); + assert_eq!(aligned_block(path, 2, 0), Some(0)); + assert_eq!(aligned_block(path, 2, 6), Some(6)); + } + + #[test] + fn a_serial_cohort_reconsiders_after_a_successful_probe() { + let path = Path::new("/test/aligned-serial-probe.gguf"); + let mut models = registry().lock().unwrap(); + let mut model = SharedBlockModel { + cost: linear_cost(25_000.0, 4_000.0, 8_000.0), + acceptance: uniform_acceptance(0.0), + ..SharedBlockModel::default() + }; + model.cost.observe_serial(29_000.0); + model.cost.observe_serial(29_000.0); + models.insert((path.to_path_buf(), 2), model); + drop(models); + assert_eq!(aligned_block(path, 2, 6), Some(0)); + record_shared(path, 2, 7, 30_000.0, 3_000.0, 6, 6); + let models = registry().lock().unwrap(); + assert!(models[&(path.to_path_buf(), 2)].choices.is_empty()); + } + #[test] fn adaptive_is_on_unless_turned_off() { assert!(adaptive_enabled_by(None)); diff --git a/crates/skippy-serving/src/frontend/local_generation/dflash_decode.rs b/crates/skippy-serving/src/frontend/local_generation/dflash_decode.rs index 19ad50c5..2c24b4d3 100644 --- a/crates/skippy-serving/src/frontend/local_generation/dflash_decode.rs +++ b/crates/skippy-serving/src/frontend/local_generation/dflash_decode.rs @@ -16,8 +16,8 @@ use crate::frontend::speculative::InferenceSpeculativeStats; use crate::frontend::util::openai_backend_error; use super::dflash_block_size::{ - Acceptance, BlockCost, adaptive_enabled, choose_block, record_shared, record_shared_serial, - shared_model, + Acceptance, BlockCost, adaptive_enabled, aligned_block, choose_block, record_shared, + record_shared_serial, shared_model, }; use super::token_generation::DecodeState; @@ -59,6 +59,7 @@ pub(super) struct DFlashDecodeState { /// Per-request state for block lengths chosen from measured cost. pub(in crate::frontend) struct AdaptiveBlocks { draft_model_path: PathBuf, + load: (usize, u64), cost: BlockCost, acceptance: Acceptance, windows: u64, @@ -69,13 +70,19 @@ pub(in crate::frontend) struct AdaptiveBlocks { serial_started: Option, /// Measured costs chose serial decoding and the next probe is not due. paused: bool, + /// Shared submissions optimize aggregate execution cost. Queue residence + /// belongs to peer work and must not distort the fit against row count. + service_cost: bool, + /// Coordinate widths only when both draft and verification can be shared. + align_windows: bool, } impl AdaptiveBlocks { fn new(draft_model_path: PathBuf) -> Self { - let shared = shared_model(&draft_model_path); + let shared = shared_model(&draft_model_path, 1); Self { draft_model_path, + load: (1, 0), cost: shared.cost, acceptance: shared.acceptance.capped(), windows: 0, @@ -83,9 +90,37 @@ impl AdaptiveBlocks { probes: 0, serial_started: None, paused: false, + service_cost: false, + align_windows: false, } } + fn for_local(draft_model_path: PathBuf) -> Self { + if !crate::frontend::iteration_scheduler::shared_drafts::enabled() { + return Self::new(draft_model_path); + } + let mut key = draft_model_path.into_os_string(); + key.push("#shared-draft-service"); + let mut blocks = Self::new(PathBuf::from(key)); + blocks.service_cost = true; + blocks.align_windows = crate::frontend::iteration_scheduler::shared_verification::enabled(); + blocks + } + + /// Discard timings that straddle a load transition. Keep this request's + /// acceptance history, but learn execution costs separately per lane count. + fn update_load(&mut self, load: (usize, u64)) { + if self.load == load { + return; + } + self.serial_started = None; + self.load = load; + self.cost = shared_model(&self.draft_model_path, load.0).cost; + self.windows = 0; + self.serial_since_probe = 0; + self.paused = false; + } + /// Block lengths for stage 0 of a split DFlash target, or `None` when /// adaptive sizing is off. Costs there include the hops between stages, /// so they are learned apart from the same draft serving one node. @@ -97,12 +132,29 @@ impl AdaptiveBlocks { /// Times the serial step that ran since the previous call, if one did. pub(in crate::frontend) fn finish_serial_step(&mut self) { + if self.service_cost { + return; + } let Some(started) = self.serial_started.take() else { return; }; let micros = started.elapsed().as_secs_f64() * 1_000_000.0; self.cost.observe_serial(micros); - record_shared_serial(&self.draft_model_path, micros); + record_shared_serial(&self.draft_model_path, self.load.0, micros); + } + + pub(super) fn finish_serial_compute(&mut self, load: (usize, u64), micros: f64) { + if !self.service_cost { + return; + } + if self.load != load { + self.update_load(load); + return; + } + if self.serial_started.take().is_some() { + self.cost.observe_serial(micros); + record_shared_serial(&self.draft_model_path, self.load.0, micros); + } } /// Drafts for the next window, or 0 to decode this token serially. @@ -127,7 +179,12 @@ impl AdaptiveBlocks { if self.windows > 0 && !self.cost.serial_measured() { return 0; } - let chosen = choose_block(&self.cost, &self.acceptance, limit, self.windows); + let chosen = if self.align_windows && self.load.0 > 1 { + aligned_block(&self.draft_model_path, self.load.0, limit) + .unwrap_or_else(|| choose_block(&self.cost, &self.acceptance, limit, self.windows)) + } else { + choose_block(&self.cost, &self.acceptance, limit, self.windows) + }; if chosen > 0 { self.serial_since_probe = 0; return chosen; @@ -160,6 +217,7 @@ impl AdaptiveBlocks { self.acceptance.observe(drafts, accepted); record_shared( &self.draft_model_path, + self.load.0, verify_rows, verify_micros, draft_micros, @@ -217,6 +275,12 @@ impl DFlashBackoff { } impl DFlashDecodeState { + pub(super) fn finish_serial_compute(&mut self, load: (usize, u64), micros: f64) { + if let Some(adaptive) = &mut self.adaptive { + adaptive.finish_serial_compute(load, micros); + } + } + /// DFlash commits by token equality against rows the native verifier /// samples in causal order, stopping at the first mismatch, which keeps /// greedy and stochastic sampling exact. `speculation_admitted` excludes @@ -232,7 +296,7 @@ impl DFlashDecodeState { max_draft_tokens: dflash.max_draft_tokens.unwrap_or(usize::MAX), backoff: DFlashBackoff::default(), adaptive: adaptive_enabled() - .then(|| AdaptiveBlocks::new(dflash.draft_model_path.clone())), + .then(|| AdaptiveBlocks::for_local(dflash.draft_model_path.clone())), stats: InferenceSpeculativeStats::default(), }) } @@ -322,6 +386,7 @@ impl StageOpenAiBackend { return Ok(DFlashSpanProgress::NotUsed); }; if let Some(adaptive) = dflash.adaptive.as_mut() { + adaptive.update_load(self.generation_limit.generation_load()); adaptive.finish_serial_step(); } // The adaptive chooser already weighs misses against serial steps. @@ -337,16 +402,37 @@ impl StageOpenAiBackend { if limit == 0 { return Ok(DFlashSpanProgress::NotUsed); } + // Prefill leaves the final prompt token undecoded. + let base_position = request + .prompt_token_ids + .len() + .saturating_sub(1) + .checked_add(state.decoded_tokens) + .and_then(|position| u64::try_from(position).ok()) + .ok_or_else(|| InferenceError::backend("DFlash base position overflow"))?; let propose_started = Instant::now(); let owned_session_id = session_id.to_string(); let anchor = state.current; - let proposal = + let proposal = if crate::frontend::iteration_scheduler::shared_drafts::enabled() { + self.iteration_scheduler + .execute_draft_timed( + crate::runtime_state::draft_batch::RuntimeDraftRequest { + session_id: owned_session_id, + anchor, + max_tokens: limit, + base_position, + }, + request.cancellation, + )? + .value + } else { self.iteration_scheduler - .execute_runtime("dflash-propose", move |runtime| { + .execute_independent_draft(move |runtime| { runtime .dflash_propose(&owned_session_id, anchor, limit) .map_err(openai_backend_error) - })?; + })? + }; let draft_micros = propose_started.elapsed().as_secs_f64() * 1_000_000.0; if let Some(dflash) = state.dflash.as_mut() { dflash.stats.draft_propose_ms += draft_micros / 1_000.0; @@ -355,15 +441,6 @@ impl StageOpenAiBackend { return Ok(DFlashSpanProgress::NotUsed); }; - // Prefill leaves the final prompt token undecoded; see the linear - // proposal path for the shared position contract. - let base_position = request - .prompt_token_ids - .len() - .saturating_sub(1) - .checked_add(state.decoded_tokens) - .and_then(|position| u64::try_from(position).ok()) - .ok_or_else(|| InferenceError::backend("DFlash base position overflow"))?; let mut verify_inputs = Vec::with_capacity(proposal.tokens.len() + 1); verify_inputs.push(state.current); verify_inputs.extend_from_slice(&proposal.tokens); @@ -397,13 +474,30 @@ impl StageOpenAiBackend { ); dflash.backoff.record_window(accepted); if let Some(adaptive) = dflash.adaptive.as_mut() { - adaptive.record( - verify_inputs.len(), - (execution.verification_elapsed_us + execution.repair_elapsed_us) as f64, - draft_micros, - proposal.tokens.len(), - accepted, - ); + let load = self.generation_limit.generation_load(); + if adaptive.load == load { + let (verify_cost, draft_cost) = if adaptive.service_cost { + ( + execution.compute_share_us as f64, + proposal.proposal_compute_us as f64, + ) + } else { + ( + (execution.verification_elapsed_us + execution.repair_elapsed_us) + as f64, + draft_micros, + ) + }; + adaptive.record( + verify_inputs.len(), + verify_cost, + draft_cost, + proposal.tokens.len(), + accepted, + ); + } else { + adaptive.update_load(load); + } } } apply_committed_tokens(state, &execution)?; @@ -445,9 +539,86 @@ fn apply_committed_tokens( #[cfg(test)] mod tests { + #[test] + fn shared_service_costs_use_measured_compute_and_discard_load_transitions() { + let mut blocks = super::AdaptiveBlocks::new("/test/shared-service-costs.gguf".into()); + blocks.service_cost = true; + blocks.serial_started = Some(std::time::Instant::now()); + blocks.finish_serial_step(); + assert!( + blocks.serial_started.is_some(), + "wall time must not consume a service sample" + ); + blocks.finish_serial_compute((1, 0), 100.0); + assert!(blocks.serial_started.is_none()); + assert!(!blocks.cost.serial_measured()); + blocks.serial_started = Some(std::time::Instant::now()); + blocks.finish_serial_compute((1, 0), 100.0); + assert!(blocks.cost.serial_measured()); + blocks.serial_started = Some(std::time::Instant::now()); + blocks.finish_serial_compute((2, 1), 5000.0); + assert!(blocks.serial_started.is_none()); + assert!( + !blocks.cost.serial_measured(), + "a sample spanning a load change must not enter the new bucket" + ); + } + + #[test] + fn changing_load_discards_pending_serial_timing_and_reloads_costs() { + let path = std::path::PathBuf::from("/test/dflash-load-transition.gguf"); + let mut blocks = super::AdaptiveBlocks::new(path.clone()); + blocks.update_load((1, 1)); + blocks.record(3, 30_000.0, 1_000.0, 2, 2); + blocks.serial_started = Some(std::time::Instant::now()); + blocks.update_load((2, 2)); + assert!(blocks.serial_started.is_none()); + assert_eq!(blocks.windows, 0); + assert!(!blocks.cost.serial_measured()); + blocks.finish_serial_step(); + assert!(!super::shared_model(&path, 2).cost.serial_measured()); + // The count returning to one is still a new measurement interval. + blocks.serial_started = Some(std::time::Instant::now()); + blocks.update_load((1, 3)); + assert!(blocks.serial_started.is_none()); + } + use super::*; use crate::frontend::NativeMtpVerifyWindowDecision; + #[test] + fn concurrent_alignment_does_not_replace_single_lane_or_unshared_choices() { + let path = PathBuf::from("/test/concurrent-width-policy.gguf"); + let make = |accepted| { + let mut blocks = AdaptiveBlocks::new(path.clone()); + for rows in [3, 5, 7] { + blocks + .cost + .observe_verify(rows, 20_000.0 + rows as f64 * 1_000.0); + } + blocks.cost.observe_draft(2_000.0); + blocks.cost.observe_serial(30_000.0); + blocks.cost.observe_serial(30_000.0); + for _ in 0..20 { + blocks.acceptance.observe(6, accepted); + } + blocks + }; + let mut good = make(6); + let mut poor = make(0); + good.align_windows = true; + poor.align_windows = true; + assert_ne!(good.next_drafts(6), poor.next_drafts(6)); + good.load.0 = 2; + poor.load.0 = 2; + assert_eq!(good.next_drafts(6), poor.next_drafts(6)); + assert_eq!(poor.next_drafts(2), 2); + assert_eq!(good.next_drafts(6), 6); + good.align_windows = false; + poor.align_windows = false; + assert_ne!(good.next_drafts(6), poor.next_drafts(6)); + } + #[test] fn serial_choices_pause_drafting_until_a_probe_is_due() { let mut blocks = AdaptiveBlocks::new(PathBuf::from("/test/serial-pause-draft.gguf")); @@ -558,6 +729,7 @@ mod tests { repair_elapsed_us: 0, runtime_lock_wait_us: 0, runtime_lock_hold_us: 0, + compute_share_us: 0, runtime_lock_acquires: 1, } } diff --git a/crates/skippy-serving/src/frontend/local_generation/resident_prefill.rs b/crates/skippy-serving/src/frontend/local_generation/resident_prefill.rs index 50ea3ad5..05e47a59 100644 --- a/crates/skippy-serving/src/frontend/local_generation/resident_prefill.rs +++ b/crates/skippy-serving/src/frontend/local_generation/resident_prefill.rs @@ -43,9 +43,19 @@ impl StageOpenAiBackend { "deferred suffix prefill requires at least one token", )); } + let admitted_session = session_id.to_string(); + let batch_limit = self.iteration_scheduler.execute_runtime( + "prefill-batch-admission", + move |runtime| { + runtime + .admit_session_batch_size(&admitted_session) + .map_err(crate::frontend::util::openai_backend_error) + }, + )?; let chunk_tokens = usize::try_from(self.config.n_ubatch.unwrap_or(256)) .unwrap_or(MAX_NATIVE_ITERATION_TOKENS) - .clamp(1, MAX_NATIVE_ITERATION_TOKENS); + .clamp(1, MAX_NATIVE_ITERATION_TOKENS) + .min(batch_limit.max(1)); let sample_flags = suffix_chunk_sample_flags(suffix.len(), chunk_tokens, sample_last); let channel = self.iteration_scheduler.direct_iteration_channel(); let mut predicted = None; @@ -95,7 +105,7 @@ fn ensure_suffix_prefill_active( } if Instant::now() >= deadline { return Err(InferenceError::timeout( - "cache operation deadline exceeded during deferred suffix prefill", + "generation deadline exceeded during prompt prefill", )); } Ok(()) diff --git a/crates/skippy-serving/src/frontend/local_generation/tests.rs b/crates/skippy-serving/src/frontend/local_generation/tests.rs index 1a91f228..9188e039 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests.rs @@ -15,7 +15,7 @@ use crate::frontend::generation::{ use crate::frontend::iteration_scheduler::IterationScheduler; use crate::frontend::local_generation::{ include_undelivered_samples, linear_proposal_allowed, native_mtp_dispatch_counts_for_test, - post_decode_checkpoint_tokens, prompt_fits_single_prefill_sample, + post_decode_checkpoint_tokens, }; use crate::frontend::{ EmbeddedOpenAiRequestDefaults, GenerationAbort, GenerationCommit, GenerationReceipt, @@ -173,14 +173,6 @@ fn wait_for_receipts(sink: &RecordingReceiptSink, expected: usize) { panic!("timed out waiting for {expected} generation receipts"); } -#[test] -fn single_prefill_sample_requires_prompt_to_fit_session_batch() { - assert!(!prompt_fits_single_prefill_sample(0, 2048)); - assert!(!prompt_fits_single_prefill_sample(1, 2048)); - assert!(prompt_fits_single_prefill_sample(2048, 2048)); - assert!(!prompt_fits_single_prefill_sample(2049, 2048)); -} - #[test] fn local_generation_signal_window_uses_configured_value() { let config = StageConfig { diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs b/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs index 2f199fb2..9de872c8 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/cold_offload_concurrency.rs @@ -158,8 +158,6 @@ fn capture_large_owner( 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)) } @@ -183,12 +181,18 @@ fn offload_while_disk_is_paused( ) -> 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 mut runtime = backend.runtime.lock().unwrap(); + assert!(kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); + runtime.prefill("continuing-decode", &[21, 22, 23])?; + runtime.ensure_session_active("eviction")?; + } + proof.baseline_decode_ms = next_decode(backend, 24)?.as_secs_f64() * 1000.0; let scheduler = backend.iteration_scheduler.clone(); let worker_kv = kv.clone(); let (started_tx, started_rx) = mpsc::channel(); @@ -205,8 +209,8 @@ fn offload_while_disk_is_paused( }) })); 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. + // Enqueue while eviction owns the runtime. The owned payload is already + // with the paused writer, so neither cell release nor decode needs it. proof.concurrent_decode_wait_ms = next_decode(backend, 25)?.as_secs_f64() * 1000.0; proof.eviction_runtime_ms = paused .worker diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs b/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs index 4e6a73fd..83337cc5 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/durable_prefix.rs @@ -108,6 +108,65 @@ struct CheckpointPreferenceCase { descriptor: skippy_runtime::RuntimeKvPageDesc, } +#[test] +#[ignore = "requires SKIPPY_RECURRENT_CACHE_TEST_MODEL and _LAYERS; run explicitly with --ignored"] +fn native_exact_prefix_import_admits_capacity_first() -> Result<()> { + for expected_source in ["l3", "l2"] { + let root = tempfile::tempdir()?; + let CheckpointPreferenceCase { + backend, + tokens, + attention, + recurrent, + .. + } = checkpoint_preference_case(root.path())?; + let kv = backend.kv.as_ref().unwrap(); + let target = identity(&backend, &tokens); + if expected_source == "l2" { + let fill = kv + .l3 + .as_ref() + .unwrap() + .fill_longest(&target.namespace, &tokens, 64)? + .unwrap(); + assert!(kv.l2.as_ref().unwrap().promote( + &target.namespace, + &tokens, + &fill.manifest, + &fill.payload, + )); + } + + let mut runtime = backend.runtime.lock().unwrap(); + runtime.ensure_session_active("pressure")?; + let capacity = u64::from(runtime.kv_pool_tokens()); + let occupied = runtime.memory_used_cells("pressure")?; + let pressure_tokens = vec![9; usize::try_from(capacity - occupied)?]; + let unrelated = identity(&backend, &pressure_tokens); + runtime.prefill("pressure", &pressure_tokens)?; + kv.record_resident_prefix(&mut runtime, "pressure", &unrelated, &pressure_tokens)? + .unwrap(); + runtime.drop_session_timed("pressure")?; + runtime.ensure_session_active("target")?; + assert!(capacity - runtime.memory_used_cells("target")? < tokens.len() as u64); + + let restored = kv + .restore_exact_state(&mut runtime, "target", std::slice::from_ref(&target))? + .expect("exact restore should reclaim cells before importing"); + assert_eq!(restored.source, expected_source); + assert_eq!(restored.token_count, tokens.len()); + assert!(kv.probe_resident_prefix(&unrelated).is_none()); + assert_eq!( + runtime + .export_kv_page("target", 0, tokens.len() as u64)? + .payload, + attention + ); + assert_eq!(runtime.export_recurrent_state("target")?, recurrent); + } + Ok(()) +} + #[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<()> { @@ -205,6 +264,7 @@ fn checkpoint_preference_case(root: &Path) -> Result { kv.record_resident_prefix(&mut rt, "long-source", &long, &tokens)? .unwrap(); rt.drop_session_timed("long-source")?; + assert!(kv.capture_resident_prefix_for_l3(&mut rt, &long)?); rt.ensure_session_active("eviction")?; assert_eq!( kv.evict_resident_prefix_for_tokens(&mut rt, "eviction", u64::MAX)? @@ -277,7 +337,7 @@ fn capture_and_commit(root: &Path) -> Result { assert!(!attention.is_empty()); assert!(!recurrent.is_empty()); let record = kv - .record_resident_prefix(&mut runtime, "source", &stored, &tokens)? + .record_resident_prefix_for_idle_capture(&mut runtime, "source", &stored, &tokens)? .expect("native checkpoint captured"); assert!(record.stored); assert!(kv.probe_resident_prefix(&stored).is_some()); @@ -293,13 +353,15 @@ fn capture_and_commit(root: &Path) -> Result { .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) }; + backend + .iteration_scheduler + .execute_runtime("finish-source", |runtime| { + runtime + .drop_session_timed("source") + .map_err(crate::frontend::util::openai_backend_error) + })?; let l3 = kv.l3.as_ref().expect("persistent tier enabled"); let deadline = Instant::now() + Duration::from_secs(30); loop { @@ -313,6 +375,14 @@ fn capture_and_commit(root: &Path) -> Result { ); thread::sleep(Duration::from_millis(2)); } + { + let mut runtime = backend.runtime.lock().unwrap(); + runtime.ensure_session_active("eviction")?; + let evicted = + kv.evict_resident_prefix_for_tokens(&mut runtime, "eviction", u64::MAX)?; + assert_eq!(evicted.evicted_entries, 1); + assert_eq!(runtime.memory_used_cells("eviction")?, 0); + } PrefixReference { seed_process_id: std::process::id(), attention_sha256: digest(&attention), @@ -442,7 +512,9 @@ fn native_cold_offload_refusal_keeps_inference_usable() -> Result<()> { .map(|&token| runtime.decode("source", token)) .collect::>>()?; runtime.drop_session_timed("source")?; + assert!(kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); runtime.ensure_session_active("reuse")?; + assert!(!kv.capture_resident_prefix_for_l3(&mut runtime, &stored)?); assert_eq!( kv.evict_resident_prefix_for_tokens(&mut runtime, "reuse", u64::MAX)? .evicted_entries, diff --git a/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs b/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs index 84a704dc..61c43405 100644 --- a/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs +++ b/crates/skippy-serving/src/frontend/local_generation/tests/recurrent_fixture.rs @@ -114,6 +114,7 @@ pub(super) fn recurrent_test_backend_with_lanes( max_entries: 8, max_bytes: 0, l2_max_bytes: RECURRENT_TEST_CHECKPOINT_RAM_BYTES, + l1_checkpoint_max_bytes: std::num::NonZeroU64::new(RECURRENT_TEST_CHECKPOINT_RAM_BYTES), codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -277,8 +278,8 @@ fn loaded_runtime_admission_uses_aggregate_pool_across_frontends() -> Result<()> 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); + let first = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane, 0); + let second = GenerationTokenBudget::shared_for_runtime(&mut runtime, per_lane, 0); assert!(Arc::ptr_eq(&first, &second)); let _reservation = first .try_reserve(GenerationTokenBudgetRequest::new(per_lane + 1, 0))? diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation.rs index 6fb931e8..a682e561 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation.rs @@ -41,8 +41,8 @@ use std::collections::BTreeMap; use std::sync::Arc; use std::time::{Duration, Instant}; +use super::LocalGenerationReceiptFinalization; use super::receipt_lifecycle::begin_generation_receipt; -use super::{LocalGenerationReceiptFinalization, prompt_fits_single_prefill_sample}; use crate::frontend::generation_commit_batcher::GenerationCommitBatcher; mod exact_state_recording; @@ -576,6 +576,7 @@ impl StageOpenAiBackend { let stats = self.iteration_scheduler.generate( ScheduledGenerationRequest { id: session_id, + priority: request.ids.request_tier().priority(), prompt_tokens: request.prompt_token_ids, max_tokens: request.max_tokens, sampling: request.sampling.enabled.then_some(request.sampling), @@ -615,32 +616,6 @@ impl StageOpenAiBackend { )) } - fn can_sample_whole_prompt_in_prefill( - &self, - request: &LocalGeneration<'_>, - session_id: &str, - ) -> InferenceResult { - if request.max_tokens == 0 || request.prompt_token_ids.len() <= 1 || self.kv.is_some() { - return Ok(false); - } - let scheduler_session_id = session_id.to_string(); - let batch_size = self.iteration_scheduler.execute_runtime( - "feature-prefill-admission", - move |runtime| { - runtime - .ensure_session_active(&scheduler_session_id) - .map_err(openai_backend_error)?; - runtime - .admit_session_batch_size(&scheduler_session_id) - .map_err(openai_backend_error) - }, - )?; - Ok(prompt_fits_single_prefill_sample( - request.prompt_token_ids.len(), - batch_size, - )) - } - fn prefill_prompt( &self, request: &LocalGeneration<'_>, @@ -660,7 +635,9 @@ impl StageOpenAiBackend { request.sampling.enabled.then_some(request.sampling), )?; } - if self.can_sample_whole_prompt_in_prefill(request, session_id)? { + // Uncached and cooperative cached requests both sample the final + // prompt token in the last prefill chunk, even above n_batch. + if self.kv.is_none() && request.max_tokens > 0 && request.prompt_token_ids.len() > 1 { let chat_sampling_configured = if let Some(metadata) = request.chat_sampling_metadata { self.configure_chat_sampling( session_id, @@ -673,7 +650,7 @@ impl StageOpenAiBackend { false }; return Ok(PromptPrefillResult { - prompt_prefill_sample: self.prefill_whole_prompt( + prompt_prefill_sample: self.prefill_uncached_prompt( request, session_id, cache_stats, @@ -716,71 +693,6 @@ impl StageOpenAiBackend { }) } - fn prefill_whole_prompt( - &self, - request: &LocalGeneration<'_>, - session_id: &str, - 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| { - Ok(runtime.session_stats()) - })?; - let outcome = self.iteration_scheduler.execute_iteration( - session_id, - request.prompt_token_ids, - &[], - request.sampling.enabled.then_some(request.sampling), - true, - skippy_runtime::IterationBatchPhase::Prefill, - )?; - let prompt_prefill_sample = Some(outcome.predicted); - cache_stats.suffix_prefill_tokens = saturating_u32(request.prompt_token_ids.len()); - let runtime_sessions_after = self - .iteration_scheduler - .execute_runtime("feature-prefill-stats-after", |runtime| { - Ok(runtime.session_stats()) - })?; - let mut attrs = self.openai_attrs(request.ids); - attrs.insert( - "llama_stage.prefill_token_count".to_string(), - json!(request.prompt_token_ids.len()), - ); - attrs.insert("llama_stage.prefill_chunk_count".to_string(), json!(1)); - attrs.insert("skippy.kv.restored_prefill".to_string(), json!(false)); - attrs.insert("skippy.kv.restored_prefill_tokens".to_string(), json!(0)); - attrs.insert( - "skippy.kv.prefill_suffix_tokens".to_string(), - json!(request.prompt_token_ids.len()), - ); - attrs.insert("skippy.kv.recorded_pages".to_string(), json!(0)); - attrs.insert( - "llama_stage.runtime_lock_wait_ms".to_string(), - json!(outcome.runtime_lock_wait_ms), - ); - attrs.insert( - "llama_stage.runtime_lock_hold_ms".to_string(), - json!(outcome.runtime_lock_hold_ms), - ); - attrs.insert("llama_stage.runtime_lock_acquires".to_string(), json!(1)); - Self::insert_runtime_session_stats( - &mut attrs, - "llama_stage.runtime_sessions_before", - &runtime_sessions_before, - ); - Self::insert_runtime_session_stats( - &mut attrs, - "llama_stage.runtime_sessions_after", - &runtime_sessions_after, - ); - cache_stats.prompt_ms = prefill_timer.elapsed_ms(); - self.emit_openai_phase("stage.openai_prefill", prefill_timer, attrs); - Ok(prompt_prefill_sample) - } - fn configure_chat_sampling( &self, session_id: &str, @@ -967,6 +879,7 @@ impl StageOpenAiBackend { let stats = self.iteration_scheduler.resume_generation( ScheduledResumeRequest { id: session_id, + priority: request.ids.request_tier().priority(), prompt_tokens: request.prompt_token_ids, generated_tokens: &initial_generated_tokens, max_tokens: request.max_tokens, diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs index f2e832bd..d760457a 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/cache_prefill.rs @@ -143,10 +143,12 @@ impl StageOpenAiBackend { { 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 prepared_restore = self.kv.as_ref().map(|kv| { + kv.prepare_standalone_restore(&lookup_identities, cache_operation_deadline, |tokens| { + self.generation_service_estimator + .estimated_prefill_ms(tokens) + }) + }); let outcome = self.iteration_scheduler.execute_cache_aware_runtime_timed( "feature-kv-restore-prefill-record", crate::frontend::iteration_scheduler::cache_runtime::CacheAwareRuntimeRequest { @@ -154,7 +156,7 @@ impl StageOpenAiBackend { deadline: cache_operation_deadline, cancellation: request.cancellation, prompt_tokens: Arc::clone(&prefill_tokens), - priority: 0, + priority: request.ids.request_tier().priority(), scheduling: cache_scheduling, refresh_affinity: refresh_cache_affinity, }, diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs index 8f708ebf..cf472cc5 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/exact_state_recording.rs @@ -264,6 +264,12 @@ impl StageOpenAiBackend { Some(&identity.namespace), ); } + if recorded && write_through_l3 && kv.l3.is_some() { + // A shared grid boundary is also a fallback. It can be + // offered before this request's exact chat prompt arrives. + let preferred = decision_prefix == "chat_prefix_checkpoint"; + kv.offer_prefix_capture(runtime, session_id, identity, preferred); + } return recorded; } #[cfg(test)] diff --git a/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs b/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs index cf547833..f8095fbc 100644 --- a/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs +++ b/crates/skippy-serving/src/frontend/local_generation/token_generation/kv_restore.rs @@ -293,9 +293,13 @@ impl StageOpenAiBackend { .emit("stage.openai_kv_record_decision", attrs); } for identity in kv.record_identities(&self.config, &base, 0, prefill_tokens) { - if let Ok(Some(record)) = - kv.record_resident_prefix(runtime, session_id, &identity, prefill_tokens) - { + if let Ok(Some(record)) = kv.record_resident_prefix_with_capture( + runtime, + session_id, + &identity, + prefill_tokens, + true, + ) { resident_recorded_pages = resident_recorded_pages.saturating_add(1); let mut attrs = self.openai_attrs(ids); attrs.insert( diff --git a/crates/skippy-serving/src/frontend/local_generation/uncached_prefill.rs b/crates/skippy-serving/src/frontend/local_generation/uncached_prefill.rs new file mode 100644 index 00000000..997305c9 --- /dev/null +++ b/crates/skippy-serving/src/frontend/local_generation/uncached_prefill.rs @@ -0,0 +1,84 @@ +//! Use the same chunk and sampling boundaries for cold and cache-aware prefill. +use super::cache_deadline::cache_operation_deadline; +use crate::frontend::generation::{ + GenerationCacheStats, LocalGeneration, PhaseTimer, StageOpenAiBackend, +}; +use crate::frontend::util::saturating_u32; +use serde_json::json; +use skippy_inference_api::InferenceResult; + +impl StageOpenAiBackend { + pub(super) fn prefill_uncached_prompt( + &self, + request: &LocalGeneration<'_>, + session_id: &str, + 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| { + Ok(runtime.session_stats()) + })?; + let outcome = self.prefill_suffix( + session_id, + request.prompt_token_ids, + request.sampling.enabled.then_some(request.sampling), + true, + cache_operation_deadline( + self.generation_admission_timeout, + request.prompt_token_ids.len(), + ), + request.cancellation, + )?; + let prompt_prefill_sample = outcome.predicted; + cache_stats.suffix_prefill_tokens = saturating_u32(request.prompt_token_ids.len()); + let runtime_sessions_after = self + .iteration_scheduler + .execute_runtime("feature-prefill-stats-after", |runtime| { + Ok(runtime.session_stats()) + })?; + let mut attrs = self.openai_attrs(request.ids); + attrs.insert( + "llama_stage.prefill_token_count".to_string(), + json!(request.prompt_token_ids.len()), + ); + attrs.insert( + "llama_stage.prefill_chunk_count".to_string(), + json!(outcome.chunk_count), + ); + attrs.insert("skippy.kv.restored_prefill".to_string(), json!(false)); + attrs.insert("skippy.kv.restored_prefill_tokens".to_string(), json!(0)); + attrs.insert( + "skippy.kv.prefill_suffix_tokens".to_string(), + json!(request.prompt_token_ids.len()), + ); + attrs.insert("skippy.kv.recorded_pages".to_string(), json!(0)); + attrs.insert( + "llama_stage.runtime_lock_wait_ms".to_string(), + json!(outcome.runtime_lock_wait_ms), + ); + attrs.insert( + "llama_stage.runtime_lock_hold_ms".to_string(), + json!(outcome.runtime_lock_hold_ms), + ); + attrs.insert( + "llama_stage.runtime_lock_acquires".to_string(), + json!(outcome.chunk_count), + ); + Self::insert_runtime_session_stats( + &mut attrs, + "llama_stage.runtime_sessions_before", + &runtime_sessions_before, + ); + Self::insert_runtime_session_stats( + &mut attrs, + "llama_stage.runtime_sessions_after", + &runtime_sessions_after, + ); + cache_stats.prompt_ms = prefill_timer.elapsed_ms(); + self.emit_openai_phase("stage.openai_prefill", prefill_timer, attrs); + Ok(prompt_prefill_sample) + } +} diff --git a/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs b/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs index 4ced09a5..a2b93b89 100644 --- a/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs +++ b/crates/skippy-serving/src/frontend/native_mtp/verify_window.rs @@ -140,6 +140,7 @@ impl StageOpenAiBackend { tokens: &verify_inputs, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; message.state.set_split_dflash(request.split_dflash()); message diff --git a/crates/skippy-serving/src/frontend/prefix_cache.rs b/crates/skippy-serving/src/frontend/prefix_cache.rs index 7ab4b098..04b03bb8 100644 --- a/crates/skippy-serving/src/frontend/prefix_cache.rs +++ b/crates/skippy-serving/src/frontend/prefix_cache.rs @@ -35,7 +35,6 @@ use skippy_protocol::SCHEMA_VERSION; use skippy_protocol::StageConfig; use skippy_protocol::binary::StageReplyStats; use skippy_protocol::binary::StageSamplingConfig as WireSamplingConfig; -use skippy_protocol::binary::StageWireMessage; use skippy_protocol::binary::WireMessageKind; use skippy_protocol::binary::WireReplyKind; use skippy_protocol::binary::recv_reply; @@ -441,7 +440,7 @@ impl StageOpenAiBackend { .unwrap_or(usize::MAX) .min(scheduler_token_ids.len()); scheduler_kv - .record_resident_prefix( + .record_resident_prefix_for_idle_capture( runtime, &scheduler_session_id, identity, @@ -554,7 +553,7 @@ impl StageOpenAiBackend { .unwrap_or(usize::MAX) .min(scheduler_token_ids.len()); scheduler_kv - .record_resident_prefix( + .record_resident_prefix_for_idle_capture( runtime, &scheduler_session_id, identity, @@ -1001,6 +1000,7 @@ impl StageOpenAiBackend { current, sampling: wire_sampling.clone(), native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; let has_downstream = request.config.downstream.is_some(); let scheduler_kv = Arc::clone(kv); @@ -1086,6 +1086,7 @@ impl StageOpenAiBackend { sampling: wire_sampling, chat_sampling_metadata: request.chat_sampling_metadata, native_mtp_draft_tokens: request.native_mtp_draft_tokens(), + request_class: request.ids.request_class(), })?; let forwarded = forwarded_stage_message_timed( request.config, @@ -1194,8 +1195,11 @@ impl StageOpenAiBackend { .map_err(openai_backend_error) }, ); - let stop = - StageWireMessage::stop_with_identity(request.ids.request_id, request.ids.session_id); + let stop = crate::frontend::wire_messages::stop_message( + request.ids.request_id, + request.ids.session_id, + request.ids.request_class(), + ); if write_stage_message_conditioned( &mut *downstream, &stop, @@ -1302,6 +1306,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -1392,6 +1397,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs b/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs index 8072e3fd..20479898 100644 --- a/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs +++ b/crates/skippy-serving/src/frontend/prefix_cache/split_restore.rs @@ -55,6 +55,7 @@ impl StageOpenAiBackend { &prefill_tokens[..restored_tokens], request.ids.request_id, request.ids.session_id, + request.ids.request_class(), )?; write_stage_message_conditioned( &mut *downstream, diff --git a/crates/skippy-serving/src/frontend/prompting.rs b/crates/skippy-serving/src/frontend/prompting.rs index 567c3d60..80072a83 100644 --- a/crates/skippy-serving/src/frontend/prompting.rs +++ b/crates/skippy-serving/src/frontend/prompting.rs @@ -13,6 +13,7 @@ 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 sha2::{Digest, Sha256}; use skippy_inference_api::ChatMessage; use skippy_inference_api::GenerationHookSignals; use skippy_inference_api::InferenceError; @@ -38,6 +39,19 @@ struct RenderedChatPrompt { metadata_json: String, } +fn cache_template_digest(options: &ChatTemplateOptions) -> Option<[u8; 32]> { + let template = options.chat_template.as_deref(); + if template.is_none() && options.use_jinja { + return None; + } + let mut hash = Sha256::new(); + hash.update([u8::from(options.use_jinja), u8::from(template.is_some())]); + if let Some(template) = template { + hash.update(template.as_bytes()); + } + Some(hash.finalize().into()) +} + impl StageOpenAiBackend { /// Offload [`Self::prepare_chat_prompt`] to a blocking thread. /// @@ -113,6 +127,7 @@ impl StageOpenAiBackend { // Native path: render with tools and use the template's own metadata. let native = self.render_chat_prompt(request, &options, &marker, None, true)?; + let cache_template_digest = cache_template_digest(&options); let shape = crate::generation_stats::RequestShape::of_chat(request, tool_calls_requested(request)); @@ -144,6 +159,7 @@ impl StageOpenAiBackend { text: emulated.prompt, media: emulated.media, chat_parse_metadata: Some(emulated.metadata_json), + cache_template_digest, recurrent_cache_prefix_text, recurrent_system_prefix_text, shape, @@ -163,6 +179,7 @@ impl StageOpenAiBackend { text: native.prompt, media: native.media, chat_parse_metadata: Some(native.metadata_json), + cache_template_digest, recurrent_cache_prefix_text, recurrent_system_prefix_text, shape, @@ -746,6 +763,28 @@ mod continuation_tests { .to_string() } + #[test] + fn default_renderer_keeps_the_legacy_namespace_and_explicit_renderers_differ() { + let mut options = ChatTemplateOptions { + use_jinja: true, + ..Default::default() + }; + assert_eq!(cache_template_digest(&options), None); + options.chat_template = Some("{{ messages[0].content }}".into()); + let first = cache_template_digest(&options); + assert!(first.is_some()); + assert_eq!(first, cache_template_digest(&options.clone())); + options.use_jinja = false; + assert_ne!(first, cache_template_digest(&options)); + options.use_jinja = true; + options + .chat_template + .as_mut() + .unwrap() + .push_str("{# equivalent #}"); + assert_ne!(first, cache_template_digest(&options)); + } + #[test] fn an_open_reasoning_block_in_the_generation_prompt_is_detected() { assert!(generation_prompt_opens_reasoning(Some(&metadata( diff --git a/crates/skippy-serving/src/frontend/request.rs b/crates/skippy-serving/src/frontend/request.rs index d8e020d5..f5247a81 100644 --- a/crates/skippy-serving/src/frontend/request.rs +++ b/crates/skippy-serving/src/frontend/request.rs @@ -1,3 +1,5 @@ +mod structured_output; + use crate::frontend::EmbeddedOpenAiRequestDefaults; use crate::frontend::EmbeddedReasoningBudget; use crate::frontend::EmbeddedReasoningEnabled; @@ -740,7 +742,8 @@ fn apply_chat_only_request_defaults( request.extra.insert(name.to_string(), value); } } - if extra_value_is_omitted(&request.extra, "grammar") + if request.response_format.as_ref().is_none_or(Value::is_null) + && extra_value_is_omitted(&request.extra, "grammar") && extra_value_is_omitted(&request.extra, "json_schema") && let Some((name, value)) = [ ("grammar", defaults.grammar.clone()), @@ -1099,6 +1102,7 @@ pub(super) fn chat_template_options( request.reasoning_effort, &request.extra, )?; + let (grammar, json_schema) = structured_output::template_constraints(request)?; Ok(ChatTemplateOptions { add_assistant: request .extra @@ -1115,8 +1119,8 @@ pub(super) fn chat_template_options( .map_err(|error| InferenceError::invalid_request(error.to_string()))?, chat_template: chat_template(request, defaults)?, use_jinja: optional_bool_extra(&request.extra, "jinja")?.unwrap_or(true), - grammar: structured_output_string(request, "grammar")?, - json_schema: structured_output_json(request, "json_schema")?, + grammar, + json_schema, skip_chat_parsing: optional_bool_extra(&request.extra, "skip_chat_parsing")? .unwrap_or(false), }) @@ -1382,46 +1386,6 @@ fn optional_bool_extra( .transpose() } -fn structured_output_string( - request: &GenerationRequest, - name: &str, -) -> InferenceResult> { - let value = bounded_optional_string_extra(&request.extra, name)?; - if value.is_some() - && request - .extra - .get("json_schema") - .is_some_and(|value| !value.is_null()) - { - return Err(InferenceError::invalid_request( - "grammar and json_schema cannot both be set", - )); - } - if let Some(grammar) = value.as_deref() { - crate::grammar_bounds::check_grammar(grammar).map_err(InferenceError::invalid_request)?; - } - Ok(value) -} - -fn structured_output_json( - request: &GenerationRequest, - name: &str, -) -> InferenceResult> { - request - .extra - .get(name) - .filter(|value| !value.is_null()) - .map(|value| { - if !value.is_object() { - return Err(InferenceError::invalid_request( - "json_schema must be an object", - )); - } - serialize_bounded_native_parser_json("json_schema", value) - }) - .transpose() -} - fn serialize_bounded_native_parser_json( name: &str, value: &impl serde::Serialize, diff --git a/crates/skippy-serving/src/frontend/request/structured_output.rs b/crates/skippy-serving/src/frontend/request/structured_output.rs new file mode 100644 index 00000000..d214e126 --- /dev/null +++ b/crates/skippy-serving/src/frontend/request/structured_output.rs @@ -0,0 +1,76 @@ +//! Translate public response formats into the native sampling constraints. +use super::{ + GenerationRequest, InferenceError, InferenceResult, Value, bounded_optional_string_extra, + serialize_bounded_native_parser_json, +}; + +pub(super) fn template_constraints( + request: &GenerationRequest, +) -> InferenceResult<(Option, Option)> { + let grammar = bounded_optional_string_extra(&request.extra, "grammar")?; + let native_schema = request.extra.get("json_schema").filter(|v| !v.is_null()); + let public_schema = response_schema(request.response_format.as_ref())?; + if public_schema.is_some() && (grammar.is_some() || native_schema.is_some()) { + return Err(InferenceError::invalid_request( + "response_format cannot be combined with grammar or json_schema", + )); + } + let schema = public_schema.as_ref().or(native_schema); + if grammar.is_some() && schema.is_some() { + return Err(InferenceError::invalid_request( + "grammar and json_schema cannot both be set", + )); + } + if let Some(grammar) = grammar.as_deref() { + crate::grammar_bounds::check_grammar(grammar).map_err(InferenceError::invalid_request)?; + } + let schema = schema + .map(|schema| { + if !schema.is_object() { + return Err(InferenceError::invalid_request( + "json_schema must be an object", + )); + } + serialize_bounded_native_parser_json("json_schema", schema) + }) + .transpose()?; + Ok((grammar, schema)) +} + +fn response_schema(format: Option<&Value>) -> InferenceResult> { + let Some(format) = format.filter(|v| !v.is_null()) else { + return Ok(None); + }; + match format.get("type").and_then(Value::as_str) { + Some("text") => Ok(None), + Some("json_object") => Ok(Some(serde_json::json!({"type":"object"}))), + Some("json_schema") => { + let specification = format + .get("json_schema") + .and_then(Value::as_object) + .ok_or_else(|| { + InferenceError::invalid_request("response_format.json_schema must be an object") + })?; + if specification + .get("strict") + .is_some_and(|v| !v.is_boolean() && !v.is_null()) + { + return Err(InferenceError::invalid_request( + "response_format.json_schema.strict must be a boolean", + )); + } + let schema = specification + .get("schema") + .filter(|v| v.is_object()) + .ok_or_else(|| { + InferenceError::invalid_request( + "response_format.json_schema.schema must be an object", + ) + })?; + Ok(Some(schema.clone())) + } + _ => Err(InferenceError::invalid_request( + "response_format.type must be text, json_object, or json_schema", + )), + } +} diff --git a/crates/skippy-serving/src/frontend/system_one/causal.rs b/crates/skippy-serving/src/frontend/system_one/causal.rs index d600bacd..cf92cb5e 100644 --- a/crates/skippy-serving/src/frontend/system_one/causal.rs +++ b/crates/skippy-serving/src/frontend/system_one/causal.rs @@ -69,6 +69,7 @@ impl StageOpenAiBackend { pub(in crate::frontend) async fn serve_system_one( &self, request: SystemOneRequest, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult { super::validate_request_fields(&request, &self.model_id)?; let decision = super::decision_request(&request)?; @@ -102,7 +103,7 @@ impl StageOpenAiBackend { }; validate_context(&plan, self.ctx_size)?; let guard = CancelOnDrop(CancellationToken::new()); - let preparation = self.warm_decision_prefixes(&plan, &guard.0).await?; + let preparation = self.warm_decision_prefixes(&plan, &guard.0, class).await?; let jobs = decision_jobs(&plan); let mut executor = self.clone(); if !preparation.reuse_cache { @@ -110,7 +111,7 @@ impl StageOpenAiBackend { // This affects only this request, not the shared backend or other users. executor.kv = None; } - let results = executor.run_readout_jobs(jobs, &guard.0).await?; + let results = executor.run_readout_jobs(jobs, &guard.0, class).await?; decision_response(request, &plan, results, preparation.usage) } @@ -119,10 +120,11 @@ impl StageOpenAiBackend { &self, jobs: Vec, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult> { let width = self.generation_limit.current_limit().clamp(1, 64); let mut running = stream::iter(jobs.into_iter().map(|job| async move { - let result = self.run_readout_job(job.clone(), cancellation).await; + let result = self.run_readout_job(job.clone(), cancellation, class).await; (job, result) })) .buffer_unordered(width); @@ -145,6 +147,7 @@ impl StageOpenAiBackend { &self, job: ReadoutJob, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> Result { job.validate()?; let ids = InferenceGenerationIds::new_with_trust( @@ -152,7 +155,8 @@ impl StageOpenAiBackend { None, false, None, - ); + ) + .with_request_class(class); let continuation = job.candidates.iter().map(Vec::len).max().unwrap_or(0); let work = GenerationAdmissionWork::new(job.prompt.len() + continuation.saturating_sub(1), 0); diff --git a/crates/skippy-serving/src/frontend/system_one/causal/cache.rs b/crates/skippy-serving/src/frontend/system_one/causal/cache.rs index 784960ef..e8a79277 100644 --- a/crates/skippy-serving/src/frontend/system_one/causal/cache.rs +++ b/crates/skippy-serving/src/frontend/system_one/causal/cache.rs @@ -78,6 +78,7 @@ impl DecisionSequence<'_> { tokens, self.ids.request_id, self.ids.session_id, + self.ids.request_class(), )?; write_stage_message_conditioned(&mut lane.stream, &message, *downstream_wire_condition) .map_err(openai_io_error)?; @@ -93,9 +94,10 @@ impl DecisionSequence<'_> { if !restored { // Reset every stage, including recurrent state that cannot safely // be truncated after a partial chain restore. - let stop = skippy_protocol::binary::StageWireMessage::stop_with_identity( + let stop = crate::frontend::wire_messages::stop_message( self.ids.request_id, self.ids.session_id, + self.ids.request_class(), ); write_stage_message_conditioned(&mut lane.stream, &stop, *downstream_wire_condition) .map_err(openai_io_error)?; diff --git a/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs b/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs index 28027bbc..cf9db5af 100644 --- a/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs +++ b/crates/skippy-serving/src/frontend/system_one/causal/preparation.rs @@ -14,6 +14,7 @@ impl StageOpenAiBackend { &self, plan: &DecisionPlan, cancellation: &CancellationToken, + class: skippy_inference_api::InferenceRequestClass, ) -> InferenceResult { let mut usage = DecisionReadoutUsage::default(); if !self @@ -28,7 +29,9 @@ impl StageOpenAiBackend { } if plan.questions.len() > 1 && plan.shared_prefix_tokens > 0 { let tokens = plan.questions[0].prompt[..plan.shared_prefix_tokens].to_vec(); - let result = self.run_readout_job(warmup_job(tokens), cancellation).await; + let result = self + .run_readout_job(warmup_job(tokens), cancellation, class) + .await; if !accumulate_preparation(stream::iter([result]), cancellation, &mut usage).await? { return Ok(PreparedPrefixes { usage, @@ -46,7 +49,7 @@ impl StageOpenAiBackend { let results = stream::iter( prompts .into_iter() - .map(|job| self.run_readout_job(job, cancellation)), + .map(|job| self.run_readout_job(job, cancellation, class)), ) .buffer_unordered(width); let reuse_cache = accumulate_preparation(results, cancellation, &mut usage).await?; diff --git a/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs b/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs index 03968ab1..775ab351 100644 --- a/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs +++ b/crates/skippy-serving/src/frontend/system_one/causal/sequence.rs @@ -8,9 +8,7 @@ use crate::frontend::generation::{ use crate::frontend::iteration_scheduler::readout::ReadoutIteration; use crate::frontend::util::openai_io_error; use crate::frontend::wire_messages::{OpenAiPrefillChunk, embedded_prefill_message}; -use skippy_protocol::binary::{ - StageStateHeader, StageWireMessage, WireMessageKind, WireReplyKind, recv_reply, -}; +use skippy_protocol::binary::{StageStateHeader, WireMessageKind, WireReplyKind, recv_reply}; use std::net::Shutdown; pub(super) struct DecisionSequence<'a> { @@ -184,11 +182,16 @@ impl<'a> DecisionSequence<'a> { tokens, request_id: self.ids.request_id, session_id: self.ids.session_id, + request_class: self.ids.request_class(), })?; message.kind = WireMessageKind::PrefillReadout; message.state = StageStateHeader::new(message.kind); message.state.prompt_token_count = i32::try_from(self.prompt_tokens) .map_err(|_| InferenceError::invalid_request("decision prompt exceeds wire bounds"))?; + crate::stage_request_class::stamp_request_class( + &mut message.state, + self.ids.request_class(), + ); message.readout_tokens = selected.to_vec(); let forwarded = forwarded_stage_message(config, &message, activation, *activation_width) .map_err(openai_backend_error)?; @@ -210,8 +213,11 @@ impl<'a> DecisionSequence<'a> { /// Close the sequence's downstream connection and remove local session state. fn close(&mut self) -> InferenceResult<()> { if let Some((pool, mut lane)) = self.lane.take() { - let stop = - StageWireMessage::stop_with_identity(self.ids.request_id, self.ids.session_id); + let stop = crate::frontend::wire_messages::stop_message( + self.ids.request_id, + self.ids.session_id, + self.ids.request_class(), + ); skippy_protocol::binary::write_stage_message(&mut lane.stream, &stop) .map_err(openai_io_error)?; let reply = recv_reply(&mut lane.stream).map_err(openai_io_error)?; diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification.rs new file mode 100644 index 00000000..3ef734c9 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification.rs @@ -0,0 +1,494 @@ +use super::{StageConfig, StageKvCacheMode, support::local_openai_backend}; +use crate::{ + frontend::{ + generation::{ + GenerationTokenLimit, InferenceCacheHints, StageOpenAiBackend, generation_ids, + }, + generation_receipt::{ + GenerationLifecycleIngress, GenerationLifecycleObservation, GenerationReceipt, + GenerationReceiptConfig, GenerationStart, + }, + request::{chat_sampling_config, chat_template_options}, + }, + kv_integration::KvStageIntegration, + telemetry::{CapturedEvent, Telemetry, TelemetryLevel}, +}; +use anyhow::{Context, Result, ensure}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use skippy_cache::L3CacheManager; +use skippy_inference_api::{ + InferenceRequestContext, chat::ChatCompletionRequest, generation::GenerationRequest, +}; +use std::{ + env, fs, + io::{BufRead, BufReader, Write}, + path::{Path, PathBuf}, + sync::{Arc, mpsc}, + time::Duration, +}; + +mod answer; +mod backend; +mod conversation; +mod evidence; +mod fixture; +mod ownership; +mod reference; +mod smoke; +mod structured; +mod template; +mod tiers; + +use backend::Backend; +use evidence::{CacheObservation, Candidate, Generation, Report, Status, TokenScore}; +use fixture::{Family, Fixture}; + +const LLAMA_PIN: &str = include_str!("../../../../../llama_cpp/upstream.txt"); +const MAX_TOKENS: u32 = 32; +const EXPECTED_CODE: i64 = 1729; +const TOP_K: u32 = 5; +const CONTEXT_TOKENS: u32 = 8192; +const BATCH_TOKENS: u32 = 512; +const TIMEOUT: Duration = Duration::from_secs(120); + +#[test] +#[ignore = "requires retained JSON evidence from a real hardware qualification"] +fn verify_report() -> Result<()> { + let path = required_path("SKIPPY_CACHE_QUAL_VERIFY_REPORT")?; + let mut report: Report = serde_json::from_reader(BufReader::new(fs::File::open(path)?))?; + ensure!( + report.backend == Backend::selected()?, + "report backend does not match the requested qualification profile" + ); + evidence::verify_saved(&mut report) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires an admitted model and actual qualification hardware"] +async fn cross_tier() -> Result<()> { + let directory = required_path("SKIPPY_CACHE_QUAL_REPORT_DIR")?; + fs::create_dir(&directory) + .with_context(|| format!("create fresh report directory {}", directory.display()))?; + + let family = match env::var("SKIPPY_CACHE_QUAL_FAMILY") { + Ok(value) => Family::parse(&value)?, + Err(env::VarError::NotPresent) => Family::DenseAttention, + Err(error) => return Err(error.into()), + }; + let mut report = Report::new(Backend::selected()?, Fixture::load(family)?); + let result = qualify(&directory, &mut report).await; + match &result { + Ok(()) => report.status = Status::Pass, + Err(error) => report.error = Some(format!("{error:#}")), + } + let report_path = directory.join("result.json"); + let mut file = fs::File::create(&report_path)?; + serde_json::to_writer_pretty(&mut file, &report)?; + writeln!(file)?; + println!("Cache qualification report: {}", report_path.display()); + result +} + +async fn qualify(directory: &Path, report: &mut Report) -> Result<()> { + let backend = report.backend; + backend.require_host()?; + skippy_runtime::test_support::require_native_runtime(); + let model = required_path("SKIPPY_CACHE_QUAL_MODEL")?.canonicalize()?; + let fixture = report.fixture.clone(); + let model_sha256 = fixture.verify_model(&model)?; + report.model_sha256 = Some(model_sha256.clone()); + report.skippy_binary_sha256 = Some(file_sha256(&env::current_exe()?)?); + + let messages = messages(); + let request = generation_request(&fixture, &messages)?; + // Run the two engines sequentially so the reference cannot change the + // candidate's device resource budget. + if env::var_os("SKIPPY_CACHE_QUAL_LLAMA_SERVER").is_some() { + match reference::observe(backend, directory, &model, &fixture, &messages).await { + Ok(reference) => report.reference = Some(reference), + Err(error) => report.reference_error = Some(format!("{error:#}")), + } + } + let config = stage_config(&fixture, &model, &model_sha256)?; + let native_log = directory.join("skippy-native.log"); + skippy_runtime::redirect_native_logs_to_file(&native_log)?; + let result = observe_candidate(fixture.family, config.clone(), &request, report).await; + skippy_runtime::restore_native_logs(); + result?; + report.skippy_offloaded_layers = + Some(backend.offloaded_layers(&fs::read_to_string(native_log)?)?); + ownership::observe(directory, config.clone(), report).await?; + template::capture( + &directory.join("template-identity"), + backend, + config, + &fixture, + report.template.get_or_insert_default(), + )?; + ensure!( + file_sha256(&model)? == model_sha256, + "fixture changed during the run" + ); + + evidence::validate_measurements(report) +} + +fn messages() -> Value { + json!([{"role":"user","content": user_content( + "The Harbor access code is 1729. Return only a JSON object with the integer field code containing the Harbor access code. Do not use Markdown fences or commentary." + )}]) +} + +fn user_content(question: &str) -> String { + format!( + "{}\n\n{question}", + include_str!("../../../tests/fixtures/skippy-kv-qualification-context.txt") + ) +} + +fn generation_request(fixture: &Fixture, messages: &Value) -> Result { + Ok(serde_json::from_value::(json!({ + "model": fixture.model_id(), + "messages": messages, + "temperature": 0, + "seed": 1, + "max_tokens": MAX_TOKENS, + "logprobs": true, + "top_logprobs": TOP_K, + "reasoning_effort": "none", + "response_format": {"type": "json_schema", "json_schema": { + "name": "cache_answer", "strict": true, + "schema": {"type": "object", "properties": {"code": {"type": "integer"}}, + "required": ["code"], "additionalProperties": false} + }} + }))? + .into()) +} + +fn stage_config(fixture: &Fixture, model: &Path, sha256: &str) -> Result { + Ok(serde_json::from_value(json!({ + "run_id": "cache-qualification", + "topology_id": "standalone", + "model_id": fixture.model_id(), + "model_path": model, + "source_model_path": model, + "source_model_sha256": sha256, + "source_model_bytes": fs::metadata(model)?.len(), + "stage_id": "stage-0", + "stage_index": 0, + "layer_start": 0, + "layer_end": fixture.layers, + "ctx_size": CONTEXT_TOKENS, + "lane_count": 1, + "n_batch": BATCH_TOKENS, + "n_ubatch": BATCH_TOKENS, + "n_gpu_layers": -1, + "cache_type_k": "f16", + "cache_type_v": "f16", + "kv_unified": true, + "flash_attn_type": "disabled", + "native_mtp_enabled": false, + "execution_contract": "", + "load_mode": "runtime-slice", + "bind_addr": "127.0.0.1:0", + "kv_cache": {"mode":"lookup-record", "min_tokens":64, "max_entries":8} + }))?) +} + +async fn observe_candidate( + family: Family, + config: StageConfig, + request: &GenerationRequest, + report: &mut Report, +) -> Result<()> { + let mut candidate = CandidateRunner::new(config, family)?; + report.cold = Some(candidate.generate(request)?); + let structured_cases = structured::observe_cold(&report.fixture, &candidate).await?; + let mut conversations = Vec::new(); + for case in conversation::Case::ALL { + let request = generation_request(&report.fixture, &case.messages())?; + let cold = candidate + .generate(&request) + .with_context(|| format!("cold {case:?}"))?; + conversations.push((case, request, cold)); + } + let cache = candidate.enable_cache(None)?; + ensure!( + cache.l2.is_none(), + "host-RAM reuse must be disabled for the L1 control" + ); + report.seed = Some(candidate.generate(request)?); + tiers::drain_workers(&cache)?; + report.replay = Some(candidate.generate(request)?); + for (case, request, cold) in conversations { + tiers::drain_workers(&cache)?; + let warm = candidate + .generate(&request) + .with_context(|| format!("warm {case:?}"))?; + report + .conversations + .insert(case, conversation::Observation { cold, warm }); + } + structured::observe_warm(structured_cases, &candidate, &cache, &mut report.structured).await?; + Ok(()) +} + +struct CandidateRunner { + backend: StageOpenAiBackend, + family: Family, + receipts: mpsc::Receiver, + starts: mpsc::Receiver, + events: mpsc::Receiver, +} + +impl CandidateRunner { + fn new(config: StageConfig, family: Family) -> Result { + let (sender, receipts) = mpsc::sync_channel(1); + let (start_sender, starts) = mpsc::sync_channel(1); + let (telemetry, events) = Telemetry::captured(config.clone(), TelemetryLevel::Debug); + let model_id = config.model_id.clone(); + let mut backend = local_openai_backend(config, model_id)?; + backend.telemetry = telemetry; + backend.generation_receipt = Some(GenerationReceiptConfig::from_lifecycle_ingress( + Arc::new(ReceiptIngress { + receipts: sender, + starts: start_sender, + }), + )); + Ok(Self { + backend, + family, + receipts, + starts, + events, + }) + } + + fn enable_cache(&mut self, manager: Option) -> Result> { + let cache = Arc::new( + KvStageIntegration::from_runtime_with_l3_manager( + &self.backend.config, + &self.backend.runtime, + manager, + None, + )? + .context("loaded runtime did not admit cache reuse")?, + ); + ensure!( + (cache.payload == self.family.payload() + || (cache.resident_requires_checkpoint() + && self.family.payload() + == crate::kv_integration::StagePrefixCachePayload::KvRecurrent)) + && self + .backend + .config + .kv_cache + .as_ref() + .is_some_and(|kv| kv.mode == StageKvCacheMode::LookupRecord), + "fixture cache mode {:?} must admit {:?} lookup and recording", + cache.payload, + self.family.payload() + ); + self.backend.kv = Some(Arc::clone(&cache)); + Ok(cache) + } + + fn generate(&self, request: &GenerationRequest) -> Result { + self.generate_with_context(request, &InferenceRequestContext::new()) + } + + fn generate_with_context( + &self, + request: &GenerationRequest, + context: &InferenceRequestContext, + ) -> Result { + let result = generate(&self.backend, request, &self.receipts, context); + let start = self.starts.try_recv(); + let mut observation = result?; + let start = start.context("missing native generation start")?; + ensure!( + start.prompt_token_ids.as_ref() == observation.generation.prompt_ids.as_slice(), + "native prompt changed before the generation receipt" + ); + self.observe_restore(&mut observation.cache)?; + Ok(observation) + } + + fn observe_restore(&self, cache: &mut CacheObservation) -> Result<()> { + let mut restores = self + .events + .try_iter() + .filter(|event| event.event == "stage.openai_kv_lookup_decision") + .filter(|event| { + event.attributes.contains_key("skippy.exact_cache.source") + || event + .attributes + .get("skippy.kv.decision") + .and_then(Value::as_str) + == Some("resident_hit") + }); + if let Some(event) = restores.next() { + let attr = |key| { + event + .attributes + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + }; + cache.restore_source = attr("skippy.exact_cache.source"); + if cache.restore_source.is_none() { + cache.hit_kind = Some("resident_prefix".into()); + } + cache.payload_kind = attr("skippy.exact_cache.payload_kind"); + } + ensure!( + restores.next().is_none(), + "request reported multiple exact restore sources" + ); + Ok(()) + } +} + +fn generate( + backend: &crate::frontend::generation::StageOpenAiBackend, + request: &GenerationRequest, + receipts: &mpsc::Receiver, + context: &InferenceRequestContext, +) -> Result { + let defaults = backend.request_defaults.snapshot(); + let options = chat_template_options(request, &defaults)?; + let prompt = backend.prepare_chat_prompt(request, options.clone())?; + let metadata = prompt.chat_parse_metadata.clone(); + let prompt_sha256 = sha256(prompt.text.as_bytes()); + let checkpoint = prompt + .recurrent_cache_prefix_text + .as_deref() + .map(|text| backend.tokenize(text)) + .transpose()?; + let sampling = chat_sampling_config(request, &defaults)?; + let ids = generation_ids( + InferenceCacheHints::from_chat_request(request), + None, + context, + ) + .with_chat_template(prompt.cache_template_digest); + let output = backend.generate_text( + prompt, + GenerationTokenLimit::Explicit(MAX_TOKENS), + None, + (0, 0), + request.stop.as_ref(), + sampling, + None, + None, + None, + ids, + |_| Ok(()), + )?; + let receipt = receipts + .try_recv() + .context("missing native generation receipt")?; + let chat_checkpoint_tokens = checkpoint + .filter(|tokens| { + !tokens.is_empty() + && tokens.len() < receipt.prompt_token_ids.len() + && receipt.prompt_token_ids.starts_with(tokens) + }) + .map(|tokens| u32::try_from(tokens.len())) + .transpose()?; + let generation = Generation { + prompt_sha256, + prompt_ids: receipt.prompt_token_ids.to_vec(), + generated_ids: receipt.generated_token_ids.into_vec(), + content: answer::content( + backend, + request, + &options, + metadata.as_deref(), + &output.text, + )?, + raw_content: Some(output.text), + top_logprobs: output + .token_logprobs + .context("missing Skippy logprobs")? + .into_iter() + .map(|row| { + row.top + .into_iter() + .map(|score| TokenScore { + id: score.token_id, + logprob: score.logprob.map(f64::from), + }) + .collect() + }) + .collect(), + }; + Ok(Candidate { + generation, + chat_checkpoint_tokens, + cache: CacheObservation { + status: output.cache_status.into(), + hit_kind: output.cache_hit_kind.map(str::to_owned), + restore_source: None, + payload_kind: None, + prompt_tokens: output.prompt_tokens, + cached_tokens: output.cached_prompt_tokens, + matched_tokens: output.matched_prefix_tokens, + suffix_tokens: output.suffix_prefill_tokens, + }, + }) +} + +struct ReceiptIngress { + receipts: mpsc::SyncSender, + starts: mpsc::SyncSender, +} + +impl GenerationLifecycleIngress for ReceiptIngress { + fn try_submit(&self, observation: GenerationLifecycleObservation) -> Result<()> { + match observation { + GenerationLifecycleObservation::Started(start) => self + .starts + .try_send(start) + .context("duplicate or undeliverable generation start")?, + GenerationLifecycleObservation::Completed(receipt) => { + self.receipts + .try_send(receipt) + .context("duplicate or undeliverable generation receipt")? + } + _ => {} + } + Ok(()) + } +} + +fn required_path(key: &str) -> Result { + env::var_os(key) + .map(PathBuf::from) + .with_context(|| format!("set {key}")) +} + +fn sha256(bytes: &[u8]) -> String { + hex_digest(&Sha256::digest(bytes)) +} + +fn file_sha256(path: &Path) -> Result { + let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?; + let mut reader = BufReader::with_capacity(64 * 1024, file); + let mut digest = Sha256::new(); + loop { + let bytes = reader.fill_buf()?; + if bytes.is_empty() { + break; + } + digest.update(bytes); + let count = bytes.len(); + reader.consume(count); + } + Ok(hex_digest(&digest.finalize())) +} + +fn hex_digest(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/answer.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/answer.rs new file mode 100644 index 00000000..5b7d4460 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/answer.rs @@ -0,0 +1,84 @@ +//! Validate the same chat content that the production response exposes. +use super::{ + CandidateRunner, Family, Fixture, chat_template_options, evidence, generation_request, + required_path, stage_config, +}; +use crate::frontend::generation::{StageOpenAiBackend, chat_output_parser_required}; +use anyhow::{Context, Result, ensure}; +use serde_json::json; +use skippy_inference_api::generation::GenerationRequest; +use skippy_runtime::ChatTemplateOptions; + +pub(super) fn content( + backend: &StageOpenAiBackend, + request: &GenerationRequest, + options: &ChatTemplateOptions, + metadata: Option<&str>, + raw: &str, +) -> Result { + if !chat_output_parser_required(request, options) { + return Ok(raw.to_owned()); + } + Ok( + match backend.parse_chat_output(raw, request, metadata, false)? { + Some(parsed) => parsed + .content + .context("chat parser returned no answer content")?, + None => raw.to_owned(), + }, + ) +} + +#[test] +#[ignore = "requires the pinned dense model and native chat parser"] +fn schema_answer_uses_parsed_content_and_rejects_wrong_values() -> Result<()> { + skippy_runtime::test_support::require_native_runtime(); + let fixture = Fixture::load(Family::DenseAttention)?; + let model = required_path("SKIPPY_CACHE_QUAL_MODEL")?.canonicalize()?; + let digest = fixture.verify_model(&model)?; + let runner = CandidateRunner::new(stage_config(&fixture, &model, &digest)?, fixture.family)?; + let request = generation_request( + &fixture, + &super::conversation::Case::DivergentTail.messages(), + )?; + let defaults = runner.backend.request_defaults.snapshot(); + let options = chat_template_options(&request, &defaults)?; + ensure!( + chat_output_parser_required(&request, &options), + "control must exercise native chat parsing" + ); + let prompt = runner + .backend + .prepare_chat_prompt(&request, options.clone())?; + for raw in [ + "{\"code\":1618}", + "```json\n{\n \"code\": 1618\n}\n```", + "```json\n{\"code\":1729}\n```", + ] { + let parsed = content( + &runner.backend, + &request, + &options, + prompt.chat_parse_metadata.as_deref(), + raw, + )?; + let expected = if raw.contains("1729") { 1729 } else { 1618 }; + ensure!( + serde_json::from_str::(&parsed)? == json!({"code":expected}), + "parser changed the answer" + ); + let generation = evidence::Generation { + prompt_sha256: "parser-control".into(), + prompt_ids: vec![1], + generated_ids: vec![2], + content: parsed, + raw_content: Some(raw.into()), + top_logprobs: vec![], + }; + ensure!( + evidence::validate_answer(&generation, 1618).is_ok() == (expected == 1618), + "known-answer check accepted the wrong value" + ); + } + Ok(()) +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/backend.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/backend.rs new file mode 100644 index 00000000..7d88f98c --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/backend.rs @@ -0,0 +1,108 @@ +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use std::env; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub(super) enum Backend { + #[serde(rename = "macos-arm64-metal")] + Metal, + #[serde(rename = "linux-x86_64-cuda")] + Cuda, + #[serde(rename = "linux-aarch64-cuda")] + CudaArm64, +} + +impl Backend { + pub(super) fn selected() -> Result { + match env::var("SKIPPY_CACHE_QUAL_BACKEND") { + Ok(value) if value == "metal" => Ok(Self::Metal), + Ok(value) if value == "cuda" => Ok(Self::Cuda), + Ok(value) if value == "cuda-arm64" => Ok(Self::CudaArm64), + Ok(value) => bail!("unknown qualification backend {value:?}"), + Err(env::VarError::NotPresent) => Ok(Self::Metal), + Err(error) => Err(error.into()), + } + } + + pub(super) fn require_host(self) -> Result<()> { + let supported = match self { + Self::Metal => cfg!(all(target_os = "macos", target_arch = "aarch64")), + Self::Cuda => cfg!(all(target_os = "linux", target_arch = "x86_64")), + Self::CudaArm64 => cfg!(all(target_os = "linux", target_arch = "aarch64")), + }; + ensure!( + supported, + "host does not match the {self:?} qualification profile" + ); + Ok(()) + } + + pub(super) fn offloaded_layers(self, log: &str) -> Result { + ensure!( + log.lines().any(|line| { + line.split_ascii_whitespace() + .any(|word| self.is_device_buffer(word)) + && (line.contains("KV buffer") || line.contains("compute buffer")) + }), + "no {self:?} device buffer allocation was observed" + ); + log.lines() + .filter_map(|line| { + let (_, count) = line.split_once("offloaded ")?; + let (count, _) = count.split_once('/')?; + line.contains("layers to GPU") + .then(|| count.parse::().ok()) + .flatten() + }) + .find(|&count| count > 0) + .context("no actual GPU layer offload was observed") + } + + fn is_device_buffer(self, word: &str) -> bool { + let prefix = match self { + Self::Metal if word == "Metal" => return true, + Self::Metal => "MTL", + Self::Cuda | Self::CudaArm64 => "CUDA", + }; + word.strip_prefix(prefix).is_some_and(|index| { + !index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()) + }) + } +} + +#[test] +fn backend_evidence_requires_matching_device_buffers_and_positive_offload() { + let metal = "sched_reserve: MTL0 compute buffer size = 256.00 MiB"; + let cuda = "sched_reserve: CUDA0 compute buffer size = 256.00 MiB"; + let pinned_host = "sched_reserve: CUDA_Host compute buffer size = 256.00 MiB"; + let offload = "load_tensors: offloaded 37/37 layers to GPU"; + assert_eq!( + Backend::Metal + .offloaded_layers(&format!("{metal}\n{offload}")) + .unwrap(), + 37 + ); + assert_eq!( + Backend::Cuda + .offloaded_layers(&format!("{cuda}\n{offload}")) + .unwrap(), + 37 + ); + assert!( + Backend::Cuda + .offloaded_layers(&format!("{pinned_host}\n{offload}")) + .is_err() + ); + assert!( + Backend::Metal + .offloaded_layers(&format!("{cuda}\n{offload}")) + .is_err() + ); + assert!(Backend::Metal.offloaded_layers(metal).is_err()); + assert_eq!( + Backend::CudaArm64 + .offloaded_layers(&format!("{cuda}\n{offload}")) + .unwrap(), + 37 + ); +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/conversation.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/conversation.rs new file mode 100644 index 00000000..4d1d8e36 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/conversation.rs @@ -0,0 +1,293 @@ +use super::{ + EXPECTED_CODE, Family, + evidence::{Candidate, Report, Status, compare, validate_l1_replay, validate_miss}, + messages, user_content, +}; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Case { + FirstFollowUp, + SecondFollowUp, + DivergentTail, +} + +impl Case { + pub(super) const ALL: [Self; 3] = [ + Self::FirstFollowUp, + Self::SecondFollowUp, + Self::DivergentTail, + ]; + + pub(super) fn messages(self) -> Value { + if self == Self::DivergentTail { + return json!([{"role": "user", "content": user_content( + "The Harbor access code is 1618. Return the Harbor access code as a JSON object with the integer field code." + )}]); + } + let Value::Array(mut history) = messages() else { + unreachable!("qualification seed is a message array"); + }; + history.extend([ + json!({"role": "assistant", "content": format!("{{\"code\":{EXPECTED_CODE}}}")}), + json!({"role": "user", "content": "The Harbor access code has changed to 3141. Return the new code as a JSON object with the integer field code."}), + ]); + if self == Self::SecondFollowUp { + history.extend([ + json!({"role": "assistant", "content": "{\"code\":3141}"}), + json!({"role": "user", "content": "The Harbor access code has changed to 2718. Return the new code as a JSON object with the integer field code."}), + ]); + } + Value::Array(history) + } + + fn code(self) -> i64 { + match self { + Self::FirstFollowUp => 3141, + Self::SecondFollowUp => 2718, + Self::DivergentTail => 1618, + } + } + + fn label(self) -> &'static str { + match self { + Self::FirstFollowUp => "first follow-up", + Self::SecondFollowUp => "second follow-up", + Self::DivergentTail => "divergent tail", + } + } +} + +#[derive(Deserialize, Serialize)] +pub(super) struct Observation { + pub(super) cold: Candidate, + pub(super) warm: Candidate, +} + +#[derive(Serialize)] +pub(super) struct ResultRow { + pub(super) status: Status, + minimum_matched_tokens: Option, + maximum_matched_tokens: Option, + pub(super) errors: Vec, +} + +pub(super) fn validate(report: &Report) -> BTreeMap { + Case::ALL + .into_iter() + .map(|case| (case, validate_case(report, case))) + .collect() +} + +fn validate_case(report: &Report, case: Case) -> ResultRow { + let mut row = ResultRow { + status: Status::Fail, + minimum_matched_tokens: None, + maximum_matched_tokens: None, + errors: Vec::new(), + }; + let observations = case_observations(report, case); + let (observed, source) = match observations { + Ok(observations) => observations, + Err(error) => { + row.errors.push(format!("{}: {error:#}", case.label())); + return row; + } + }; + let family = report.fixture.family; + let accounting = validate_accounting(case, family, observed, source, &mut row); + for (check, outcome) in [ + ( + "known answer and prompt identity", + compare( + &observed.cold.generation, + &observed.warm.generation, + case.code(), + ), + ), + ("token accounting", accounting), + ] { + if let Err(error) = outcome { + row.errors + .push(format!("{} {check}: {error:#}", case.label())); + } + } + if row.errors.is_empty() { + row.status = Status::Pass; + } + row +} + +fn case_observations(report: &Report, case: Case) -> Result<(&Observation, &Candidate)> { + let observed = report + .conversations + .get(&case) + .context("missing Skippy conversation results")?; + let source = match case { + Case::FirstFollowUp | Case::DivergentTail => report.seed.as_ref(), + Case::SecondFollowUp => report + .conversations + .get(&Case::FirstFollowUp) + .map(|case| &case.warm), + } + .context("missing previously seeded conversation")?; + Ok((observed, source)) +} + +fn validate_accounting( + case: Case, + family: Family, + observation: &Observation, + source: &Candidate, + row: &mut ResultRow, +) -> Result<()> { + let prompt = observation.warm.generation.prompt_ids.as_slice(); + let source_prompt = source.generation.prompt_ids.as_slice(); + let prompt_tokens = u32::try_from(prompt.len())?; + ensure!( + observation.cold.cache.status == "disabled" && observation.cold.cache.cached_tokens == 0, + "comparison baseline did not run with caching disabled" + ); + match case { + Case::DivergentTail => ensure!( + !prompt.starts_with(source_prompt) && common_prefix(prompt, source_prompt) >= 64, + "divergent chat must share an admissible prefix and change the tail" + ), + _ => ensure!( + prompt.len() > source_prompt.len(), + "follow-up did not grow the prompt" + ), + } + let (minimum, maximum) = expected_match(family, source, prompt)?; + row.minimum_matched_tokens = Some(minimum); + row.maximum_matched_tokens = Some(maximum); + if maximum == 0 { + ensure!( + case == Case::DivergentTail, + "follow-up did not preserve a reusable checkpoint" + ); + validate_miss(prompt_tokens, &observation.warm) + } else { + let restored = observation.warm.cache.matched_tokens; + ensure!( + restored >= minimum && restored <= maximum, + "restored prefix {restored} lies outside the retained {minimum}..={maximum} tokens" + ); + validate_l1_replay(family, prompt_tokens, restored, &observation.warm) + } +} + +fn expected_match(family: Family, source: &Candidate, prompt: &[i32]) -> Result<(u32, u32)> { + let source_prompt = source.generation.prompt_ids.as_slice(); + let maximum = family.prefill_tokens(u32::try_from(prompt.len())?) as usize; + let prompt = &prompt[..maximum]; + match family { + Family::DenseAttention | Family::AttentionMoe => { + let previous_prefill = source_prompt.len().saturating_sub(1); + let minimum = common_prefix(prompt, &source_prompt[..previous_prefill]); + // Receipts contain delivered tokens, not the scheduler's queued + // sample. Read-ahead may already have consumed the delivered stop + // token, so the entire delivered prefix is a valid upper bound. + let mut retained = source_prompt.to_vec(); + let generated = &source.generation.generated_ids; + retained.extend_from_slice(generated); + let maximum = common_prefix(prompt, &retained); + Ok((u32::try_from(minimum)?, u32::try_from(maximum)?)) + } + Family::HybridDense | Family::HybridMoe => { + let checkpoint = source + .chat_checkpoint_tokens + .context("missing recurrent chat checkpoint")?; + let prefix = source_prompt + .get(..checkpoint as usize) + .context("invalid recurrent chat checkpoint")?; + let matched = if prompt.starts_with(prefix) { + checkpoint + } else { + 0 + }; + Ok((matched, matched)) + } + } +} + +fn common_prefix(first: &[i32], second: &[i32]) -> usize { + first + .iter() + .zip(second) + .take_while(|(left, right)| left == right) + .count() +} + +#[test] +fn conversation_keeps_the_seed_for_follow_ups_and_changes_the_divergent_tail() { + let seed = messages(); + let original = &seed[0]; + assert_eq!(&Case::FirstFollowUp.messages()[0], original); + assert_eq!(&Case::SecondFollowUp.messages()[0], original); + assert_ne!(&Case::DivergentTail.messages()[0], original); + assert_eq!(Case::SecondFollowUp.messages().as_array().unwrap().len(), 5); +} + +#[test] +fn attention_accounting_includes_decoded_generated_tokens() { + let source: Candidate = serde_json::from_value(json!({ + "generation": {"prompt_sha256":"prompt", "prompt_ids":[1,2,3,4], + "generated_ids":[5,6,7], "content":"{\"code\":1729}", "top_logprobs":[]}, + "chat_checkpoint_tokens":null, + "cache":{"status":"miss", "hit_kind":null,"restore_source":null,"payload_kind":null, + "prompt_tokens":4,"cached_tokens":0,"matched_tokens":0,"suffix_tokens":4} + })) + .unwrap(); + assert_eq!( + expected_match(Family::AttentionMoe, &source, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), + (3, 7) + ); + assert_eq!( + expected_match(Family::DenseAttention, &source, &[1, 2, 9, 8]).unwrap(), + (2, 2) + ); + let mut cold = source.clone(); + cold.generation.prompt_ids = (1..=9).collect(); + cold.cache.status = "disabled".into(); + cold.cache.prompt_tokens = 9; + cold.cache.suffix_tokens = 9; + let mut warm = cold.clone(); + warm.cache.status = "hit".into(); + warm.cache.hit_kind = Some("resident_prefix".into()); + warm.cache.cached_tokens = 7; + warm.cache.matched_tokens = 7; + warm.cache.suffix_tokens = 2; + let mut observation = Observation { cold, warm }; + let mut row = ResultRow { + status: Status::Fail, + minimum_matched_tokens: None, + maximum_matched_tokens: None, + errors: Vec::new(), + }; + validate_accounting( + Case::FirstFollowUp, + Family::AttentionMoe, + &observation, + &source, + &mut row, + ) + .unwrap(); + observation.warm.cache.cached_tokens = 8; + observation.warm.cache.matched_tokens = 8; + observation.warm.cache.suffix_tokens = 1; + assert!( + validate_accounting( + Case::FirstFollowUp, + Family::AttentionMoe, + &observation, + &source, + &mut row, + ) + .is_err() + ); +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/evidence.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/evidence.rs new file mode 100644 index 00000000..059d13d9 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/evidence.rs @@ -0,0 +1,694 @@ +use super::{ + Backend, CONTEXT_TOKENS, EXPECTED_CODE, LLAMA_PIN, MAX_TOKENS, TOP_K, + conversation::{self, Case}, + fixture::{Family, Fixture}, + reference, structured, template, +}; +use crate::kv_integration::StagePrefixCachePayload; +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use skippy_model_artifact::kv_fixtures::valid_sha256; +use std::collections::BTreeMap; + +const SCHEMA_VERSION: u32 = 11; +const QUALIFICATION_CONTRACT: &str = "behavior_and_reuse_v1"; +const SCENARIO: &str = "cross_tier_replay"; +const ABI: [u32; 3] = [ + skippy_runtime::ABI_VERSION_MAJOR, + skippy_runtime::ABI_VERSION_MINOR, + skippy_runtime::ABI_VERSION_PATCH, +]; + +#[derive(Deserialize, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Status { + Pass, + Fail, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct Report { + schema_version: u32, + scenario: String, + pub(super) backend: Backend, + pub(super) status: Status, + model_id: String, + pub(super) fixture: Fixture, + llama_pin: String, + skippy_abi: [u32; 3], + qualification_contract: String, + context_tokens: u32, + pub(super) model_sha256: Option, + pub(super) skippy_binary_sha256: Option, + pub(super) reference: Option, + pub(super) reference_error: Option, + pub(super) skippy_offloaded_layers: Option, + pub(super) cold: Option, + pub(super) seed: Option, + pub(super) replay: Option, + pub(super) conversations: BTreeMap, + #[serde(skip_deserializing)] + conversation_results: BTreeMap, + pub(super) structured: BTreeMap, + #[serde(skip_deserializing)] + structured_results: BTreeMap, + pub(super) template: Option, + #[serde(skip_deserializing)] + template_result: Option, + pub(super) durable: Option, + pub(super) ownership: Option, + pub(super) restart: Option, + pub(super) error: Option, + #[serde(skip_deserializing)] + validation_errors: Vec, +} + +impl Report { + pub(super) fn new(backend: Backend, fixture: Fixture) -> Self { + Self { + schema_version: SCHEMA_VERSION, + scenario: SCENARIO.into(), + backend, + status: Status::Fail, + model_id: fixture.model_id(), + fixture, + llama_pin: LLAMA_PIN.trim().into(), + skippy_abi: ABI, + qualification_contract: QUALIFICATION_CONTRACT.into(), + context_tokens: CONTEXT_TOKENS, + model_sha256: None, + skippy_binary_sha256: None, + reference: None, + reference_error: None, + skippy_offloaded_layers: None, + cold: None, + seed: None, + replay: None, + conversations: BTreeMap::new(), + conversation_results: BTreeMap::new(), + structured: BTreeMap::new(), + structured_results: BTreeMap::new(), + template: None, + template_result: None, + durable: None, + ownership: None, + restart: None, + error: None, + validation_errors: Vec::new(), + } + } +} + +#[derive(Deserialize, Serialize)] +pub(super) struct Reference { + pub(super) binary_sha256: String, + pub(super) version: String, + pub(super) offloaded_layers: usize, + pub(super) template_sha256: String, + pub(super) generation: Generation, + pub(super) conversations: BTreeMap, + pub(super) structured: BTreeMap, +} + +#[derive(Deserialize, Serialize, Clone)] +pub(super) struct Candidate { + pub(super) generation: Generation, + pub(super) chat_checkpoint_tokens: Option, + pub(super) cache: CacheObservation, +} + +#[derive(Deserialize, Serialize, Clone)] +pub(super) struct Generation { + pub(super) prompt_sha256: String, + pub(super) prompt_ids: Vec, + pub(super) generated_ids: Vec, + pub(super) content: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) raw_content: Option, + pub(super) top_logprobs: Vec>, +} + +#[derive(Deserialize, Serialize, Clone)] +pub(super) struct TokenScore { + pub(super) id: i32, + pub(super) logprob: Option, +} + +#[derive(Default, Deserialize, Serialize, Clone)] +pub(super) struct CacheObservation { + pub(super) status: String, + pub(super) hit_kind: Option, + pub(super) restore_source: Option, + pub(super) payload_kind: Option, + pub(super) prompt_tokens: u32, + pub(super) cached_tokens: u32, + pub(super) matched_tokens: u32, + pub(super) suffix_tokens: u32, +} + +#[derive(Default, Deserialize, Serialize)] +pub(super) struct DurableObservations { + pub(super) checkpoint_tokens: Option, + pub(super) seed: Option, + pub(super) first_l3: Option, + pub(super) second_l3: Option, + pub(super) l2: Option, + pub(super) l2_disk_payload_bytes: Option, + pub(super) namespace_miss: Option, + pub(super) evictions: Vec, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct Eviction { + pub(super) resident_entries: usize, + pub(super) exact_entries: usize, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct CleanRestartObservation { + pub(super) pid: u32, + pub(super) offloaded_layers: usize, + pub(super) replay: Candidate, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct OwnershipObservation { + pub(super) publisher_pid: u32, + pub(super) publisher_offloaded_layers: usize, + pub(super) clean_restart: CleanRestartObservation, + pub(super) lock_conflict: String, + pub(super) contender: Candidate, + pub(super) preserved_pack_sha256: String, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct RestartObservation { + pub(super) pid: u32, + pub(super) offloaded_layers: usize, + pub(super) replay: Candidate, + pub(super) corrupt_fallback: Candidate, + pub(super) corrupt_objects: u64, + pub(super) reconciled_temporary_files: u64, +} + +pub(super) fn validate_measurements(report: &mut Report) -> Result<()> { + require_expected_identity(report)?; + validate(report) +} + +fn require_expected_identity(report: &Report) -> Result<()> { + ensure!( + report.schema_version == SCHEMA_VERSION + && report.scenario == SCENARIO + && report.llama_pin == LLAMA_PIN.trim() + && report.skippy_abi == ABI + && report.context_tokens == CONTEXT_TOKENS + && report.qualification_contract == QUALIFICATION_CONTRACT, + "correctness evidence does not match this qualification contract" + ); + let pinned = Fixture::load(report.fixture.family)?; + ensure!( + report.fixture == pinned + && report.model_id == pinned.model_id() + && report.model_sha256.as_deref() == Some(pinned.digest()), + "correctness evidence does not match the pinned model identity" + ); + ensure!( + report + .skippy_binary_sha256 + .as_deref() + .is_some_and(valid_sha256) + && report.reference.as_ref().is_none_or(|reference| { + valid_sha256(&reference.binary_sha256) + && reference::version_matches(&reference.version, LLAMA_PIN.trim()) + }), + "correctness evidence lacks matching binary provenance" + ); + Ok(()) +} + +pub(super) fn verify_saved(report: &mut Report) -> Result<()> { + ensure!( + report.status == Status::Pass && report.error.is_none(), + "reported qualification run failed: {}", + report.error.as_deref().unwrap_or("no error recorded") + ); + validate_measurements(report) +} + +pub(super) fn validate(report: &mut Report) -> Result<()> { + let template = report + .template + .as_ref() + .context("missing chat template identity observations") + .and_then(|observation| observation.validate()); + report.template_result = Some(if template.is_ok() { + Status::Pass + } else { + Status::Fail + }); + let mut errors = Vec::new(); + for result in [ + validate_l1(report), + validate_durable(report), + validate_cold(report), + template.context("chat template identity qualification"), + ] { + if let Err(error) = result { + errors.push(format!("{error:#}")); + } + } + if let Some(cold) = &report.cold { + for (label, case) in replay_cases(report) { + if let Some(candidate) = case + && let Err(error) = compare(&cold.generation, &candidate.generation, EXPECTED_CODE) + .with_context(|| label) + { + errors.push(format!("{error:#}")); + } + } + } + report.conversation_results = conversation::validate(report); + errors.extend( + report + .conversation_results + .values() + .flat_map(|row| row.errors.iter().cloned()), + ); + report.structured_results = structured::validate(report.fixture.family, &report.structured); + errors.extend( + report + .structured_results + .values() + .flat_map(|row| row.errors.iter().cloned()), + ); + report.validation_errors = errors; + if let Some(first) = report.validation_errors.first() { + bail!( + "{} qualification checks failed. {first}", + report.validation_errors.len() + ); + } + Ok(()) +} + +fn replay_cases(report: &Report) -> [(&'static str, Option<&Candidate>); 11] { + let durable = report.durable.as_ref(); + let ownership = report.ownership.as_ref(); + let restart = report.restart.as_ref(); + [ + ("L1 seed against cold Skippy", report.seed.as_ref()), + ("L1 replay against cold Skippy", report.replay.as_ref()), + ( + "durable seed against cold Skippy", + durable.and_then(|case| case.seed.as_ref()), + ), + ( + "first disk fill against cold Skippy", + durable.and_then(|case| case.first_l3.as_ref()), + ), + ( + "second disk fill against cold Skippy", + durable.and_then(|case| case.second_l3.as_ref()), + ), + ( + "host-RAM replay against cold Skippy", + durable.and_then(|case| case.l2.as_ref()), + ), + ( + "clean restart disk replay against cold Skippy", + ownership.map(|case| &case.clean_restart.replay), + ), + ( + "lock contention fallback against cold Skippy", + ownership.map(|case| &case.contender), + ), + ( + "crash restart disk replay against cold Skippy", + restart.map(|case| &case.replay), + ), + ( + "isolated execution scope against cold Skippy", + durable.and_then(|case| case.namespace_miss.as_ref()), + ), + ( + "corrupt L3 fallback against cold Skippy", + restart.map(|case| &case.corrupt_fallback), + ), + ] +} + +fn validate_durable(report: &Report) -> Result<()> { + let cold = report.cold.as_ref().context("missing cold output")?; + let prompt_tokens = u32::try_from(cold.generation.prompt_ids.len())?; + let durable = report + .durable + .as_ref() + .context("missing cross-tier evidence")?; + let restart = report + .restart + .as_ref() + .context("missing restart evidence")?; + let ownership = report + .ownership + .as_ref() + .context("missing exclusive ownership evidence")?; + let checkpoint = durable + .checkpoint_tokens + .context("missing durable checkpoint token count")?; + let seed = durable.seed.as_ref().context("missing durable seed")?; + validate_miss(prompt_tokens, seed).context("durable seed accounting")?; + ensure!( + durable.evictions.len() == 3 + && durable + .evictions + .iter() + .all(|eviction| eviction.exact_entries + eviction.resident_entries > 0), + "the expected in-memory cache entries were not evicted" + ); + ensure!( + durable.l2_disk_payload_bytes == Some(0), + "L2 restore read a disk payload" + ); + ensure!( + ownership.publisher_offloaded_layers > 0 + && ownership.clean_restart.offloaded_layers > 0 + && restart.offloaded_layers > 0, + "an L3 owner did not execute on the qualification GPU" + ); + ensure!( + ownership.publisher_pid != 0 + && ownership.clean_restart.pid != 0 + && restart.pid != 0 + && ownership.publisher_pid != ownership.clean_restart.pid + && ownership.clean_restart.pid != restart.pid + && ownership.publisher_pid != restart.pid + && !ownership.lock_conflict.is_empty() + && valid_sha256(&ownership.preserved_pack_sha256), + "incomplete exclusive L3 ownership observations" + ); + ensure!( + restart.reconciled_temporary_files > 0, + "replacement did not reconcile the interrupted write" + ); + validate_miss(prompt_tokens, &ownership.contender) + .context("lock contention fallback accounting")?; + for (label, tier, replay) in [ + ("first disk fill", "l3", durable.first_l3.as_ref()), + ("second disk fill", "l3", durable.second_l3.as_ref()), + ("host-RAM replay", "l2", durable.l2.as_ref()), + ( + "clean restart disk replay", + "l3", + Some(&ownership.clean_restart.replay), + ), + ("crash restart disk replay", "l3", Some(&restart.replay)), + ] { + let replay = replay.with_context(|| format!("missing {label}"))?; + validate_durable_replay(prompt_tokens, replay, tier, checkpoint).with_context(|| label)?; + if report.fixture.family.payload() == StagePrefixCachePayload::KvRecurrent { + ensure!( + replay.cache.payload_kind.as_deref() == Some("kv-recurrent"), + "{label} must restore KV and recurrent state" + ); + } + } + let namespace = durable + .namespace_miss + .as_ref() + .context("missing namespace-isolation evidence")?; + validate_miss(prompt_tokens, namespace).context("isolated execution scope accounting")?; + ensure!( + restart.corrupt_objects > 0, + "L3 reported no corrupt object after truncation" + ); + validate_miss(prompt_tokens, &restart.corrupt_fallback) + .context("corrupt L3 fallback accounting")?; + Ok(()) +} + +pub(super) fn validate_miss(prompt_tokens: u32, candidate: &Candidate) -> Result<()> { + let cache = &candidate.cache; + ensure!( + cache.status == "miss" + && cache.hit_kind.is_none() + && cache.restore_source.is_none() + && cache.prompt_tokens == prompt_tokens + && cache.cached_tokens == 0 + && cache.matched_tokens == 0 + && cache.suffix_tokens == prompt_tokens, + "expected a cache miss and complete prefill" + ); + Ok(()) +} + +pub(super) fn validate_durable_replay( + prompt_tokens: u32, + replay: &Candidate, + tier: &str, + checkpoint: u32, +) -> Result<()> { + ensure!( + checkpoint > 0 && checkpoint < prompt_tokens, + "invalid checkpoint length" + ); + let cache = &replay.cache; + ensure!( + cache.status == "hit" + && cache.hit_kind.as_deref() == Some("exact_prefix") + && cache.restore_source.as_deref() == Some(tier), + "expected a successful {tier} restore, observed {:?}", + cache.restore_source + ); + ensure!( + cache.prompt_tokens == prompt_tokens + && cache.cached_tokens == checkpoint + && cache.matched_tokens == checkpoint + && cache.suffix_tokens == prompt_tokens - checkpoint, + "incorrect token accounting for {tier} restore of {checkpoint} prefill tokens" + ); + Ok(()) +} + +fn validate_cold(report: &Report) -> Result<()> { + ensure!( + report + .skippy_offloaded_layers + .is_some_and(|layers| layers > 0), + "Skippy must execute on the qualification GPU" + ); + let cold = report.cold.as_ref().context("missing cold Skippy result")?; + validate_answer(&cold.generation, EXPECTED_CODE) +} + +pub(super) fn validate_l1(report: &Report) -> Result<()> { + let cold = report.cold.as_ref().context("missing cold Skippy result")?; + let seed = report.seed.as_ref().context("missing L1 seed")?; + let replay = report.replay.as_ref().context("missing L1 replay")?; + let prompt_tokens = u32::try_from(cold.generation.prompt_ids.len())?; + ensure!(prompt_tokens > 64, "prompt is too short for L1 admission"); + for (case, expected_status) in [(cold, "disabled"), (seed, "miss")] { + ensure!( + case.cache.status == expected_status + && case.cache.hit_kind.is_none() + && case.cache.prompt_tokens == prompt_tokens + && case.cache.cached_tokens == 0 + && case.cache.matched_tokens == 0, + "{expected_status} generation reported unexpected cache reuse" + ); + } + let family = report.fixture.family; + let expected_match = if family.payload() == StagePrefixCachePayload::ResidentKv { + family.prefill_tokens(prompt_tokens) + } else { + seed.chat_checkpoint_tokens + .context("hybrid seed did not render a chat checkpoint")? + }; + validate_l1_replay(family, prompt_tokens, expected_match, replay) +} + +pub(super) fn validate_l1_replay( + family: Family, + prompt_tokens: u32, + expected_match: u32, + replay: &Candidate, +) -> Result<()> { + let prefill_tokens = family.prefill_tokens(prompt_tokens); + ensure!( + expected_match > 0 && expected_match <= prefill_tokens, + "invalid L1 prefix length" + ); + let native = replay.cache.hit_kind.as_deref() == Some("resident_prefix") + && replay.cache.restore_source.is_none(); + let serialized_hybrid = family.payload() == StagePrefixCachePayload::KvRecurrent + && replay.cache.hit_kind.as_deref() == Some("exact_prefix") + && replay.cache.restore_source.as_deref() == Some("radix") + && replay.cache.payload_kind.as_deref() == Some("kv-recurrent"); + ensure!( + replay.cache.status == "hit" && (native || serialized_hybrid), + "expected a complete L1 prefix restore, observed {:?}", + replay.cache.hit_kind + ); + ensure!( + replay.cache.prompt_tokens == prompt_tokens + && replay.cache.cached_tokens == expected_match + && replay.cache.matched_tokens == expected_match + && replay.cache.suffix_tokens == prompt_tokens - expected_match, + "L1 did not restore its expected {expected_match}-token prefix" + ); + Ok(()) +} + +/// Compare the request identity and known answer. Tokens and score traces are +/// retained diagnostics; GPU execution shapes need not reproduce their values. +pub(super) fn compare(expected: &Generation, actual: &Generation, code: i64) -> Result<()> { + ensure!( + expected.prompt_sha256 == actual.prompt_sha256, + "rendered prompt differs" + ); + ensure!( + expected.prompt_ids == actual.prompt_ids, + "prompt token IDs differ" + ); + validate_answer(expected, code).context("cold answer")?; + validate_answer(actual, code).context("replayed answer") +} + +pub(super) fn validate_answer(generation: &Generation, code: i64) -> Result<()> { + ensure!( + !generation.generated_ids.is_empty() + && generation.generated_ids.len() <= MAX_TOKENS as usize, + "missing or excessive generated token evidence" + ); + let answer: serde_json::Value = serde_json::from_str(&generation.content) + .context("answer is not a complete JSON object")?; + ensure!( + answer == serde_json::json!({"code": code}), + "wrong answer: expected code {code}, observed {answer}" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn behavior_accepts_different_tokenization_and_score_traces_but_rejects_wrong_answers() { + let expected = passing_report().cold.unwrap().generation; + let mut actual = expected.clone(); + actual.generated_ids = vec![7, 8]; + actual.top_logprobs.clear(); + actual.content = "{ \"code\" : 1729 }".into(); + compare(&expected, &actual, EXPECTED_CODE).unwrap(); + actual.content = "{\"code\":2718}".into(); + assert!(compare(&expected, &actual, EXPECTED_CODE).is_err()); + actual.content = expected.content.clone(); + actual.prompt_ids[0] ^= 1; + assert!(compare(&expected, &actual, EXPECTED_CODE).is_err()); + } + + fn passing_report() -> Report { + let score = (0..TOP_K) + .map(|value| TokenScore { + id: value as i32, + logprob: Some(-f64::from(value) - 0.5), + }) + .collect::>(); + let generation = Generation { + prompt_sha256: "prompt".into(), + prompt_ids: vec![1; 100], + generated_ids: vec![2; MAX_TOKENS as usize], + content: "{\"code\":1729}".into(), + raw_content: None, + top_logprobs: vec![score; MAX_TOKENS as usize], + }; + let cold = Candidate { + generation: generation.clone(), + chat_checkpoint_tokens: None, + cache: CacheObservation { + status: "disabled".into(), + hit_kind: None, + restore_source: None, + payload_kind: None, + prompt_tokens: 100, + cached_tokens: 0, + matched_tokens: 0, + suffix_tokens: 0, + }, + }; + let mut seed = cold.clone(); + seed.cache.status = "miss".into(); + let mut replay = cold.clone(); + replay.cache.status = "hit".into(); + replay.cache.hit_kind = Some("resident_prefix".into()); + replay.cache.cached_tokens = 99; + replay.cache.matched_tokens = 99; + replay.cache.suffix_tokens = 1; + let mut report = Report::new( + Backend::Metal, + Fixture::load(Family::DenseAttention).unwrap(), + ); + report.reference = Some(Reference { + binary_sha256: "reference".into(), + version: "version".into(), + offloaded_layers: 36, + template_sha256: report.fixture.chat_template_sha256.clone(), + generation, + conversations: BTreeMap::new(), + structured: BTreeMap::new(), + }); + report.skippy_offloaded_layers = Some(36); + report.cold = Some(cold); + report.seed = Some(seed); + report.replay = Some(replay); + report + } + + #[test] + fn dense_evidence_accepts_a_matching_resident_replay() { + validate_l1(&passing_report()).unwrap(); + } + + #[test] + fn dense_evidence_rejects_wrong_output_tier_and_accounting() { + let mut report = passing_report(); + report.replay.as_mut().unwrap().generation.content = "{\"code\":2718}".into(); + let cold = &report.cold.as_ref().unwrap().generation; + assert!( + compare( + cold, + &report.replay.as_ref().unwrap().generation, + EXPECTED_CODE + ) + .is_err() + ); + let mut report = passing_report(); + report.replay.as_mut().unwrap().cache.hit_kind = Some("exact_prefix".into()); + assert!(validate_l1(&report).is_err()); + let mut report = passing_report(); + report.replay.as_mut().unwrap().cache.suffix_tokens = 0; + assert!(validate_l1(&report).is_err()); + } + + #[test] + fn saved_evidence_rejects_the_previous_numerical_contract() { + let mut report = passing_report(); + report.schema_version = 10; + assert!(require_expected_identity(&report).is_err()); + } + + #[test] + fn durable_replay_requires_the_observed_tier_and_expected_suffix() { + let mut candidate = passing_report().replay.unwrap(); + candidate.cache.hit_kind = Some("exact_prefix".into()); + candidate.cache.restore_source = Some("l3".into()); + candidate.cache.cached_tokens = 64; + candidate.cache.matched_tokens = 64; + candidate.cache.suffix_tokens = 36; + validate_durable_replay(100, &candidate, "l3", 64).unwrap(); + assert!(validate_durable_replay(100, &candidate, "l2", 64).is_err()); + candidate.cache.suffix_tokens += 1; + assert!(validate_durable_replay(100, &candidate, "l3", 64).is_err()); + } +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/fixture.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/fixture.rs new file mode 100644 index 00000000..8dcc3cc1 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/fixture.rs @@ -0,0 +1,183 @@ +use super::file_sha256; +use crate::kv_integration::StagePrefixCachePayload; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use skippy_model_artifact::gguf::scan_gguf_compact_meta; +use skippy_model_artifact::kv_fixtures::{KV_FIXTURE_MANIFEST, Sidecar}; +use std::{collections::BTreeSet, fs, path::Path}; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "kebab-case")] +pub(super) enum Family { + DenseAttention, + HybridDense, + AttentionMoe, + HybridMoe, +} + +impl Family { + pub(super) fn parse(value: &str) -> Result { + serde_json::from_value(serde_json::Value::String(value.into())) + .with_context(|| format!("unknown qualification model family {value:?}")) + } + + pub(super) fn payload(self) -> StagePrefixCachePayload { + match self { + Self::DenseAttention | Self::AttentionMoe => StagePrefixCachePayload::ResidentKv, + Self::HybridDense | Self::HybridMoe => StagePrefixCachePayload::KvRecurrent, + } + } + + pub(super) fn has_experts(self) -> bool { + matches!(self, Self::AttentionMoe | Self::HybridMoe) + } + + pub(super) fn prefill_tokens(self, prompt_tokens: u32) -> u32 { + match self { + // The deferred recurrent path records the entire final suffix. + Self::HybridDense | Self::HybridMoe => prompt_tokens, + Self::DenseAttention | Self::AttentionMoe => prompt_tokens.saturating_sub(1), + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + schema_version: u32, + models: Vec, +} + +#[derive(Clone, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Fixture { + pub(super) family: Family, + repo: String, + revision: String, + file: String, + quantization: String, + size_bytes: u64, + sha256: String, + pub(super) chat_template_sha256: String, + license: String, + architecture: String, + pub(super) layers: u32, + required_sidecars: Vec, +} + +impl Fixture { + pub(super) fn load(family: Family) -> Result { + let manifest: Manifest = + serde_json::from_str(KV_FIXTURE_MANIFEST).context("read cache fixture manifest")?; + manifest.validate()?; + manifest + .models + .into_iter() + .find(|row| row.family == family) + .context("qualification fixture missing from manifest") + } + + pub(super) fn model_id(&self) -> String { + format!("{}:{}", self.repo, self.quantization) + } + + pub(super) fn digest(&self) -> &str { + &self.sha256 + } + + pub(super) fn verify_model(&self, path: &Path) -> Result { + let observed_bytes = fs::metadata(path)?.len(); + ensure!( + observed_bytes == self.size_bytes, + "fixture size mismatch: expected {}, observed {observed_bytes}", + self.size_bytes + ); + let digest = file_sha256(path)?; + ensure!( + digest == self.sha256, + "fixture SHA-256 mismatch: expected {}, observed {digest}", + self.sha256 + ); + let meta = scan_gguf_compact_meta(path).context("read qualified GGUF metadata")?; + ensure!( + meta.architecture == self.architecture + && meta.layer_count == self.layers + && (meta.expert_count > 0) == self.family.has_experts(), + "fixture layout disagrees with the manifest for {}", + self.model_id() + ); + Ok(digest) + } +} + +impl Manifest { + fn validate(&self) -> Result<()> { + ensure!( + self.schema_version == 2 && self.models.len() == 4, + "expected four version-2 cache fixtures" + ); + let mut families = BTreeSet::new(); + let mut identities = BTreeSet::new(); + for model in &self.models { + ensure!( + model.required_sidecars.is_empty(), + "this cache runner does not support attaching model sidecars" + ); + ensure!( + families.insert(model.family) && identities.insert(model.model_id()), + "duplicate cache fixture identity" + ); + ensure!( + hex(&model.revision, 40), + "fixture revision must be a pinned commit" + ); + ensure!( + hex(&model.sha256, 64) && hex(&model.chat_template_sha256, 64), + "fixture and chat template require SHA-256" + ); + ensure!( + model.size_bytes > 0 && model.layers > 0 && !model.architecture.is_empty(), + "fixture layout is incomplete" + ); + let (owner, name) = model + .repo + .split_once('/') + .context("fixture requires an owner and repository")?; + ensure!( + !owner.is_empty() && !name.is_empty() && !name.contains('/'), + "invalid fixture repository" + ); + ensure!( + matches!(model.quantization.as_str(), "Q4_K_M" | "UD-Q4_K_M") + && model + .file + .ends_with(&format!("-{}.gguf", model.quantization)) + && !model.file.contains(['/', '\\']), + "invalid fixture GGUF file or quantization" + ); + ensure!( + model.license == "Apache-2.0", + "fixture requires a supported SPDX license" + ); + } + Ok(()) + } +} + +fn hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +#[test] +fn cache_fixture_manifest_has_one_pinned_model_per_family() { + Fixture::load(Family::DenseAttention).unwrap(); + let mut manifest: Manifest = serde_json::from_str(KV_FIXTURE_MANIFEST).unwrap(); + manifest.models[0].revision = "main".into(); + assert!(manifest.validate().is_err()); + let mut manifest: Manifest = serde_json::from_str(KV_FIXTURE_MANIFEST).unwrap(); + manifest.models[0].family = manifest.models[1].family; + assert!(manifest.validate().is_err()); +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/ownership.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/ownership.rs new file mode 100644 index 00000000..1ce31c6d --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/ownership.rs @@ -0,0 +1,355 @@ +//! Exercise L3 ownership changes with separate operating-system processes. + +use super::{ + Backend, CandidateRunner, Family, Fixture, Report, StageConfig, + evidence::{ + CleanRestartObservation, DurableObservations, OwnershipObservation, RestartObservation, + }, + file_sha256, generation_request, messages, required_path, tiers, +}; +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use skippy_cache::CacheRootInUse; +use std::{ + env, fs, + path::{Path, PathBuf}, + process::{ExitStatus, Stdio}, + time::Duration, +}; +use tokio::{ + process::{Child, Command}, + time::{Instant, sleep, timeout}, +}; + +const PROCESS_TIMEOUT: Duration = Duration::from_secs(300); +const REQUEST_FILE: &str = "l3-process-input.json"; +const INTERRUPTED_WRITE: &str = "l3/segments/.tmp-interrupted-qualification"; + +#[derive(Clone, Copy)] +enum Phase { + Publish, + Reopen, + CleanRestart, + CrashRestart, +} + +impl Phase { + fn name(self) -> &'static str { + match self { + Self::Publish => "publish", + Self::Reopen => "reopen", + Self::CleanRestart => "clean-restart", + Self::CrashRestart => "crash-restart", + } + } +} + +#[derive(Deserialize, Serialize)] +struct ProcessInput { + config: StageConfig, + family: Family, + backend: Backend, +} + +#[derive(Deserialize, Serialize)] +struct Publication { + pid: u32, + offloaded_layers: usize, + pack_name: PathBuf, + durable: DurableObservations, +} + +pub(super) async fn observe( + directory: &Path, + config: StageConfig, + report: &mut Report, +) -> Result<()> { + let input = ProcessInput { + config, + family: report.fixture.family, + backend: report.backend, + }; + fs::write(directory.join(REQUEST_FILE), serde_json::to_vec(&input)?)?; + let (mut publisher, publisher_pid) = start(directory, Phase::Publish)?; + wait_success(&mut publisher, Phase::Publish).await?; + let publication: Publication = read_observation(directory, Phase::Publish)?; + ensure!(publisher_pid == publication.pid, "publication PID mismatch"); + report.durable = Some(publication.durable); + + let (mut owner, owner_pid) = start(directory, Phase::CleanRestart)?; + let clean_restart = wait_for_owner(directory, &mut owner).await?; + ensure!(owner_pid == clean_restart.pid, "clean restart PID mismatch"); + let pack = directory.join("l3/packs").join(publication.pack_name); + let preserved_pack_sha256 = file_sha256(&pack)?; + let error = tiers::open_store(directory).expect_err("live owner must prevent a second open"); + ensure!( + error.downcast_ref::().is_some(), + "second process failed to open L3 for an unexpected reason: {error:#}" + ); + let contender = generate_without_l3(directory, &input)?; + ensure!( + owner.try_wait()?.is_none() && file_sha256(&pack)? == preserved_pack_sha256, + "the original owner or its committed pack did not survive lock contention" + ); + report.ownership = Some(OwnershipObservation { + publisher_pid, + publisher_offloaded_layers: publication.offloaded_layers, + clean_restart, + lock_conflict: error.to_string(), + contender, + preserved_pack_sha256, + }); + + owner.start_kill()?; + let status = timeout(PROCESS_TIMEOUT, owner.wait()).await??; + ensure!( + was_killed(status), + "expected abrupt termination, got {status}" + ); + let (mut recovery, recovery_pid) = start(directory, Phase::CrashRestart)?; + wait_success(&mut recovery, Phase::CrashRestart).await?; + let restart: RestartObservation = read_observation(directory, Phase::CrashRestart)?; + ensure!(recovery_pid == restart.pid, "crash restart PID mismatch"); + report.restart = Some(restart); + Ok(()) +} + +pub(super) async fn reopen( + directory: &Path, + config: StageConfig, + family: Family, + backend: Backend, +) -> Result { + let input = ProcessInput { + config, + family, + backend, + }; + fs::write(directory.join(REQUEST_FILE), serde_json::to_vec(&input)?)?; + let (mut child, pid) = start(directory, Phase::Reopen)?; + wait_success(&mut child, Phase::Reopen).await?; + let observation: CleanRestartObservation = read_observation(directory, Phase::Reopen)?; + ensure!(pid == observation.pid, "reopened cache PID mismatch"); + Ok(observation) +} + +fn start(directory: &Path, phase: Phase) -> Result<(Child, u32)> { + let name = phase.name(); + let log = fs::File::create(directory.join(format!("l3-{name}-process.log")))?; + let child = Command::new(env::current_exe()?) + .args([ + "frontend::tests::cache_qualification::ownership::l3_owner", + "--ignored", + "--exact", + "--nocapture", + ]) + .env("SKIPPY_CACHE_QUAL_OWNER_DIR", directory.canonicalize()?) + .env("SKIPPY_CACHE_QUAL_OWNER_PHASE", name) + .stdin(Stdio::piped()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log)) + .kill_on_drop(true) + .spawn()?; + let pid = child.id().context("L3 process PID missing")?; + Ok((child, pid)) +} + +async fn wait_success(child: &mut Child, phase: Phase) -> Result<()> { + let status = timeout(PROCESS_TIMEOUT, child.wait()) + .await + .with_context(|| format!("L3 {} timed out", phase.name()))??; + ensure!( + status.success(), + "L3 {} failed with {status}. See l3-{}-process.log", + phase.name(), + phase.name() + ); + Ok(()) +} + +async fn wait_for_owner(directory: &Path, owner: &mut Child) -> Result { + let deadline = Instant::now() + PROCESS_TIMEOUT; + let path = observation_path(directory, Phase::CleanRestart); + loop { + if let Some(status) = owner.try_wait()? { + bail!("L3 owner exited early with {status}. See l3-clean-restart-process.log"); + } + if path.try_exists()? { + return read_observation(directory, Phase::CleanRestart); + } + ensure!( + Instant::now() < deadline, + "L3 owner did not report readiness" + ); + sleep(Duration::from_millis(50)).await; + } +} + +#[cfg(unix)] +fn was_killed(status: ExitStatus) -> bool { + use std::os::unix::process::ExitStatusExt; + status.signal() == Some(9) +} + +#[cfg(not(unix))] +fn was_killed(status: ExitStatus) -> bool { + !status.success() +} + +#[test] +#[ignore = "spawned by the GPU qualification to publish and reopen an exclusive L3 root"] +fn l3_owner() -> Result<()> { + let directory = required_path("SKIPPY_CACHE_QUAL_OWNER_DIR")?; + let phase = match env::var("SKIPPY_CACHE_QUAL_OWNER_PHASE")?.as_str() { + "publish" => Phase::Publish, + "reopen" => Phase::Reopen, + "clean-restart" => Phase::CleanRestart, + "crash-restart" => Phase::CrashRestart, + value => bail!("invalid L3 process phase {value}"), + }; + let input: ProcessInput = serde_json::from_slice(&fs::read(directory.join(REQUEST_FILE))?)?; + let fixture = Fixture::load(input.family)?; + ensure!( + input.config.model_id == fixture.model_id(), + "model identity mismatch" + ); + skippy_runtime::test_support::require_native_runtime(); + let native_log = directory.join(format!("l3-{}-native.log", phase.name())); + skippy_runtime::redirect_native_logs_to_file(&native_log)?; + let result = run_phase(&directory, input, &fixture, phase, &native_log); + skippy_runtime::restore_native_logs(); + result +} + +fn run_phase( + directory: &Path, + input: ProcessInput, + fixture: &Fixture, + phase: Phase, + native_log: &Path, +) -> Result<()> { + let request = generation_request(fixture, &messages())?; + let offloaded = || { + input + .backend + .offloaded_layers(&fs::read_to_string(native_log)?) + }; + let pid = std::process::id(); + if matches!(phase, Phase::Publish) { + let mut durable = DurableObservations::default(); + let pack_name = tiers::observe( + input.family, + directory, + input.config, + &request, + &mut durable, + )?; + return write_observation( + directory, + phase, + &Publication { + pid, + offloaded_layers: offloaded()?, + pack_name, + durable, + }, + ); + } + + let manager = tiers::open_store(directory)?; + let mut runner = CandidateRunner::new(input.config, input.family)?; + if matches!(phase, Phase::CleanRestart | Phase::Reopen) { + let cache = runner.enable_cache(Some(manager.clone()))?; + let replay = runner.generate(&request)?; + tiers::drain_workers(&cache)?; + drop(cache); + drop(runner); + if matches!(phase, Phase::CleanRestart) { + fs::write( + directory.join(INTERRUPTED_WRITE), + b"unpublished checkpoint bytes", + )?; + } + write_observation( + directory, + phase, + &CleanRestartObservation { + pid, + offloaded_layers: offloaded()?, + replay, + }, + )?; + if matches!(phase, Phase::Reopen) { + return Ok(()); + } + // Retain exclusive ownership until the parent deliberately kills us. + let mut line = String::new(); + let _ = std::io::stdin().read_line(&mut line)?; + drop(manager); + bail!("L3 owner exited without abrupt termination"); + } + + let publication: Publication = read_observation(directory, Phase::Publish)?; + let reconciled_temporary_files = manager.reconciliation().removed_temporary_files; + ensure!( + !directory.join(INTERRUPTED_WRITE).try_exists()?, + "reconciliation left the interrupted write in place" + ); + let (replay, corrupt_fallback, corrupt_objects) = tiers::observe_recovery( + directory, + &publication.pack_name, + &manager, + runner, + &request, + )?; + write_observation( + directory, + phase, + &RestartObservation { + pid, + offloaded_layers: offloaded()?, + replay, + corrupt_fallback, + corrupt_objects, + reconciled_temporary_files, + }, + ) +} + +fn generate_without_l3(directory: &Path, input: &ProcessInput) -> Result { + let native_log = directory.join("l3-contender-native.log"); + skippy_runtime::redirect_native_logs_to_file(&native_log)?; + let result = (|| { + let fixture = Fixture::load(input.family)?; + let mut runner = CandidateRunner::new(input.config.clone(), input.family)?; + let cache = runner.enable_cache(None)?; + ensure!( + cache.l3.is_none() && cache.l2.is_none(), + "contender attached to durable state" + ); + runner.generate(&generation_request(&fixture, &messages())?) + })(); + skippy_runtime::restore_native_logs(); + input + .backend + .offloaded_layers(&fs::read_to_string(native_log)?)?; + result +} + +fn observation_path(directory: &Path, phase: Phase) -> PathBuf { + directory.join(format!("l3-{}-observation.json", phase.name())) +} + +fn write_observation(directory: &Path, phase: Phase, value: &impl Serialize) -> Result<()> { + let path = observation_path(directory, phase); + let temp = path.with_extension("tmp"); + fs::write(&temp, serde_json::to_vec(value)?)?; + fs::rename(temp, path)?; + Ok(()) +} + +fn read_observation(directory: &Path, phase: Phase) -> Result { + let path = observation_path(directory, phase); + let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?; + Ok(serde_json::from_slice(&bytes)?) +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/reference.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/reference.rs new file mode 100644 index 00000000..b4aa48de --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/reference.rs @@ -0,0 +1,331 @@ +use super::conversation::Case; +use super::evidence::{Generation, Reference, TokenScore}; +use super::{ + BATCH_TOKENS, Backend, CONTEXT_TOKENS, Fixture, LLAMA_PIN, MAX_TOKENS, TIMEOUT, TOP_K, + file_sha256, required_path, sha256, structured, +}; +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, fs, net::TcpListener, path::Path, process::Stdio, time::Duration, +}; +use tokio::{ + process::Command, + time::{Instant, sleep, timeout}, +}; + +// Large pinned fixtures may load from shared storage. Keep this separate from +// the request deadline so slow initialization does not weaken generation checks. +const STARTUP_TIMEOUT: Duration = Duration::from_secs(600); + +pub(super) async fn observe( + backend: Backend, + directory: &Path, + model: &Path, + fixture: &Fixture, + messages: &Value, +) -> Result { + let binary = required_path("SKIPPY_CACHE_QUAL_LLAMA_SERVER")?.canonicalize()?; + let binary_sha256 = file_sha256(&binary)?; + let version = timeout( + Duration::from_secs(15), + Command::new(&binary) + .arg("--version") + .kill_on_drop(true) + .output(), + ) + .await + .context("llama-server --version timed out")??; + ensure!(version.status.success(), "llama-server --version failed"); + let version = format!( + "{}{}", + String::from_utf8_lossy(&version.stdout), + String::from_utf8_lossy(&version.stderr) + ); + ensure!( + version_matches(&version, LLAMA_PIN.trim()), + "llama-server does not identify the pinned upstream commit {}: {}", + LLAMA_PIN.trim(), + version.trim() + ); + + let socket = TcpListener::bind(("127.0.0.1", 0))?; + let port = socket.local_addr()?.port(); + let base = format!("http://127.0.0.1:{port}"); + let log_path = directory.join("llama-server.log"); + let log = fs::File::create(&log_path)?; + drop(socket); + let mut child = Command::new(&binary) + .arg("--model") + .arg(model) + .arg("--alias") + .arg(fixture.model_id()) + .args(["--host", "127.0.0.1", "--port", &port.to_string()]) + .args(["--ctx-size", &CONTEXT_TOKENS.to_string()]) + .args([ + "--batch-size", + &BATCH_TOKENS.to_string(), + "--ubatch-size", + &BATCH_TOKENS.to_string(), + ]) + .args([ + "--n-gpu-layers", + "all", + "--parallel", + "1", + "--flash-attn", + "off", + "--fit", + "off", + "--kv-unified", + "--cache-type-k", + "f16", + "--cache-type-v", + "f16", + "--no-context-shift", + "--jinja", + "--cache-ram", + "0", + "--ctx-checkpoints", + "0", + "--verbose", + ]) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log)) + .kill_on_drop(true) + .spawn() + .context("start pinned llama-server")?; + + let client = reqwest::Client::builder() + .no_proxy() + .timeout(TIMEOUT) + .build()?; + let result = async { + let deadline = Instant::now() + STARTUP_TIMEOUT; + loop { + if let Some(status) = child.try_wait()? { + anyhow::bail!("llama-server exited before readiness: {status}"); + } + let response = client + .get(format!("{base}/health")) + .timeout(Duration::from_secs(2)) + .send() + .await; + if response.is_ok_and(|response| response.status().is_success()) { + break; + } + ensure!( + Instant::now() < deadline, + "timeout waiting for llama-server readiness" + ); + sleep(Duration::from_millis(200)).await; + } + let layers = backend.offloaded_layers(&fs::read_to_string(&log_path)?)?; + let props: Props = client + .get(format!("{base}/props")) + .send() + .await? + .error_for_status()? + .json() + .await?; + ensure!( + !props.chat_template.is_empty(), + "llama-server returned an empty chat template" + ); + let generation = observe_generation(&client, &base, messages).await?; + let mut conversations = BTreeMap::new(); + for case in Case::ALL { + let generation = observe_generation(&client, &base, &case.messages()) + .await + .with_context(|| format!("llama.cpp {case:?}"))?; + conversations.insert(case, generation); + } + let mut structured = BTreeMap::new(); + for case in structured::Case::ALL { + let mut request = case.request(&fixture.model_id()); + request["cache_prompt"] = json!(false); + let result = post(&client, &base, "/v1/chat/completions", request).await; + structured.insert(case, structured::Attempt::reference(result)); + } + ensure!( + !fs::read_to_string(&log_path)?.contains("created context checkpoint"), + "llama-server created a context checkpoint during cold inference" + ); + ensure!( + child.try_wait()?.is_none(), + "llama-server exited during inference" + ); + ensure!( + file_sha256(&binary)? == binary_sha256, + "llama-server executable changed during inference" + ); + Ok(Reference { + binary_sha256, + version, + offloaded_layers: layers, + template_sha256: sha256(props.chat_template.as_bytes()), + generation, + conversations, + structured, + }) + } + .await; + let shutdown = child + .kill() + .await + .context("stop llama-server and reclaim device resources"); + result.and_then(|observation| { + shutdown?; + Ok(observation) + }) +} + +pub(super) fn version_matches(version: &str, expected: &str) -> bool { + version.lines().any(|line| { + line.starts_with("version: ") + && line + .split_once("commit ") + .and_then(|(_, value)| value.strip_suffix(')')) + .is_some_and(|commit| commit.len() >= 7 && expected.starts_with(commit)) + }) +} + +async fn observe_generation( + client: &reqwest::Client, + base: &str, + messages: &Value, +) -> Result { + let template: Rendered = post( + client, + base, + "/apply-template", + json!({ + "messages": messages, + "chat_template_kwargs": {"enable_thinking": false, "preserve_reasoning": false} + }), + ) + .await?; + let tokenized: Tokenized = post( + client, + base, + "/tokenize", + json!({ + "content": template.prompt, "add_special": true, "parse_special": true + }), + ) + .await?; + let completion: Completion = post( + client, + base, + "/completion", + json!({ + "prompt": &tokenized.tokens, "n_predict": MAX_TOKENS, + "temperature": -1, "seed": 1, "cache_prompt": false, + "return_tokens": true, "n_probs": TOP_K, "post_sampling_probs": false + }), + ) + .await?; + ensure!( + !completion.truncated + && completion.tokens_evaluated == tokenized.tokens.len() + && completion.timings.cache_n == 0 + && completion.timings.prompt_n == tokenized.tokens.len(), + "llama-server did not evaluate the entire input cold" + ); + ensure!( + completion + .completion_probabilities + .iter() + .map(|row| row.id) + .eq(completion.tokens.iter().copied()), + "llama-server probability rows do not align with generated token IDs" + ); + Ok(Generation { + prompt_sha256: sha256(template.prompt.as_bytes()), + prompt_ids: tokenized.tokens, + generated_ids: completion.tokens, + content: completion.content, + raw_content: None, + top_logprobs: completion + .completion_probabilities + .into_iter() + .map(|row| row.top_logprobs) + .collect(), + }) +} + +async fn post( + client: &reqwest::Client, + base: &str, + route: &str, + body: Value, +) -> Result { + let response = client + .post(format!("{base}{route}")) + .json(&body) + .send() + .await?; + let status = response.status(); + let raw = response.bytes().await?; + ensure!( + status.is_success(), + "llama-server {route} returned {status}: {}", + String::from_utf8_lossy(&raw) + ); + serde_json::from_slice(&raw).with_context(|| format!("decode llama-server {route} response")) +} + +#[derive(Deserialize)] +struct Props { + chat_template: String, +} + +#[derive(Deserialize)] +struct Rendered { + prompt: String, +} + +#[derive(Deserialize)] +struct Tokenized { + tokens: Vec, +} + +#[derive(Deserialize)] +struct Completion { + content: String, + tokens: Vec, + tokens_evaluated: usize, + timings: Timings, + truncated: bool, + completion_probabilities: Vec, +} + +#[derive(Deserialize)] +struct Distribution { + id: i32, + top_logprobs: Vec, +} + +#[derive(Deserialize)] +struct Timings { + cache_n: usize, + prompt_n: usize, +} + +#[test] +fn reference_version_requires_pinned_commit() { + let pin = "8954f194837d2ec4d5f67f20c81b84abe63883ba"; + assert!(version_matches( + "version: 1 (build 3, commit 8954f1948)\nbuilt with clang", + pin + )); + assert!(!version_matches( + "version: 1 (build 3, commit 895)\nbuilt with clang", + pin + )); + assert!(!version_matches( + "version: 1 (build 3, commit 1234567)\nbuilt with clang", + pin + )); +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs new file mode 100644 index 00000000..7e290a88 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/smoke.rs @@ -0,0 +1,103 @@ +use super::{ + Backend, CandidateRunner, EXPECTED_CODE, Family, Fixture, Report, Status, evidence, + file_sha256, generation_request, messages, ownership, required_path, stage_config, tiers, +}; +use anyhow::{Context, Result, ensure}; +use serde_json::json; +use std::{env, fs, path::Path}; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires the pinned dense fixture and actual qualification hardware"] +async fn packaged_cache_smoke() -> Result<()> { + let directory = required_path("SKIPPY_CACHE_QUAL_REPORT_DIR")?; + fs::create_dir(&directory)?; + let backend = Backend::selected()?; + let fixture = Fixture::load(Family::DenseAttention)?; + let mut report = Report::new(backend, fixture); + let result = observe(&directory, &mut report).await; + match &result { + Ok(()) => report.status = Status::Pass, + Err(error) => report.error = Some(format!("{error:#}")), + } + fs::write( + directory.join("smoke-result.json"), + serde_json::to_vec_pretty(&report)?, + )?; + result +} + +async fn observe(directory: &Path, report: &mut Report) -> Result<()> { + let backend = report.backend; + backend.require_host()?; + skippy_runtime::test_support::require_native_runtime(); + let model = required_path("SKIPPY_CACHE_QUAL_MODEL")?.canonicalize()?; + let fixture = &report.fixture; + let family = fixture.family; + let digest = fixture.verify_model(&model)?; + report.model_sha256 = Some(digest.clone()); + report.skippy_binary_sha256 = Some(file_sha256(&env::current_exe()?)?); + let config = stage_config(fixture, &model, &digest)?; + let request = generation_request(fixture, &messages())?; + let log = directory.join("skippy-native.log"); + skippy_runtime::redirect_native_logs_to_file(&log)?; + let observed = (|| { + let manager = tiers::open_store(directory)?; + ensure!(manager.inventory()?.is_empty(), "new L3 store is not empty"); + let mut runner = CandidateRunner::new(config.clone(), family)?; + report.cold = Some(runner.generate(&request)?); + let cache = runner.enable_cache(Some(manager.clone()))?; + report.seed = Some(runner.generate(&request)?); + let checkpoint = tiers::published_checkpoint( + family, + &manager, + report.seed.as_ref().context("missing cache seed")?, + )?; + report.replay = Some(runner.generate(&request)?); + tiers::drain_workers(&cache)?; + tiers::evict_l1(&runner, &cache)?; + Ok::<_, anyhow::Error>(checkpoint) + })(); + skippy_runtime::restore_native_logs(); + let checkpoint = observed?; + report.skippy_offloaded_layers = Some(backend.offloaded_layers(&fs::read_to_string(log)?)?); + evidence::validate_l1(report)?; + let cold = &report + .cold + .as_ref() + .context("missing cold generation")? + .generation; + let seed = &report + .seed + .as_ref() + .context("missing cache seed")? + .generation; + let warm = &report + .replay + .as_ref() + .context("missing L1 replay")? + .generation; + evidence::compare(cold, seed, EXPECTED_CODE).context("seed output")?; + evidence::compare(cold, warm, EXPECTED_CODE).context("L1 output")?; + + let restarted = ownership::reopen(directory, config, family, backend).await?; + ensure!( + restarted.pid != std::process::id(), + "L3 was not reopened in a fresh process" + ); + evidence::validate_durable_replay( + u32::try_from(cold.prompt_ids.len())?, + &restarted.replay, + "l3", + checkpoint, + )?; + evidence::compare(cold, &restarted.replay.generation, EXPECTED_CODE).context("L3 output")?; + ensure!( + file_sha256(&model)? == digest, + "fixture changed during the run" + ); + fs::write( + directory.join("smoke-checkpoint.json"), + serde_json::to_vec_pretty(&json!({"checkpoint_tokens": checkpoint}))?, + )?; + Ok(()) +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/structured.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/structured.rs new file mode 100644 index 00000000..0a9ab910 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/structured.rs @@ -0,0 +1,395 @@ +//! Check parsed OpenAI output and cache accounting against explicit answers. + +use super::{CandidateRunner, Family, Fixture, evidence::Status, tiers}; +use crate::kv_integration::KvStageIntegration; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use skippy_inference_api::{ + InferenceBackend, InferenceRequestContext, + chat::{ChatCompletionRequest, ChatCompletionResponse}, + generation::GenerationRequest, +}; +use std::{collections::BTreeMap, fmt::Write as _}; + +const CODE: u32 = 1729; +const TOOL_NAME: &str = "record_code"; +const MIN_LONG_PROMPT_TOKENS: u64 = 4096; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Case { + JsonSchema, + NamedTool, + LongRetrieval, +} + +impl Case { + pub(super) const ALL: [Self; 3] = [Self::JsonSchema, Self::NamedTool, Self::LongRetrieval]; + + pub(super) fn request(self, model: &str) -> Value { + let mut schema = json!({ + "type": "object", "properties": {"code": {"type": "integer"}}, + "required": ["code"], "additionalProperties": false, + }); + let message = match self { + Self::JsonSchema => { + super::user_content("Return a JSON object with the integer code 1729.") + } + Self::NamedTool => super::user_content("Call record_code with the integer code 1729."), + Self::LongRetrieval => retrieval_prompt(), + }; + if self == Self::JsonSchema { + schema["properties"]["code"]["const"] = json!(CODE); + } + let mut request = json!({ + "model": model, "messages": [{"role": "user", "content": message}], + "temperature": 0, "seed": 1, "max_tokens": 128, "reasoning_effort": "none", + }); + if self == Self::NamedTool { + request["tools"] = json!([{ + "type": "function", + "function": {"name": TOOL_NAME, "description": "Record the provided code.", "parameters": schema}, + }]); + request["tool_choice"] = json!({"type":"function", "function":{"name":TOOL_NAME}}); + } else { + request["response_format"] = json!({ + "type": "json_schema", "json_schema": {"name": "lookup", "strict": true, "schema": schema}, + }); + } + request + } + + fn minimum_prompt_tokens(self) -> u64 { + if self == Self::LongRetrieval { + MIN_LONG_PROMPT_TOKENS + } else { + 64 + } + } +} + +fn retrieval_prompt() -> String { + let mut prompt = String::from("The access code for Harbor is 1729.\n"); + for row in 0..240 { + writeln!( + prompt, + "Archive record {row:03}: miscellaneous harbor maintenance notes. Check the beacon housing, safety rails, water level, and west pier signs." + ) + .expect("appending to a string is infallible"); + } + prompt.push_str("Retrieve the Harbor access code from the first line. Put that code in the JSON field code as an integer."); + prompt +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "snake_case", tag = "outcome")] +pub(super) enum Attempt { + Captured { + response: Value, + prompt_digest: Option, + hit_kind: Option, + restore_source: Option, + payload_kind: Option, + }, + Error { + error: String, + }, +} + +impl Attempt { + pub(super) fn reference(result: Result) -> Self { + match result { + Ok(response) => Self::Captured { + response, + prompt_digest: None, + hit_kind: None, + restore_source: None, + payload_kind: None, + }, + Err(error) => Self::Error { + error: format!("{error:#}"), + }, + } + } +} + +pub(super) struct Prepared { + case: Case, + request: GenerationRequest, + context: InferenceRequestContext, + cold: Attempt, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct Observation { + cold: Attempt, + seed: Attempt, + warm: Attempt, +} + +#[derive(Serialize)] +pub(super) struct ResultRow { + pub(super) status: Status, + pub(super) errors: Vec, +} + +pub(super) async fn observe_cold( + fixture: &Fixture, + runner: &CandidateRunner, +) -> Result> { + let mut prepared = Vec::new(); + for case in Case::ALL { + let request: GenerationRequest = + serde_json::from_value::(case.request(&fixture.model_id()))? + .into(); + let context = tiers::isolated_context(); + let cold = observe(runner, &request, &context).await; + prepared.push(Prepared { + case, + request, + context, + cold, + }); + } + Ok(prepared) +} + +pub(super) async fn observe_warm( + prepared: Vec, + runner: &CandidateRunner, + cache: &KvStageIntegration, + observations: &mut BTreeMap, +) -> Result<()> { + for Prepared { + case, + request, + context, + cold, + } in prepared + { + tiers::drain_workers(cache)?; + let seed = observe(runner, &request, &context).await; + tiers::drain_workers(cache)?; + let warm = observe(runner, &request, &context).await; + observations.insert(case, Observation { cold, seed, warm }); + } + Ok(()) +} + +async fn observe( + runner: &CandidateRunner, + request: &GenerationRequest, + context: &InferenceRequestContext, +) -> Attempt { + let result = runner + .backend + .chat_completion_with_context(request.clone(), context.clone()) + .await; + // The cache-disabled scheduler can finish after its session is dropped. + // The start observation captures the actual prompt for either driver. + let start = runner.starts.try_recv(); + let _ = runner.receipts.try_recv(); + let mut cache = super::evidence::CacheObservation::default(); + let restore = runner.observe_restore(&mut cache); + let observation = (|| -> Result { + let response = ChatCompletionResponse::from(result?); + let start = start.context("missing native start for structured output")?; + ensure!( + start.prompt_token_ids.len() == response.usage.prompt_tokens as usize, + "structured response usage disagrees with the native prompt" + ); + let mut digest = Sha256::new(); + for token in start.prompt_token_ids.iter() { + digest.update(token.to_le_bytes()); + } + restore?; + Ok(Attempt::Captured { + response: serde_json::to_value(response)?, + prompt_digest: Some(super::hex_digest(&digest.finalize())), + hit_kind: cache.hit_kind, + restore_source: cache.restore_source, + payload_kind: cache.payload_kind, + }) + })(); + observation.unwrap_or_else(|error| Attempt::Error { + error: format!("{error:#}"), + }) +} + +pub(super) fn validate( + family: Family, + observed: &BTreeMap, +) -> BTreeMap { + Case::ALL + .into_iter() + .map(|case| { + let result = (|| -> Result> { + let observed = observed + .get(&case) + .context("missing Skippy structured responses")?; + Ok(validate_attempts(case, family, observed)) + })(); + let errors = result.unwrap_or_else(|error| vec![format!("{error:#}")]); + let status = if errors.is_empty() { + Status::Pass + } else { + Status::Fail + }; + (case, ResultRow { status, errors }) + }) + .collect() +} + +fn validate_attempts(case: Case, family: Family, observed: &Observation) -> Vec { + [ + ("Skippy cold", &observed.cold, true, false), + ("Skippy seed", &observed.seed, true, false), + ("Skippy warm", &observed.warm, true, true), + ] + .into_iter() + .filter_map(|(label, attempt, candidate, warm)| { + validate_attempt( + case, + family, + attempt, + candidate.then_some(&observed.cold), + warm, + ) + .err() + .map(|error| format!("{label} {case:?}: {error:#}")) + }) + .collect() +} + +fn validate_attempt( + case: Case, + family: Family, + attempt: &Attempt, + baseline: Option<&Attempt>, + warm: bool, +) -> Result<()> { + let (response, prompt_digest, hit_kind, restore_source, payload_kind) = match attempt { + Attempt::Captured { + response, + prompt_digest, + hit_kind, + restore_source, + payload_kind, + } => ( + response, + prompt_digest, + hit_kind, + restore_source, + payload_kind, + ), + Attempt::Error { error } => anyhow::bail!("{error}"), + }; + validate_answer(case, response)?; + let prompt = response["usage"]["prompt_tokens"] + .as_u64() + .context("missing prompt-token usage")?; + let cached = response["usage"]["prompt_tokens_details"]["cached_tokens"] + .as_u64() + .context("missing cache-token usage")?; + ensure!( + prompt >= case.minimum_prompt_tokens(), + "prompt contains only {prompt} tokens" + ); + if let Some(cold) = baseline { + let Attempt::Captured { + prompt_digest: Some(expected), + .. + } = cold + else { + anyhow::bail!("missing cold Skippy prompt token digest"); + }; + ensure!( + prompt_digest.as_ref() == Some(expected), + "Skippy prompt token digest changed" + ); + } + if !warm { + ensure!(cached == 0, "cold response reused {cached} tokens"); + return Ok(()); + } + let prefill = u64::from(family.prefill_tokens(u32::try_from(prompt)?)); + ensure!( + cached >= 64 && cached <= prefill, + "expected L1 reuse, observed {cached} cached tokens" + ); + ensure!( + response["timings"]["suffix_prefill_n"].as_u64() == Some(prompt - cached), + "suffix prefill does not match cached-token accounting" + ); + let recurrent = family.payload() == crate::kv_integration::StagePrefixCachePayload::KvRecurrent; + if recurrent { + ensure!( + hit_kind.as_deref() == Some("resident_prefix") + || (restore_source.as_deref() == Some("radix") + && payload_kind.as_deref() == Some("kv-recurrent")), + "expected complete L1 KV and recurrent state" + ); + } else { + ensure!( + restore_source.is_none() && cached == prefill, + "expected full resident L1 prefix" + ); + } + Ok(()) +} + +fn validate_answer(case: Case, response: &Value) -> Result<()> { + let choices = response["choices"] + .as_array() + .context("missing chat choices")?; + ensure!(choices.len() == 1, "expected one chat choice"); + let choice = &choices[0]; + let message = &choice["message"]; + let answer = if case == Case::NamedTool { + ensure!( + choice["finish_reason"] == "tool_calls", + "named tool call did not finish" + ); + let calls = message["tool_calls"] + .as_array() + .context("missing parsed tool calls")?; + ensure!( + calls.len() == 1 + && calls[0]["type"] == "function" + && calls[0]["function"]["name"] == TOOL_NAME, + "expected one call to {TOOL_NAME}" + ); + calls[0]["function"]["arguments"] + .as_str() + .context("missing tool arguments")? + } else { + ensure!( + choice["finish_reason"] == "stop", + "JSON response did not finish" + ); + message["content"] + .as_str() + .context("missing JSON response content")? + }; + ensure!( + serde_json::from_str::(answer)? == json!({"code": CODE}), + "wrong structured answer {answer:?}" + ); + Ok(()) +} + +#[test] +fn structured_contract_rejects_wrong_answers_and_incomplete_tool_calls() { + let json_response = + |content: &str| json!({"choices":[{"finish_reason":"stop","message":{"content":content}}]}); + assert!(validate_answer(Case::LongRetrieval, &json_response(r#"{"code": 1729}"#)).is_ok()); + assert!(validate_answer(Case::LongRetrieval, &json_response(r#"{"code": 42}"#)).is_err()); + let mut tool = json!({"choices":[{"finish_reason":"tool_calls","message":{"tool_calls":[ + {"type":"function","function":{"name":"record_code","arguments":"{\"code\":1729}"}} + ]}}]}); + assert!(validate_answer(Case::NamedTool, &tool).is_ok()); + tool["choices"][0]["finish_reason"] = json!("length"); + assert!(validate_answer(Case::NamedTool, &tool).is_err()); +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs new file mode 100644 index 00000000..e10db136 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/template.rs @@ -0,0 +1,150 @@ +use super::{ + Backend, CandidateRunner, EXPECTED_CODE, Family, Fixture, StageConfig, + evidence::{Candidate, compare, validate_durable_replay, validate_miss}, + generation_request, messages, required_path, stage_config, tiers, +}; +use crate::frontend::EmbeddedOpenAiRequestDefaults; +use anyhow::{Context, Result, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::{env, fs, path::Path}; + +const BODY: &str = concat!( + "{% for message in messages %}", + "{{ '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}", + "{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" +); + +#[derive(Default, Deserialize, Serialize)] +pub(super) struct Observation { + offloaded_layers: Option, + checkpoint: Option, + cold: Option, + seed: Option, + restored: Vec, + revised: Option, + revised_disk_payload_bytes: Option, +} + +impl Observation { + pub(super) fn validate(&self) -> Result<()> { + ensure!( + self.offloaded_layers.is_some_and(|layers| layers > 0), + "template case lacks GPU offload evidence" + ); + let cold = self + .cold + .as_ref() + .context("missing cold template observation")?; + let seed = self.seed.as_ref().context("missing template seed")?; + let checkpoint = self.checkpoint.context("missing template checkpoint")?; + let prompt_tokens = u32::try_from(cold.generation.prompt_ids.len())?; + validate_miss(prompt_tokens, seed).context("original template seed")?; + compare(&cold.generation, &seed.generation, EXPECTED_CODE) + .context("original template seed")?; + ensure!( + self.restored.len() == 3, + "incomplete template restore sequence" + ); + for (source, replay) in ["l3", "l3", "l2"].into_iter().zip(&self.restored) { + validate_durable_replay(prompt_tokens, replay, source, checkpoint) + .with_context(|| format!("original template {source} restore"))?; + compare(&cold.generation, &replay.generation, EXPECTED_CODE) + .with_context(|| format!("original template {source} output"))?; + } + let revised = self + .revised + .as_ref() + .context("missing revised template observation")?; + validate_miss(prompt_tokens, revised).context("revised template prefill")?; + compare(&cold.generation, &revised.generation, EXPECTED_CODE) + .context("revised template output")?; + ensure!( + self.revised_disk_payload_bytes == Some(0), + "a changed renderer read a stale disk payload" + ); + println!( + "Equivalent template revision missed all tiers for {prompt_tokens} identical tokens" + ); + Ok(()) + } +} + +#[test] +#[ignore = "requires a pinned model and the selected cache qualification GPU"] +fn equivalent_renderers_do_not_share_state() -> Result<()> { + let backend = Backend::selected()?; + backend.require_host()?; + let family = env::var("SKIPPY_CACHE_QUAL_FAMILY") + .map_or(Ok(Family::DenseAttention), |family| Family::parse(&family))?; + let fixture = Fixture::load(family)?; + let model = required_path("SKIPPY_CACHE_QUAL_MODEL")?.canonicalize()?; + let model_sha256 = fixture.verify_model(&model)?; + let directory = required_path("SKIPPY_CACHE_QUAL_REPORT_DIR")?; + let config = stage_config(&fixture, &model, &model_sha256)?; + let mut observation = Observation::default(); + capture(&directory, backend, config, &fixture, &mut observation)?; + observation.validate() +} + +pub(super) fn capture( + directory: &Path, + backend: Backend, + config: StageConfig, + fixture: &Fixture, + observation: &mut Observation, +) -> Result<()> { + fs::create_dir(directory)?; + let config = tiers::with_host_cache(config)?; + let mut original = generation_request(fixture, &messages())?; + original.extra.insert("chat_template".into(), json!(BODY)); + let mut revised = original.clone(); + revised.extra.insert( + "chat_template".into(), + json!(format!("{{# an equivalent revision #}}{BODY}")), + ); + let native_log = directory.join("template-native.log"); + skippy_runtime::redirect_native_logs_to_file(&native_log)?; + let result = (|| { + let mut runner = CandidateRunner::new(config, fixture.family)?; + runner.backend.request_defaults = EmbeddedOpenAiRequestDefaults { + allow_request_chat_template: Some(true), + ..Default::default() + } + .into(); + observe(directory, runner, &original, &revised, observation) + })(); + skippy_runtime::restore_native_logs(); + result?; + observation.offloaded_layers = + Some(backend.offloaded_layers(&fs::read_to_string(native_log)?)?); + Ok(()) +} + +fn observe( + directory: &Path, + mut runner: CandidateRunner, + original: &skippy_inference_api::generation::GenerationRequest, + revised: &skippy_inference_api::generation::GenerationRequest, + observation: &mut Observation, +) -> Result<()> { + observation.cold = Some(runner.generate(original)?); + let manager = tiers::open_store(directory)?; + let cache = runner.enable_cache(Some(manager.clone()))?; + let seed = observation.seed.insert(runner.generate(original)?); + observation.checkpoint = Some(tiers::published_checkpoint(runner.family, &manager, seed)?); + tiers::evict_l1(&runner, &cache)?; + for attempt in 0..3 { + if attempt > 0 { + tiers::evict_l1(&runner, &cache)?; + } + observation.restored.push(runner.generate(original)?); + tiers::drain_workers(&cache)?; + } + let disk_before = manager.activity()?.bytes_read; + observation.revised = Some(runner.generate(revised)?); + observation.revised_disk_payload_bytes = + manager.activity()?.bytes_read.checked_sub(disk_before); + tiers::drain_workers(&cache)?; + Ok(()) +} diff --git a/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs b/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs new file mode 100644 index 00000000..ebbeaec5 --- /dev/null +++ b/crates/skippy-serving/src/frontend/tests/cache_qualification/tiers.rs @@ -0,0 +1,233 @@ +use super::evidence::{Candidate, DurableObservations}; +use super::{CandidateRunner, Family, StageConfig}; +use crate::{kv_integration::KvStageIntegration, runtime_state::panic_recovery::lock_runtime}; +use anyhow::{Context, Result, anyhow, ensure}; +use skippy_cache::{L3CacheManager, StoreLimits}; +use skippy_inference_api::{ + InferenceExecutionLease, InferenceExecutionScope, InferenceRequestContext, + generation::GenerationRequest, +}; +use std::{ + ffi::OsStr, + fs, + path::{Path, PathBuf}, + sync::Arc, + thread, + time::{Duration, Instant}, +}; + +const STORE_LIMIT: u64 = 2 * 1024 * 1024 * 1024; +const HOST_LIMIT: u64 = 256 * 1024 * 1024; +const WORKER_TIMEOUT: Duration = Duration::from_secs(15); + +pub(super) fn observe( + family: Family, + directory: &Path, + config: StageConfig, + request: &GenerationRequest, + observations: &mut DurableObservations, +) -> Result { + let config = with_host_cache(config)?; + let manager = open_store(directory)?; + ensure!(manager.inventory()?.is_empty(), "new L3 store is not empty"); + let mut runner = CandidateRunner::new(config, family)?; + let cache = runner.enable_cache(Some(manager.clone()))?; + let host = cache + .l2 + .as_ref() + .context("loaded runtime did not admit L2")?; + + let seed = observations.seed.insert(runner.generate(request)?); + let checkpoint = published_checkpoint(family, &manager, seed)?; + observations.evictions.push(evict_l1(&runner, &cache)?); + observations.checkpoint_tokens = Some(checkpoint); + let pack_name = published_pack_name(directory, &cache, checkpoint)?; + + // For shorter checkpoints the production host policy promotes after + // two disk fills. Drain L1 before each fill while retaining the same L2. + observations.first_l3 = Some(runner.generate(request)?); + observations.evictions.push(evict_l1(&runner, &cache)?); + observations.second_l3 = Some(runner.generate(request)?); + drain_workers(&cache)?; + ensure!( + host.stats().entries > 0, + "L3 fills did not publish a host-RAM entry" + ); + + observations.evictions.push(evict_l1(&runner, &cache)?); + let disk_before = manager.activity()?.bytes_read; + observations.l2 = Some(runner.generate(request)?); + let disk_after = manager.activity()?.bytes_read; + observations.l2_disk_payload_bytes = Some(disk_after.saturating_sub(disk_before)); + drain_workers(&cache)?; + + let scope = isolated_context(); + observations.namespace_miss = Some(runner.generate_with_context(request, &scope)?); + drain_workers(&cache)?; + Ok(pack_name) +} + +pub(super) fn published_checkpoint( + family: Family, + manager: &L3CacheManager, + seed: &Candidate, +) -> Result { + let prefill = family.prefill_tokens(u32::try_from(seed.generation.prompt_ids.len())?); + let tokens = seed + .chat_checkpoint_tokens + .map(u64::from) + .unwrap_or(u64::from(prefill)); + wait_for_checkpoint(manager, tokens)?; + Ok(u32::try_from(tokens)?) +} + +#[derive(Debug)] +struct QualificationLease; + +impl InferenceExecutionLease for QualificationLease {} + +pub(super) fn isolated_context() -> InferenceRequestContext { + InferenceRequestContext::new() + .with_execution_scope(InferenceExecutionScope::new(), Arc::new(QualificationLease)) +} + +pub(super) fn with_host_cache(mut config: StageConfig) -> Result { + config + .kv_cache + .as_mut() + .context("missing cache configuration")? + .l2_max_bytes = HOST_LIMIT; + Ok(config) +} + +pub(super) fn open_store(directory: &Path) -> Result { + L3CacheManager::acquire( + directory.canonicalize()?.join("l3"), + StoreLimits::new(STORE_LIMIT, 0), + ) +} + +fn published_pack_name( + directory: &Path, + cache: &KvStageIntegration, + checkpoint: u32, +) -> Result { + let store = cache.l3.as_ref().context("missing disk tier")?.store(); + let manifests = store.list_manifests()?; + let [manifest] = manifests.as_slice() else { + anyhow::bail!("expected one manifest in the fresh qualification store"); + }; + ensure!( + store.load_manifest(manifest)?.token_count == u64::from(checkpoint), + "published manifest has the wrong checkpoint length" + ); + // The isolated store has one checkpoint. A raw pack is named by its + // content digest, which can differ from the manifest digest. + let mut packs = fs::read_dir(directory.join("l3/packs"))?; + let pack = packs.next().context("missing qualification pack")??; + let name = PathBuf::from(pack.file_name()); + ensure!( + packs.next().is_none() + && pack.file_type()?.is_file() + && name.extension() == Some(OsStr::new("pack")), + "expected one packed object for the qualification checkpoint" + ); + Ok(name) +} + +pub(super) fn wait_for_checkpoint(manager: &L3CacheManager, tokens: u64) -> Result<()> { + let deadline = Instant::now() + WORKER_TIMEOUT; + loop { + if manager + .inventory()? + .iter() + .any(|entry| entry.token_count == tokens && entry.total_bytes > 0) + { + return Ok(()); + } + ensure!( + Instant::now() < deadline, + "L3 checkpoint with {tokens} tokens was not published: {:?}", + manager.activity()? + ); + thread::sleep(Duration::from_millis(10)); + } +} + +pub(super) fn drain_workers(cache: &KvStageIntegration) -> Result<()> { + cache + .wait_for_exact_state_captures_idle(WORKER_TIMEOUT) + .map_err(|error| anyhow!(error))?; + cache + .wait_for_exact_state_recording(WORKER_TIMEOUT) + .map_err(|error| anyhow!(error)) +} + +pub(super) fn evict_l1( + runner: &CandidateRunner, + cache: &KvStageIntegration, +) -> Result { + drain_workers(cache)?; + // Drive production resident eviction so native sequences and ownership + // counters are released together. Both L1 representations must be gone. + let session_id = "cache-qualification-eviction"; + let mut runtime = lock_runtime(&runner.backend.runtime); + runtime.ensure_session_active(session_id)?; + let resident = cache.evict_resident_prefix_for_tokens(&mut runtime, session_id, u64::MAX); + runtime.drop_session_timed(session_id)?; + let resident = resident?; + drop(runtime); + + let mut radix = cache.radix.lock().unwrap(); + let exact = std::iter::from_fn(|| radix.evict_lru_recurrent()) + .map(|entry| entry.value.payload) + .collect::>(); + let stats = radix.stats(); + drop(radix); + let mut blobs = cache.exact_blobs.lock().unwrap(); + for payload in &exact { + payload.release_from(&mut blobs)?; + } + ensure!( + stats.resident_entries == 0 && stats.recurrent_entries == 0, + "L1 entries survived forced eviction" + ); + Ok(super::evidence::Eviction { + resident_entries: resident.evicted_entries, + exact_entries: exact.len(), + }) +} + +pub(super) fn observe_recovery( + directory: &Path, + pack_name: &Path, + manager: &L3CacheManager, + mut runner: CandidateRunner, + request: &GenerationRequest, +) -> Result<(Candidate, Candidate, u64)> { + let cache = runner.enable_cache(Some(manager.clone()))?; + let replay = runner.generate(request)?; + evict_l1(&runner, &cache)?; + + ensure!( + pack_name.components().count() == 1 && pack_name.extension() == Some(OsStr::new("pack")), + "expected a packed object name in the qualification store" + ); + let pack = directory.join("l3/packs").join(pack_name); + ensure!( + fs::symlink_metadata(&pack)?.file_type().is_file(), + "cache pack is not a regular file" + ); + // The isolated test root has no other readers or writers. Damage the + // actual on-disk object after the successful restore, leaving its index + // in place so the serving lookup is responsible for detecting damage. + let corrupt_before = manager.activity()?.corrupt_entries; + fs::OpenOptions::new().write(true).open(&pack)?.set_len(1)?; + let fallback = runner.generate(request)?; + let corrupt_count = manager + .activity()? + .corrupt_entries + .saturating_sub(corrupt_before); + drain_workers(&cache)?; + Ok((replay, fallback, corrupt_count)) +} diff --git a/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs b/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs index 650b3a01..40feee1b 100644 --- a/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs +++ b/crates/skippy-serving/src/frontend/tests/enc_dec_lane_admission.rs @@ -50,6 +50,7 @@ pub(in crate::frontend) fn modelless_stage_openai_args() -> EmbeddedOpenAiArgs { pipeline_decode_groups: None, adaptive_generation_min_concurrency: None, generation_queue_capacity: 8, + local_kv_reserve_percent: 0, generation_admission_timeout_secs: 1, prefill_chunk_size: 512, prefill_chunk_policy: "fixed".to_string(), diff --git a/crates/skippy-serving/src/frontend/tests/generation.rs b/crates/skippy-serving/src/frontend/tests/generation.rs index 9265c475..8f7c4c40 100644 --- a/crates/skippy-serving/src/frontend/tests/generation.rs +++ b/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); } diff --git a/crates/skippy-serving/src/frontend/tests/mod.rs b/crates/skippy-serving/src/frontend/tests/mod.rs index a2360f60..c06f7545 100644 --- a/crates/skippy-serving/src/frontend/tests/mod.rs +++ b/crates/skippy-serving/src/frontend/tests/mod.rs @@ -51,6 +51,7 @@ pub(super) use std::{ pub(super) use tokio::sync::Semaphore; mod cache_publication; +mod cache_qualification; mod causal_decisions; mod chat_stream_deltas; mod draft_runtime; diff --git a/crates/skippy-serving/src/frontend/tests/prefix_cache.rs b/crates/skippy-serving/src/frontend/tests/prefix_cache.rs index 5c49901f..87cef9fd 100644 --- a/crates/skippy-serving/src/frontend/tests/prefix_cache.rs +++ b/crates/skippy-serving/src/frontend/tests/prefix_cache.rs @@ -292,6 +292,47 @@ fn shared_execution_scopes_isolate_resident_and_content_addressed_cache() { assert!(kv.probe_resident_prefix(&b).is_none()); } +#[test] +fn explicit_chat_templates_partition_the_native_session_and_cache_namespace() { + let config = prefix_cache_test_config(); + let kv = KvStageIntegration::from_test_state(&config, skippy_runtime::ModelStateKind::Dense) + .unwrap() + .unwrap(); + let scope = skippy_inference_api::InferenceExecutionScope::new(); + let ids = || { + let mut cache = InferenceCacheHints::default(); + cache.prompt_cache_key = Some("same-key".into()); + InferenceGenerationIds::new_with_trust(cache, Some("same-agent"), true, None) + .with_execution_scope(Some(scope)) + }; + let default = ids(); + let unchanged = default.clone().with_chat_template(None); + let first = default.clone().with_chat_template(Some([1; 32])); + let repeat = ids().with_chat_template(Some([1; 32])); + let other = ids().with_chat_template(Some([2; 32])); + assert_eq!(unchanged.session_id, default.session_id); + assert_eq!(unchanged.cache.namespace(), default.cache.namespace()); + assert_eq!(first.session_id, repeat.session_id); + assert_eq!(first.request_id, default.request_id); + assert_ne!(first.session_id, other.session_id); + assert_ne!(first.session_id, default.session_id); + let tokens = (0..1024).collect::>(); + let identity = |ids: &InferenceGenerationIds| { + let mut base = prefix_cache_test_base(); + base.chat_template_id = ids.cache.namespace(); + kv.prefill_identity(&config, &base, 0, &tokens) + }; + let original = identity(&first); + seed_resident_prefix(&kv, &original); + assert!(kv.probe_resident_prefix(&identity(&repeat)).is_some()); + for changed in [&default, &other] { + let lookup = identity(changed); + assert_ne!(lookup.page_id, original.page_id); + assert_ne!(lookup.namespace, original.namespace); + assert!(kv.probe_resident_prefix(&lookup).is_none()); + } +} + #[test] fn disabled_cache_config_has_no_stage_integration() { let config = StageConfig { diff --git a/crates/skippy-serving/src/frontend/tests/prompting.rs b/crates/skippy-serving/src/frontend/tests/prompting.rs index 1d3cf8c6..61fdddb8 100644 --- a/crates/skippy-serving/src/frontend/tests/prompting.rs +++ b/crates/skippy-serving/src/frontend/tests/prompting.rs @@ -784,6 +784,7 @@ fn chat_message_generation_value_preserves_omitted_content() { /// Two generated tokens with recorded logprobs; the second one's row was unreadable. fn generated_text_with_logprobs() -> GeneratedText { let candidate = |text: &str, logprob: Option| GeneratedLogprobCandidate { + token_id: 0, text: text.to_string(), bytes: text.as_bytes().to_vec(), logprob, diff --git a/crates/skippy-serving/src/frontend/tests/request.rs b/crates/skippy-serving/src/frontend/tests/request.rs index b9631c2c..bb39b9bc 100644 --- a/crates/skippy-serving/src/frontend/tests/request.rs +++ b/crates/skippy-serving/src/frontend/tests/request.rs @@ -18,6 +18,64 @@ fn chat_runtime_feature_guard_allows_noop_parity_fields() { ensure_chat_runtime_features_supported(&request).unwrap(); } +#[test] +fn public_response_format_reaches_native_template_options() { + let schema = + json!({"type":"object", "properties":{"code":{"const":1729}}, "required":["code"]}); + let request = chat_request_with(&json!({"response_format": { + "type":"json_schema", "json_schema":{"name":"answer", "strict":true, "schema":schema} + }})); + let options = chat_template_options(&request, &Default::default()).unwrap(); + assert!(options.grammar.is_none()); + assert_eq!( + serde_json::from_str::(&options.json_schema.unwrap()).unwrap(), + schema + ); + + let request = chat_request_with(&json!({"response_format":{"type":"json_object"}})); + let options = chat_template_options(&request, &Default::default()).unwrap(); + assert_eq!( + serde_json::from_str::(&options.json_schema.unwrap()).unwrap(), + json!({"type":"object"}) + ); +} + +#[test] +fn public_response_format_overrides_default_native_constraints() { + let defaults = EmbeddedOpenAiRequestDefaults { + json_schema: Some(json!({"type":"object", "required":["default_only"]})), + ..Default::default() + }; + for format in [json!({"type":"text"}), json!({"type":"json_object"})] { + let mut request = chat_request_with(&json!({"response_format":format})); + apply_chat_request_defaults(&mut request, &defaults).unwrap(); + assert!(!request.extra.contains_key("json_schema")); + let options = chat_template_options(&request, &defaults).unwrap(); + assert_eq!( + options.json_schema.is_some(), + format["type"] == "json_object" + ); + } +} + +#[test] +fn malformed_or_conflicting_response_formats_are_rejected() { + for extra in [ + json!({"response_format":{"type":"unknown"}}), + json!({"response_format":{"type":"json_schema"}}), + json!({"response_format":{"type":"json_schema", "json_schema":{"schema":null}}}), + json!({"response_format":{"type":"json_schema", "json_schema":{"schema":{}, "strict":"yes"}}}), + json!({"response_format":{"type":"json_object"}, "grammar":"root ::= \"x\""}), + json!({"response_format":{"type":"json_object"}, "json_schema":{"type":"object"}}), + ] { + let request = chat_request_with(&extra); + assert!( + chat_template_options(&request, &Default::default()).is_err(), + "{extra}" + ); + } +} + /// A one-message chat request with `extra` fields merged in. fn chat_request_with(extra: &serde_json::Value) -> GenerationRequest { let mut payload = json!({ diff --git a/crates/skippy-serving/src/frontend/tests/support.rs b/crates/skippy-serving/src/frontend/tests/support.rs index 66d5a008..f84845bf 100644 --- a/crates/skippy-serving/src/frontend/tests/support.rs +++ b/crates/skippy-serving/src/frontend/tests/support.rs @@ -49,6 +49,7 @@ pub(super) fn prefix_cache_test_config() -> StageConfig { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, @@ -114,6 +115,7 @@ pub(super) fn seed_resident_prefix(kv: &KvStageIntegration, identity: &PrefillKv seq_id, token_count, recompute_cost: token_count, + retention_priority: 0, }, ) .expect("synthetic radix prefix should record"); diff --git a/crates/skippy-serving/src/frontend/tests/wire_messages.rs b/crates/skippy-serving/src/frontend/tests/wire_messages.rs index 5571ec3f..23a024f3 100644 --- a/crates/skippy-serving/src/frontend/tests/wire_messages.rs +++ b/crates/skippy-serving/src/frontend/tests/wire_messages.rs @@ -18,6 +18,7 @@ fn multimodal_final_prefill_message_requests_downstream_prediction() { positions: Vec::new(), sampling: Some(sampling.clone()), final_chunk: true, + request_class: Default::default(), }) .unwrap(); @@ -49,6 +50,7 @@ fn restore_prefill_decode_message_carries_chat_sampling_metadata() { sampling: Some(sampling.clone()), chat_sampling_metadata: Some(metadata), native_mtp_draft_tokens: 0, + request_class: Default::default(), }) .unwrap(); @@ -82,6 +84,7 @@ fn reusable_decode_message_updates_hot_path_fields() { sampling: Some(sampling.clone()), sideband_capacity: 4, native_mtp_draft_tokens: 3, + request_class: skippy_inference_api::InferenceRequestClass::default(), }) .unwrap(); @@ -115,3 +118,99 @@ fn reusable_decode_message_updates_hot_path_fields() { assert!(second.activation.is_empty()); assert!(second.raw_bytes.is_empty()); } + +/// A downstream stage caches prompts from every prefill, restore, decode, +/// verify window and stop of a session, so each must carry the request's +/// class. +#[test] +fn decode_verify_and_stop_messages_carry_the_request_class() { + use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; + let class = InferenceRequestClass::new(InferenceRequestTier::Mesh, true); + let served = |state| { + crate::stage_request_class::stage_request_class( + &skippy_protocol::StageConfig::default(), + state, + ) + }; + + let decode = embedded_decode_message(DecodeMessageArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 4, + pos_start: 4, + decode_step: 0, + current: 104, + sampling: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(decode.state), class); + + let verify = embedded_verify_window_message(VerifyWindowMessageArgs { + window_id: 1, + request_id: 11, + session_id: 13, + prompt_token_count: 4, + pos_start: 5, + decode_step: 1, + tokens: &[105, 106], + sampling: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(verify.state), class); + + let stop = stop_message(11, 13, class); + assert_eq!(stop.kind, WireMessageKind::Stop); + assert_eq!(served(stop.state), class); + + let prefill = embedded_prefill_message(OpenAiPrefillChunk { + seq_id: 0, + pos_start: 0, + prefill_token_count: 2, + tokens: &[1, 2], + request_id: 11, + session_id: 13, + request_class: class, + }) + .unwrap(); + assert_eq!(served(prefill.state), class); + + let restore = + embedded_prefix_cache_message(WireMessageKind::TryRestorePrefill, &[1, 2], 11, 13, class) + .unwrap(); + assert_eq!(served(restore.state), class); + + let multimodal = multimodal_prefill_message(MultimodalPrefillArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 2, + pos_start: 0, + token_count: 2, + tokens: vec![1, 2], + positions: Vec::new(), + sampling: None, + final_chunk: false, + request_class: class, + }) + .unwrap(); + assert_eq!(served(multimodal.state), class); + + let fused = embedded_restore_prefill_decode_message(RestorePrefillDecodeMessageArgs { + request_id: 11, + session_id: 13, + prompt_token_count: 3, + pos_start: 2, + decode_step: 0, + prefix_tokens: &[1, 2], + current: 3, + sampling: None, + chat_sampling_metadata: None, + native_mtp_draft_tokens: 0, + request_class: class, + }) + .unwrap(); + assert_eq!(served(fused.state), class); +} diff --git a/crates/skippy-serving/src/frontend/wire_messages.rs b/crates/skippy-serving/src/frontend/wire_messages.rs index 9c7e6057..e14f389a 100644 --- a/crates/skippy-serving/src/frontend/wire_messages.rs +++ b/crates/skippy-serving/src/frontend/wire_messages.rs @@ -1,4 +1,5 @@ use skippy_inference_api::InferenceError; +use skippy_inference_api::InferenceRequestClass; use skippy_inference_api::InferenceResult; use skippy_protocol::binary::LLAMA_TOKEN_NULL; use skippy_protocol::binary::StageSamplingConfig as WireSamplingConfig; @@ -16,6 +17,8 @@ pub(super) struct DecodeMessageArgs { pub(super) sampling: Option, /// Native MTP drafts the final stage should propose; zero asks for none. pub(super) native_mtp_draft_tokens: usize, + /// The tier and cache partition of the request this decode serves. + pub(super) request_class: InferenceRequestClass, } pub(super) fn embedded_decode_message( @@ -29,6 +32,7 @@ pub(super) fn embedded_decode_message( sampling: args.sampling, sideband_capacity: 1, native_mtp_draft_tokens: args.native_mtp_draft_tokens, + request_class: args.request_class, })?; message.update_at_pos( args.decode_step, @@ -47,6 +51,9 @@ pub(super) struct ReusableDecodeMessageArgs { pub(super) sampling: Option, pub(super) sideband_capacity: usize, pub(super) native_mtp_draft_tokens: usize, + /// Stamped on every decode, since a downstream stage records the prompt + /// on the first one. + pub(super) request_class: InferenceRequestClass, } pub(super) struct ReusableDecodeMessage { @@ -63,6 +70,7 @@ impl ReusableDecodeMessage { state.prompt_token_count = i32::try_from(args.prompt_token_count) .map_err(|_| InferenceError::backend("prompt token count exceeds i32"))?; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(Self { message: StageWireMessage { kind: WireMessageKind::DecodeEmbd, @@ -143,6 +151,7 @@ pub(super) struct VerifyWindowMessageArgs<'a> { pub(super) tokens: &'a [i32], pub(super) sampling: Option, pub(super) native_mtp_draft_tokens: usize, + pub(super) request_class: InferenceRequestClass, } /// Construct a verification-window request with coordinator-owned identity. @@ -166,6 +175,7 @@ pub(super) fn embedded_verify_window_message( .map_err(|_| InferenceError::backend("decode step exceeds i32"))?; state.current_token = args.tokens[0]; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind: WireMessageKind::VerifyWindow, pos_start: i32::try_from(args.pos_start) @@ -185,6 +195,18 @@ pub(super) fn embedded_verify_window_message( }) } +/// Ends a request's stage session. It carries the request's class because a +/// downstream stage records the prompt it accumulated when the session stops. +pub(super) fn stop_message( + request_id: u64, + session_id: u64, + request_class: InferenceRequestClass, +) -> StageWireMessage { + let mut message = StageWireMessage::stop_with_identity(request_id, session_id); + crate::stage_request_class::stamp_request_class(&mut message.state, request_class); + message +} + /// Invalidates verify windows `min_window_id..=max_window_id` for a request /// after divergence. The downstream records the range at receive time so /// buffered stale windows are answered with an empty reply instead of being @@ -270,6 +292,7 @@ pub(super) struct OpenAiPrefillChunk<'a> { pub(super) tokens: &'a [i32], pub(super) request_id: u64, pub(super) session_id: u64, + pub(super) request_class: InferenceRequestClass, } /// Construct a prefill request with its prompt, activation and sampling metadata. @@ -286,6 +309,7 @@ pub(super) fn embedded_prefill_message( .last() .ok_or_else(|| InferenceError::backend("prefill chunk is empty"))?; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, chunk.request_class); Ok(StageWireMessage { kind: WireMessageKind::PrefillEmbd, pos_start: i32::try_from(chunk.pos_start) @@ -311,12 +335,14 @@ pub(super) fn embedded_prefix_cache_message( tokens: &[i32], request_id: u64, session_id: u64, + request_class: InferenceRequestClass, ) -> InferenceResult { let mut state = StageStateHeader::new(kind); state.prompt_token_count = i32::try_from(tokens.len()) .map_err(|_| InferenceError::backend("prefix token count exceeds i32"))?; state.current_token = tokens.last().copied().unwrap_or(LLAMA_TOKEN_NULL); state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, request_class); Ok(StageWireMessage { kind, pos_start: 0, @@ -346,6 +372,7 @@ pub(super) struct RestorePrefillDecodeMessageArgs<'a> { pub(super) sampling: Option, pub(super) chat_sampling_metadata: Option<&'a str>, pub(super) native_mtp_draft_tokens: usize, + pub(super) request_class: InferenceRequestClass, } /// Construct a fused restore/prefill/decode request preserving generation metadata. @@ -364,6 +391,7 @@ pub(super) fn embedded_restore_prefill_decode_message( let mut tokens = Vec::with_capacity(args.prefix_tokens.len().saturating_add(1)); tokens.extend_from_slice(args.prefix_tokens); tokens.push(args.current); + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind: WireMessageKind::TryRestorePrefillDecode, pos_start: i32::try_from(args.pos_start) @@ -400,6 +428,7 @@ pub(super) struct MultimodalPrefillArgs { pub(super) positions: Vec, pub(super) sampling: Option, pub(super) final_chunk: bool, + pub(super) request_class: InferenceRequestClass, } /// Construct a prefill request carrying multimodal positions and activation data. @@ -417,6 +446,7 @@ pub(super) fn multimodal_prefill_message( .map_err(|_| InferenceError::backend("multimodal prefill token count exceeds i32"))?; state.current_token = LLAMA_TOKEN_NULL; state.source_stage_index = -1; + crate::stage_request_class::stamp_request_class(&mut state, args.request_class); Ok(StageWireMessage { kind, pos_start: i32::try_from(args.pos_start) diff --git a/crates/skippy-serving/src/kv_integration/activation.rs b/crates/skippy-serving/src/kv_integration/activation.rs index 6e315545..91b6693f 100644 --- a/crates/skippy-serving/src/kv_integration/activation.rs +++ b/crates/skippy-serving/src/kv_integration/activation.rs @@ -213,6 +213,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 256, shared_prefix_stride_tokens: 128, diff --git a/crates/skippy-serving/src/kv_integration/cache_affinity.rs b/crates/skippy-serving/src/kv_integration/cache_affinity.rs index 6a8331b3..e4166a68 100644 --- a/crates/skippy-serving/src/kv_integration/cache_affinity.rs +++ b/crates/skippy-serving/src/kv_integration/cache_affinity.rs @@ -110,6 +110,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 64, shared_prefix_stride_tokens: 32, @@ -170,6 +171,7 @@ mod checkpoint_matching_tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 128, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), min_tokens: 1, @@ -181,7 +183,7 @@ mod checkpoint_matching_tests { ..StageConfig::default() }; // An arbitrary state-kind label cannot override the loaded memory contract. - let integration = KvStageIntegration::from_test_model_with_l3_manager( + let integration = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(skippy_runtime::ModelStateKind::Dense), Some(MemoryCacheCapabilities { @@ -238,6 +240,7 @@ mod checkpoint_matching_tests { seq_id: seq, token_count: identity.token_ids.len() as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); diff --git a/crates/skippy-serving/src/kv_integration/config.rs b/crates/skippy-serving/src/kv_integration/config.rs index 1514701f..1cc4c1ef 100644 --- a/crates/skippy-serving/src/kv_integration/config.rs +++ b/crates/skippy-serving/src/kv_integration/config.rs @@ -7,7 +7,7 @@ use anyhow::Result; use skippy_cache::{ CacheBlobStore, GeometryBlock, GeometryKind, L3CacheManager, L3Tier, PayloadGeometry, ResidentActivationCache, ResidentCacheConfig, SparseCheckpointPolicy, StoreLimits, - UnifiedRadixCache, exact_state_identity_for_stage, numerical_model_identity_for_stage, + UnifiedRadixCache, numerical_model_identity_for_stage, }; use skippy_protocol::{StageConfig, StageKvCacheCodec, StageKvCacheConfig, StageKvCacheMode}; use skippy_runtime::{ModelStateKind, RuntimeKvPageDesc}; @@ -19,31 +19,27 @@ 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, +}; +mod durable_identity; 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. @@ -73,7 +69,6 @@ impl KvStageIntegration { config, model_state_kind, memory_cache, - None, || l3_manager_from_env(config), observer, ) @@ -93,7 +88,6 @@ impl KvStageIntegration { config, model_state_kind, memory_cache, - None, || Ok(manager), observer, ) @@ -103,9 +97,6 @@ impl KvStageIntegration { config: &StageConfig, model_state_kind: Option, memory_cache: Option, - loaded_model_content: Option< - Arc, - >, manager: impl FnOnce() -> Result>, observer: Option>, ) -> Result> { @@ -139,12 +130,22 @@ impl KvStageIntegration { }; let payload_selection_reason = "loaded_graph_and_memory"; let dense_without_recurrent = admitted.resident && !admitted.resident_checkpoint; - let l3_manager = if loaded_model_content.is_some() { + // Model resolution and package admission own content verification. + // Reuse their identity instead of reopening model files in the cache. + let l3_manager = if config.source_model_sha256.is_some() || config.manifest_sha256.is_some() + { manager()? } else { None }; - if !admitted.resident && cache_config.l2_max_bytes > 0 && l3_manager.is_none() { + let durable_payload = l3_manager + .as_ref() + .and_then(|_| durable_cache_payload(admitted)); + let l3 = l3_manager + .zip(durable_payload) + .and_then(|(manager, payload)| l3_tier_for_manager(config, payload, manager)); + let durable_payload = durable_payload.filter(|_| l3.is_some()); + if !admitted.resident && cache_config.l2_max_bytes > 0 && l3.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(), @@ -155,27 +156,14 @@ impl KvStageIntegration { }, ); } - let durable_payload = l3_manager - .as_ref() - .and_then(|_| durable_cache_payload(admitted)); - let l3 = l3_manager - .zip(durable_payload) - .map(|(manager, payload)| { - l3_tier_for_manager(config, payload, manager, loaded_model_content.as_deref()) - }) - .transpose()?; let l2 = l3 .as_ref() - .filter(|_| !admitted.resident && cache_config.l2_max_bytes > 0) - .and(durable_payload) - .map(|payload| { + .filter(|_| cache_config.l2_max_bytes > 0) + .map(|tier| { super::l2_serving::StageL2::new( cache_config.l2_max_bytes, - numerical_model_identity_for_stage(config), - bind_model_content( - loaded_model_content.as_deref(), - exact_state_identity_for_stage(config, l3_payload_kind(payload)), - ), + tier.model_identity().to_owned(), + tier.state_identity().to_owned(), ) }); // Complete exporters are admitted by the native graph and memory; state @@ -221,8 +209,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(); @@ -303,6 +294,20 @@ impl KvStageIntegration { worker_observer.as_ref(), pending, |pending| { + if admitted.resident + && let (Some(l2), Some(manifest)) = + (worker_l2.as_ref(), pending.l2_promotion_manifest.as_deref()) + { + // The native resident prefix already owns L1. + // Publish only the bounded host-RAM mirror. + let _ = l2.promote( + &pending.namespace, + &pending.token_ids, + manifest, + &pending.payload, + ); + return Ok(()); + } // The serving worker owns only L1/L2 publication. // Durable I/O runs on its own bounded fail-open // worker so an early page spill cannot head-of-line @@ -359,7 +364,6 @@ impl KvStageIntegration { durable_spill_tx, )); let integration = Self { - loaded_model_content, mode, payload, payload_selection_reason, @@ -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)] @@ -412,6 +417,7 @@ impl KvStageIntegration { l3, cachegen_serving_enabled: worker_cachegen, inflight_fills, + l3_staging: Arc::new(std::sync::atomic::AtomicBool::new(false)), dense_without_recurrent, resident_checkpoint_max_bytes, }; @@ -514,12 +520,22 @@ fn l3_tier_for_manager( config: &StageConfig, payload: StagePrefixCachePayload, manager: L3CacheManager, - content: Option<&crate::runtime_state::model_content::VerifiedModelContent>, -) -> Result> { - let identity = bind_model_content( - content, - exact_state_identity_for_stage(config, l3_payload_kind(payload)), - ); +) -> Option> { + let identity = match durable_identity::read(config, l3_payload_kind(payload)) { + Ok(identity) => identity, + Err(error) => { + let _ = skippy_events::diagnostics::emit( + skippy_events::diagnostics::ServingDiagnostic::Warning { + message: "Skippy L3 disk cache disabled for this model stage".to_string(), + context: Some(format!( + "stage_id={} model_id={} reason={error:#}", + config.stage_id, config.model_id, + )), + }, + ); + return None; + } + }; 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); @@ -550,17 +566,7 @@ 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, - } + Some(Arc::new(tier)) } fn l3_payload_kind(payload: StagePrefixCachePayload) -> &'static str { @@ -581,13 +587,19 @@ fn l3_payload_kind(payload: StagePrefixCachePayload) -> &'static str { /// run after the first — measured at 8x on an M4 mini. Cutting per run into /// fixed token windows writes only the new rows. /// -/// Returns `None` when the layout is not one this mapping can state exactly; -/// the store then falls back to fixed-size cutting, which is correct but not -/// cheap. -fn kv_page_geometry(desc: &RuntimeKvPageDesc, payload_bytes: u64) -> Option { - // A composite (ISWA) page is two independently-shaped components; its - // geometry is not this single-run description. - if desc.component_count != 0 || desc.token_count == 0 || desc.layer_count == 0 { +/// Falls back to fixed-size segments for layouts without contiguous token rows. +/// In particular, windowing each transposed V column separately creates hundreds +/// of thousands of segment records for a short checkpoint. Fixed-size packing +/// bounds that metadata and preserves the native bytes and restore descriptor. +pub(super) fn kv_page_geometry( + desc: &RuntimeKvPageDesc, + payload_bytes: u64, +) -> Option { + if desc.component_count != 0 + || desc.flags & skippy_runtime::KV_PAGE_FLAG_V_TRANSPOSED != 0 + || desc.token_count == 0 + || desc.layer_count == 0 + { return None; } let rows = desc.token_count; @@ -605,35 +617,7 @@ fn kv_page_geometry(desc: &RuntimeKvPageDesc, payload_bytes: u64) -> Option 0 { + if desc.v_row_bytes > 0 { for layer in 0..layers { blocks.push(GeometryBlock { stride: u64::from(desc.v_row_bytes), @@ -744,10 +728,11 @@ fn store_exact_radix_record_with_codec( payload, extra, namespace, + retention_priority, token_ids, l3_fill_claim: _, write_through_l3, - l2_promotion_digest, + l2_promotion_manifest, l3_cost, admission_credit: _admission_credit, } = pending; @@ -774,7 +759,8 @@ fn store_exact_radix_record_with_codec( payload.clone(), extra.clone(), write_through_l3, - ), + ) + .with_retention_priority(retention_priority), ); match insert_result { Err(error) => Err(error), @@ -782,8 +768,16 @@ fn store_exact_radix_record_with_codec( if let Some(replaced) = replaced { released.push(replaced.payload); } + // Count pressure follows use, not prefix position: a + // checkpoint that a longer retained checkpoint extends is + // often the branch point sibling conversations still match, + // so the coldest entry leaves first. Superseded reclaim + // ahead of recency belongs to the hard byte pass in + // `exact_state_retention`. while radix.stats().recurrent_entries > max_entries { - let Some(evicted) = radix.evict_lru_recurrent() else { + let Some(evicted) = + radix.evict_recurrent_by_retention(RadixExactEntry::retention_priority) + else { break; }; released.push(evicted.value.payload); @@ -808,27 +802,12 @@ 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 small - // 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)?; + enforce_exact_state_limits(radix, blobs, limits, max_entries, logical_bytes)?; #[cfg(test)] crate::frontend::capture_trace::log_stored_identity(&namespace, &token_ids); - if let (Some(l2), Some(payload_digest)) = (l2, l2_promotion_digest.as_deref()) { - let _ = l2.promote(&namespace, &token_ids, payload_digest, &payload, &extra); + if let (Some(l2), Some(manifest)) = (l2, l2_promotion_manifest.as_deref()) { + let _ = l2.promote(&namespace, &token_ids, manifest, &payload); } // Durable write-through is best-effort after L1 publication: a slow, full, // or failing disk must not delay or invalidate the in-memory record. The @@ -837,7 +816,8 @@ fn store_exact_radix_record_with_codec( let durable_spill = write_through_l3.then_some(PendingDurableSpill { page_id, native_raw: false, - payload, + extension: None, + payload: payload.into(), extra, namespace, token_ids, @@ -899,50 +879,6 @@ 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. -fn evict_exact_entries_over( - radix: &Mutex>, - blobs: &Mutex, - limit_bytes: u64, - min_retained_entries: usize, -) -> Result<()> { - if limit_bytes == 0 { - return Ok(()); - } - let floor = min_retained_entries.max(1); - loop { - let over_bytes = blobs - .lock() - .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 { - break; - } - let evicted = radix - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .evict_lru_recurrent(); - let Some(evicted) = evicted else { - break; - }; - evicted.value.payload.release_from( - &mut blobs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner), - )?; - } - Ok(()) -} - /// 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 { @@ -996,6 +932,7 @@ pub(super) fn effective_cache_config(config: &StageConfig) -> Option ExactStateByteLimits { ExactStateByteLimits { soft_bytes, hard_bytes, + hard_is_explicit: false, } } @@ -1053,6 +993,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") @@ -1072,10 +1013,11 @@ mod tests { payload: skippy_cache::ExactStatePayload::full_state(bytes.to_vec()), extra: super::super::ExactStateExtra::default(), namespace: "model".to_string(), + retention_priority: 0, token_ids: tokens.to_vec(), l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit: budget.credit(), } @@ -1124,10 +1066,11 @@ mod tests { kv_desc: Some(desc), }, namespace: "model".to_string(), + retention_priority: 0, token_ids: tokens.to_vec(), l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit: budget.credit(), } @@ -1282,7 +1225,9 @@ mod tests { let budget = StorageBudget::new(); let mut record = pending("filled", &[1, 2], bytes, &budget); record.write_through_l3 = false; - record.l2_promotion_digest = Some(skippy_cache::segment_digest(bytes)); + record.l2_promotion_manifest = Some(Box::new( + super::super::l2_serving::legacy_test_manifest(2, bytes), + )); store_exact_radix_record(&radix, &blobs, 1, limits(0, 0), Some(&l2), None, record).unwrap(); @@ -1461,23 +1406,17 @@ mod tests { } #[test] - fn kv_page_geometry_windows_transposed_value_columns() { - // Transposed V is column-major, but each column is one contiguous run - // of one element per token, so it windows like any other run. - let mut desc = kv_desc(2, 256, 1024, 0); + fn kv_page_geometry_uses_fixed_size_packing_for_transposed_values() { + let mut desc = kv_desc(48, 533, 1024, 0); desc.flags = skippy_runtime::KV_PAGE_FLAG_V_TRANSPOSED; desc.v_element_bytes = 2; - let columns = 512u64; - let payload = desc.payload_bytes + u64::from(desc.layer_count) * columns * 256 * 2; - let geometry = kv_page_geometry(&desc, payload).expect("transposed page"); - - let value_blocks = geometry - .blocks - .iter() - .filter(|block| block.kind == GeometryKind::Value) - .count(); - assert_eq!(value_blocks as u64, u64::from(desc.layer_count) * columns); - assert!(geometry.matches(payload)); + let value_columns = 512_u64; + desc.payload_bytes += u64::from(desc.layer_count) + * desc.token_count + * value_columns + * u64::from(desc.v_element_bytes); + + assert!(kv_page_geometry(&desc, desc.payload_bytes).is_none()); } #[test] @@ -1546,15 +1485,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 +1513,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] @@ -1663,6 +1615,7 @@ mod tests { max_entries: 512, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -1673,460 +1626,3 @@ mod tests { config } } - -#[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, - 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()); - } -} diff --git a/crates/skippy-serving/src/kv_integration/config/durable_identity.rs b/crates/skippy-serving/src/kv_integration/config/durable_identity.rs new file mode 100644 index 00000000..45789b4a --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/config/durable_identity.rs @@ -0,0 +1,93 @@ +use anyhow::{Result, ensure}; +use serde::Serialize; +use skippy_cache::exact_state_identity_for_stage; +use skippy_protocol::{SplitMode, StageConfig}; +use skippy_runtime::{BackendDevice, BackendDeviceType}; + +/// The native runtime can choose devices automatically or split a stage +/// between devices. Keep registry order because the native placement can use +/// that order. Free memory and other transient counters are deliberately +/// excluded so an otherwise identical replacement process can restore. +#[derive(Serialize)] +struct DeviceIdentity<'a> { + name: &'a str, + description: Option<&'a str>, + device_id: Option<&'a str>, + kind: &'static str, +} + +impl<'a> From<&'a BackendDevice> for DeviceIdentity<'a> { + fn from(device: &'a BackendDevice) -> Self { + Self { + name: &device.name, + description: device.description.as_deref(), + device_id: device.device_id.as_deref(), + kind: match device.device_type { + BackendDeviceType::Cpu => "cpu", + BackendDeviceType::Gpu => "gpu", + BackendDeviceType::IntegratedGpu => "integrated_gpu", + BackendDeviceType::Accelerator => "accelerator", + BackendDeviceType::Meta => "meta", + }, + } + } +} + +#[derive(Serialize)] +struct RuntimePlacement<'a> { + os: &'static str, + native_abi: [u32; 3], + devices: Vec>, + main_gpu: Option, + split_mode: SplitMode, + kv_offload: Option, + op_offload: Option, + no_host_buffer: bool, +} + +pub(super) fn read(config: &StageConfig, payload: &str) -> Result { + let native_abi = [ + skippy_runtime::ABI_VERSION_MAJOR, + skippy_runtime::ABI_VERSION_MINOR, + skippy_runtime::ABI_VERSION_PATCH, + ]; + let loaded = skippy_runtime::native_runtime_loaded(); + #[cfg(test)] + if !loaded { + // Modelless tests can pass synthetic cache capabilities with no FFI. + return state_identity(config, payload, native_abi, &[]); + } + ensure!(loaded, "no native runtime device inventory"); + let devices = skippy_runtime::backend_devices()?; + ensure!( + !devices.is_empty() && devices.iter().all(|device| !device.name.is_empty()), + "native runtime reported an incomplete device inventory" + ); + state_identity(config, payload, native_abi, &devices) +} + +fn state_identity( + config: &StageConfig, + payload: &str, + native_abi: [u32; 3], + devices: &[BackendDevice], +) -> Result { + let placement = RuntimePlacement { + os: std::env::consts::OS, + native_abi, + devices: devices.iter().map(DeviceIdentity::from).collect(), + main_gpu: config.main_gpu, + split_mode: config.split_mode, + kv_offload: config.kv_offload, + op_offload: config.op_offload, + no_host_buffer: config.no_host_buffer, + }; + let mut hash = blake3::Hasher::new(); + hash.update(b"skippy-durable-placement-v1"); + hash.update(exact_state_identity_for_stage(config, payload).as_bytes()); + hash.update(&serde_json::to_vec(&placement)?); + Ok(format!("blake3:{}", hash.finalize().to_hex())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/skippy-serving/src/kv_integration/config/durable_identity/tests.rs b/crates/skippy-serving/src/kv_integration/config/durable_identity/tests.rs new file mode 100644 index 00000000..eacfa42c --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/config/durable_identity/tests.rs @@ -0,0 +1,110 @@ +use super::*; +use crate::kv_integration::identity::durable_namespace; +use skippy_cache::{ + ExactStatePayload, L3CacheManager, StoreLimits, numerical_model_identity_for_stage, + prefix_namespace_hash, +}; + +const ABI: [u32; 3] = [0, 1, 80]; +const PAYLOAD: &str = "full-state"; + +fn device(name: &str, id: &str) -> BackendDevice { + BackendDevice { + name: name.into(), + description: None, + device_id: Some(id.into()), + memory_free: 100, + memory_total: 200, + device_type: BackendDeviceType::Gpu, + caps: 0, + } +} + +#[test] +fn auto_placement_uses_stable_device_identity_and_order() { + let config = StageConfig::default(); + assert!(config.selected_device.is_none()); + let mut devices = [device("CUDA0", "pcie:0"), device("CUDA1", "pcie:1")]; + let identity = + |config, devices: &[BackendDevice]| state_identity(config, PAYLOAD, ABI, devices).unwrap(); + let first = identity(&config, &devices); + devices[0].memory_free /= 2; + assert_eq!(first, identity(&config, &devices)); + devices.swap(0, 1); + assert_ne!(first, identity(&config, &devices)); + devices.swap(0, 1); + devices[0].device_id = Some("pcie:4".into()); + assert_ne!(first, identity(&config, &devices)); +} + +#[test] +fn stale_abi_backend_model_and_placement_miss_on_one_store() { + let directory = tempfile::tempdir().unwrap(); + let limits = StoreLimits::new(1 << 20, 0); + let config = StageConfig { + model_id: "same-model-alias".into(), + source_model_sha256: Some("a".repeat(64)), + ..StageConfig::default() + }; + let other_model = StageConfig { + source_model_sha256: Some("b".repeat(64)), + ..config.clone() + }; + let other_placement = StageConfig { + kv_offload: Some(false), + ..config.clone() + }; + let metal = [device("MTL0", "device:0")]; + let cuda = [device("CUDA0", "device:0")]; + let tokens: Vec = (0..128).collect(); + let payload = ExactStatePayload::full_state(vec![7; 1024]); + let namespace = |config: &StageConfig, state_identity: &str| { + durable_namespace(&prefix_namespace_hash(config, 0, None), state_identity) + }; + let original_state = state_identity(&config, PAYLOAD, ABI, &metal).unwrap(); + let original_model = numerical_model_identity_for_stage(&config); + let original_namespace = namespace(&config, &original_state); + + { + let publisher = L3CacheManager::acquire(directory.path(), limits).unwrap(); + let legacy_state = exact_state_identity_for_stage(&config, PAYLOAD); + let legacy = publisher.tier_for_model(original_model.clone(), legacy_state, 4096); + let legacy_namespace = prefix_namespace_hash(&config, 0, None); + let unrelated_tokens: Vec = (128..256).collect(); + legacy + .spill(&legacy_namespace, &unrelated_tokens, &payload, None, None) + .unwrap(); + let tier = publisher.tier_for_model(original_model.clone(), original_state.clone(), 4096); + tier.spill(&original_namespace, &tokens, &payload, None, None) + .unwrap(); + } + let replacement = L3CacheManager::acquire(directory.path(), limits).unwrap(); + let warm_tier = replacement.tier_for_model(original_model, original_state.clone(), 4096); + let reads_before = replacement.activity().unwrap().bytes_read; + assert!( + warm_tier + .fill_longest(&original_namespace, &(128..256).collect::>(), 4) + .unwrap() + .is_none() + ); + for (variant, abi, devices) in [ + (&config, [0, 1, 79], &metal), + (&config, ABI, &cuda), + (&other_model, ABI, &metal), + (&other_placement, ABI, &metal), + ] { + let state = state_identity(variant, PAYLOAD, abi, devices).unwrap(); + assert_ne!(state, original_state); + let prefix = namespace(variant, &state); + let tier = + replacement.tier_for_model(numerical_model_identity_for_stage(variant), state, 4096); + assert!(tier.fill_longest(&prefix, &tokens, 4).unwrap().is_none()); + } + assert_eq!(replacement.activity().unwrap().bytes_read, reads_before); + let hit = warm_tier + .fill_longest(&original_namespace, &tokens, 4) + .unwrap() + .unwrap(); + assert_eq!(hit.token_count, 128); + assert_eq!(hit.payload_bytes, 1024); +} diff --git a/crates/skippy-serving/src/kv_integration/config/durable_spill.rs b/crates/skippy-serving/src/kv_integration/config/durable_spill.rs index ae9e4c09..ec01e182 100644 --- a/crates/skippy-serving/src/kv_integration/config/durable_spill.rs +++ b/crates/skippy-serving/src/kv_integration/config/durable_spill.rs @@ -1,4 +1,7 @@ +use super::super::resident_offload::NativeCapturePayload; use super::*; +use anyhow::Context; +use std::{collections::VecDeque, num::NonZeroU64}; #[derive(Clone, Copy)] pub(in crate::kv_integration) struct DurableRecordTarget<'a> { @@ -12,12 +15,55 @@ pub(in crate::kv_integration) struct DurableRecordTarget<'a> { #[derive(Debug)] 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) payload: DurableSpillPayload, 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, + pub(in crate::kv_integration) extension: Option, +} + +#[derive(Debug)] +pub(in crate::kv_integration) enum DurableSpillPayload { + Assembled(skippy_cache::ExactStatePayload), + Native(NativeCapturePayload), +} + +impl From for DurableSpillPayload { + fn from(payload: skippy_cache::ExactStatePayload) -> Self { + Self::Assembled(payload) + } +} + +impl DurableSpillPayload { + fn byte_len(&self) -> u64 { + match self { + Self::Assembled(payload) => payload.byte_len(), + Self::Native(payload) => payload.byte_len(), + } + } + + fn assemble(self) -> Result { + match self { + Self::Assembled(payload) => Ok(payload), + Self::Native(payload) => payload.assemble(), + } + } +} + +#[derive(Debug)] +pub(in crate::kv_integration) struct NativeSpillExtension { + pub(in crate::kv_integration) base: skippy_cache::L3Location, + pub(in crate::kv_integration) reused_rows: NonZeroU64, + pub(in crate::kv_integration) geometry: PayloadGeometry, +} + +#[derive(Debug)] +struct NativeCheckpoint { + namespace: String, + tokens: Vec, + location: skippy_cache::L3Location, } pub(in crate::kv_integration) struct DurableSpillReservation { @@ -43,17 +89,85 @@ pub(in crate::kv_integration) struct DurableSpillSender { tx: std::sync::mpsc::SyncSender, held_bytes: Arc, byte_cap: u64, + recent_checkpoints: Arc>>, } impl DurableSpillSender { + pub(in crate::kv_integration) fn has_native_checkpoint( + &self, + namespace: &str, + tokens: &[i32], + ) -> bool { + self.recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .any(|entry| entry.namespace == namespace && entry.tokens == tokens) + } + fn new(tx: std::sync::mpsc::SyncSender, byte_cap: u64) -> Self { Self { tx, held_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)), byte_cap, + recent_checkpoints: Arc::default(), } } + pub(in crate::kv_integration) fn native_base( + &self, + namespace: &str, + tokens: &[i32], + ) -> Option { + self.recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .filter(|entry| { + entry.namespace == namespace + && entry.tokens.len() < tokens.len() + && tokens.starts_with(&entry.tokens) + }) + .max_by_key(|entry| entry.tokens.len()) + .map(|entry| entry.location.clone()) + } + + pub(in crate::kv_integration) fn remember_loaded( + &self, + namespace: &str, + tokens: &[i32], + location: &skippy_cache::L3Location, + ) { + if location.native_kv_passthrough + && let Ok(len) = usize::try_from(location.token_count) + && let Some(prefix) = tokens.get(..len) + { + Self::remember_native_checkpoint( + &self.recent_checkpoints, + NativeCheckpoint { + namespace: namespace.to_owned(), + tokens: prefix.to_vec(), + location: location.clone(), + }, + ); + } + } + + fn remember_native_checkpoint( + recent: &Mutex>, + checkpoint: NativeCheckpoint, + ) { + const RECENT_NATIVE_CHECKPOINTS: usize = 16; + let mut recent = recent + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + recent.retain(|entry| entry.location.manifest_key != checkpoint.location.manifest_key); + if recent.len() >= RECENT_NATIVE_CHECKPOINTS { + recent.pop_front(); + } + recent.push_back(checkpoint); + } + /// 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( @@ -146,6 +260,7 @@ pub(in crate::kv_integration) fn start_durable_spill_worker( }; let (tx, rx) = std::sync::mpsc::sync_channel::(EXACT_STATE_RECORD_CAPACITY); let sender = DurableSpillSender::new(tx, byte_cap); + let recent_checkpoints = Arc::clone(&sender.recent_checkpoints); let task = std::thread::Builder::new() .name(format!("skippy-l3-spill-{stage_id}")) .spawn(move || { @@ -161,7 +276,33 @@ pub(in crate::kv_integration) fn start_durable_spill_worker( while pause.load(std::sync::atomic::Ordering::Acquire) { std::thread::sleep(std::time::Duration::from_millis(2)); } + let prefix = pending + .native_raw + .then(|| (pending.namespace.clone(), pending.token_ids.clone())); + let reused_base = pending + .extension + .as_ref() + .map(|extension| extension.base.manifest_key.clone()); spill_exact_record_to_l3(&l3, cachegen_enabled, pending); + if let Some((namespace, tokens)) = prefix + && let Ok(Some(location)) = l3.locate_longest(&namespace, &tokens, 1) + && location.token_count == tokens.len() as u64 + && location.native_kv_passthrough + { + DurableSpillSender::remember_native_checkpoint( + &recent_checkpoints, + NativeCheckpoint { + namespace, + tokens, + location, + }, + ); + } else if let Some(base) = reused_base { + recent_checkpoints + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .retain(|entry| entry.location.manifest_key != base); + } } })?; Ok((Some(sender), Some(task))) @@ -181,6 +322,7 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( token_ids, l3_cost, native_raw, + extension, } = pending; // Native eviction already owns the runtime and resident index. Resolve // committed disk entries here on the durable worker, never under either @@ -194,6 +336,10 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( { return; } + let Ok(payload) = payload.assemble() else { + tracing::debug!(%page_id, "durable checkpoint assembly failed"); + return; + }; let kv_desc_json = extra .kv_desc .as_ref() @@ -243,16 +389,27 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( } else { None }; - let spill = cachegen_spill.unwrap_or_else(|| { - l3.spill_with_cost( + let spill = if let Some(extension) = extension { + spill_native_extension( + l3, &namespace, &token_ids, &payload, kv_desc_json, - geometry.as_ref(), - l3_cost, + &extension, ) - }); + } else { + cachegen_spill.unwrap_or_else(|| { + l3.spill_with_cost( + &namespace, + &token_ids, + &payload, + kv_desc_json, + geometry.as_ref(), + l3_cost, + ) + }) + }; emit_l3_state_transitions(l3); if let Err(error) = spill { static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -267,6 +424,33 @@ pub(in crate::kv_integration) fn spill_exact_record_to_l3( } } +fn spill_native_extension( + l3: &L3Tier, + namespace: &str, + tokens: &[i32], + payload: &skippy_cache::ExactStatePayload, + descriptor: Option, + extension: &NativeSpillExtension, +) -> Result> { + let descriptor = descriptor.context("native extension has no full checkpoint descriptor")?; + let kv = payload + .kv_bytes()? + .context("native extension has no KV suffix")?; + let recurrent = payload.recurrent_state_bytes()?; + l3.spill_native_extension( + namespace, + tokens, + skippy_cache::NativeKvExtension { + base: &extension.base, + reused_rows: extension.reused_rows, + geometry: &extension.geometry, + kv_desc_json: descriptor, + kv_tail: &kv, + recurrent: &recurrent, + }, + ) +} + #[cfg(test)] mod tests { use super::*; @@ -274,12 +458,13 @@ mod tests { fn pending(bytes: usize) -> PendingDurableSpill { PendingDurableSpill { page_id: format!("spill-{bytes}"), - payload: skippy_cache::ExactStatePayload::full_state(vec![7; bytes]), + payload: skippy_cache::ExactStatePayload::full_state(vec![7; bytes]).into(), extra: super::super::super::ExactStateExtra::default(), namespace: "model".to_string(), token_ids: vec![1, 2], l3_cost: None, native_raw: false, + extension: None, } } diff --git a/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs b/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs index a13bfc6a..5f6bec1a 100644 --- a/crates/skippy-serving/src/kv_integration/config/exact_state_limits.rs +++ b/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/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs b/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs new file mode 100644 index 00000000..4f079071 --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/config/exact_state_retention.rs @@ -0,0 +1,179 @@ +//! 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. + // The soft pass also stops at that floor: a checkpoint that a longer + // retained checkpoint extends is often the branch point sibling + // conversations still match, so only the hard ceiling below may evict + // it ahead of recency. + 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, + InteriorReclaim::FloorBounded, + )?; + // 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, + InteriorReclaim::SupersededFirst, + )?; + 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, +} + +/// Whether a byte-pressure pass may reclaim superseded checkpoints ahead of +/// its retention floor. +#[derive(Clone, Copy)] +enum InteriorReclaim { + /// Recency and the floor are the whole policy. The attention-derived + /// soft cap structurally undercounts indivisible snapshots, so the + /// catalog sits over it even at the floor and it must not be read as + /// pressure: a checkpoint that a longer retained checkpoint extends is + /// often the branch point sibling conversations still match, and + /// evicting it on prefix position alone drops the only entry those + /// siblings can reuse. + FloorBounded, + /// Superseded checkpoints may be reclaimed ahead of the floor: a hard + /// byte ceiling outranks hit rate, and every conversation keeps its + /// latest continuation. + SupersededFirst, +} + +/// Evict by recency above the floor; superseded checkpoints first only when +/// [`InteriorReclaim::SupersededFirst`] allows reclaiming them below it. +fn evict_exact_entries_over( + radix: &Mutex>, + blobs: &Mutex, + limit_bytes: u64, + floor: RetentionFloor, + interior_reclaim: InteriorReclaim, +) -> 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); + let superseded = match interior_reclaim { + InteriorReclaim::SupersededFirst => radix.evict_lru_superseded_recurrent(), + InteriorReclaim::FloorBounded => None, + }; + superseded.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_recurrent_by_retention(RadixExactEntry::retention_priority) + }) + .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/crates/skippy-serving/src/kv_integration/config/resident_policy.rs b/crates/skippy-serving/src/kv_integration/config/resident_policy.rs index 41e1405e..322c0eb2 100644 --- a/crates/skippy-serving/src/kv_integration/config/resident_policy.rs +++ b/crates/skippy-serving/src/kv_integration/config/resident_policy.rs @@ -1,16 +1,13 @@ //! Native radix prefixes own shared KV references and bounded recurrent host state. use skippy_protocol::StageKvCacheConfig; +use std::num::NonZeroU64; -/// 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 - } + cache + .l1_checkpoint_max_bytes + .map_or(DEFAULT_CHECKPOINT_BYTES, NonZeroU64::get) } #[cfg(test)] @@ -18,11 +15,12 @@ mod tests { use super::*; #[test] - fn checkpoint_ram_budget_is_independent_of_disk_and_attention_estimates() { + fn checkpoint_ram_budget_is_independent_of_l2_and_attention_estimates() { let cache = StageKvCacheConfig { max_bytes: 32, exact_max_bytes: Some(64), l2_max_bytes: 256, + l1_checkpoint_max_bytes: None, mode: skippy_protocol::StageKvCacheMode::LookupRecord, max_entries: 64, codec: Default::default(), @@ -32,13 +30,13 @@ mod tests { prefill_admission: Default::default(), retention: Default::default(), }; - assert_eq!(checkpoint_budget(&cache), 256); + assert_eq!(checkpoint_budget(&cache), DEFAULT_CHECKPOINT_BYTES); assert_eq!( checkpoint_budget(&StageKvCacheConfig { - l2_max_bytes: 0, + l1_checkpoint_max_bytes: NonZeroU64::new(512), ..cache }), - DEFAULT_CHECKPOINT_BYTES + 512 ); } } diff --git a/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs b/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs index 66f44957..50867c30 100644 --- a/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs +++ b/crates/skippy-serving/src/kv_integration/config/runtime_identity.rs @@ -1,59 +1,22 @@ -//! Bind cache construction to proof of the runtime's loaded model inputs. +//! Construct cache tiers from the loaded runtime's admitted capabilities. 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. + /// Combine loaded cache capabilities with the model identity admitted by serving. pub fn from_runtime_with_l3_manager( config: &StageConfig, runtime: &Arc>, manager: Option, observer: Option>, ) -> Result> { - let (kind, memory, content) = { + let (kind, memory) = { 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; - 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, - ) + Self::from_loaded_model_with_l3_manager(config, kind, memory, manager, observer) } } diff --git a/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs b/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs index 40da18eb..ff385f39 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/durable_spill.rs +++ b/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_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs b/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs new file mode 100644 index 00000000..0217c286 --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/config/tests/exact_state_retention.rs @@ -0,0 +1,310 @@ +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`. +/// +/// Seeds 0..7 map to disjoint 32-byte ranges: a wrapped `seed * 64` used to +/// alias seed 4 onto seed 0, which deduped the fifth snapshot's blocks and +/// removed the byte pressure this helper exists to create. +fn distinct_payload(seed: u8, len: usize) -> Vec { + let base = (seed % 4) * 64 + 32 * (seed / 4); + (0..len) + .map(|offset| base.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_keeps_a_matched_checkpoint_over_a_colder_conversation() { + // Count pressure follows use, not prefix position: a matched checkpoint + // may still be the only reusable entry for sibling branches that + // diverge at it, so a colder conversation's entry leaves first even + // when a longer checkpoint extends the matched one. + 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_some(), + "the just-matched checkpoint must survive its conversation extending past it" + ); + assert!( + radix.recurrent_exact("model", &[1, 3]).is_none(), + "the coldest conversation leaves first" + ); + for tokens in [&[1, 2, 9][..], &[1, 4], &[1, 5]] { + assert!(radix.recurrent_exact("model", tokens).is_some()); + } +} + +#[test] +fn entry_limit_keeps_a_fresh_branch_point_over_a_colder_conversation() { + // Flash Next AgentX replay shape: a request records its shared-boundary + // checkpoint and then its own post-decode continuation extends past + // it. The boundary must survive while an older, unused conversation + // entry is available to evict instead, because the next sibling + // request matches exactly that boundary. + 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("b", &[1, 3], 1); + store("c", &[1, 4], 2); + store("d", &[1, 5], 3); + store("a-shared", &[1, 2], 0); + store("a-decode", &[1, 2, 9], 4); + + let mut radix = radix.lock().unwrap(); + assert!( + radix.lookup_recurrent("model", &[1, 2, 6]).is_some(), + "a sibling branch diverging at the shared boundary must still hit it" + ); + assert!( + radix.recurrent_exact("model", &[1, 3]).is_none(), + "the older conversation leaves before the fresh boundary" + ); +} + +#[test] +fn soft_pressure_keeps_a_branch_point_sibling_conversations_still_match() { + // Regression: the attention-derived soft cap sits below one indivisible + // snapshot, so the soft pass runs on every insert. Evicting superseded + // checkpoints under it removed the shared-prefix checkpoint the moment + // its own conversation extended past it, and every sibling branch that + // diverges at that prefix lost its only reusable entry. Recency and + // the floor bound the soft pass; only the hard ceiling may reclaim + // superseded entries ahead of recency. + let radix = Mutex::new(UnifiedRadixCache::new()); + let blobs = Mutex::new(CacheBlobStore::new(4)); + let budget = StorageBudget::new(); + // The soft cap is below one 32-byte snapshot, so the catalog is over it + // from the first insert; a zero hard cap disables the hard pass. + let always_over_soft = limits(10, 0); + let store = |page, tokens, seed| { + store_exact_radix_record( + &radix, + &blobs, + 512, + always_over_soft, + None, + None, + pending(page, tokens, &distinct_payload(seed, 32), &budget), + ) + .unwrap(); + }; + // Conversations b and c branch off the shared [1, 2] context, and + // conversation a extends past it. + store("a-shared", &[1, 2], 0); + store("b-branch", &[1, 2, 7], 1); + store("c-branch", &[1, 2, 8], 2); + store("a-decode", &[1, 2, 3, 4], 3); + let mut radix = radix.lock().unwrap(); + assert_eq!(radix.stats().recurrent_entries, 4); + assert!( + radix.lookup_recurrent("model", &[1, 2, 6]).is_some(), + "a sibling branch diverging at the shared prefix must still hit it" + ); +} diff --git a/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs b/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs index 799bcb1a..c3beec34 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs +++ b/crates/skippy-serving/src/kv_integration/config/tests/native_spill_failures.rs @@ -9,11 +9,13 @@ fn pending(token: i32, bytes: usize) -> PendingDurableSpill { payload: skippy_cache::ExactStatePayload::kv_recurrent( vec![7; bytes / 2], vec![9; bytes - bytes / 2], - ), + ) + .into(), extra: super::super::super::ExactStateExtra::default(), namespace: "native-test".into(), token_ids: vec![token], native_raw: true, + extension: None, l3_cost: None, } } diff --git a/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs b/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs new file mode 100644 index 00000000..edb08ada --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/config/tests/reserved_admission.rs @@ -0,0 +1,500 @@ +//! Exact-state record admission end to end, on a modelless runtime. +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, + l1_checkpoint_max_bytes: None, + 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(), + retention_priority: 0, + token_ids, + l3_fill_claim: None, + write_through_l3: true, + l2_promotion_manifest: 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() { + skippy_runtime::test_support::require_native_runtime(); + 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/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs b/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs index 5c3407d6..56dd2e25 100644 --- a/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs +++ b/crates/skippy-serving/src/kv_integration/config/tests/runtime_admission.rs @@ -32,12 +32,13 @@ fn absent_weight_identity_disables_disk_without_disabling_native_cache() { } #[test] -fn well_formed_declared_hashes_do_not_authorize_raw_config_disk_reuse() { +fn admitted_model_identity_enables_disk_without_reopening_model_files() { 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"); + let mut config = enabled_auto_config("admitted-model"); config.source_model_sha256 = Some("ab".repeat(32)); config.manifest_sha256 = Some("cd".repeat(32)); + config.model_path = Some(root.path().join("unavailable.gguf").display().to_string()); let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), @@ -54,27 +55,32 @@ fn well_formed_declared_hashes_do_not_authorize_raw_config_disk_reuse() { .unwrap() .unwrap(); assert!(kv.records_resident_prefixes()); - assert!(kv.l3.is_none()); - assert!(kv.durable_payload.is_none()); + let tier = kv.l3.as_ref().expect("admitted model identity enables L3"); + assert_eq!( + tier.model_identity(), + numerical_model_identity_for_stage(&config) + ); + assert_eq!( + tier.state_identity(), + durable_identity::read(&config, "kv-recurrent").unwrap() + ); + assert_eq!( + kv.durable_payload, + Some(StagePrefixCachePayload::KvRecurrent) + ); } #[test] -fn actual_weight_content_separates_disk_and_prefix_keys_under_one_claimed_identity() { - use crate::runtime_state::model_content::VerifiedModelContent; +fn admitted_weight_identity_separates_disk_and_prefix_keys() { 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, + let create = |config: &StageConfig| { + KvStageIntegration::from_loaded_model_with_l3_manager( + config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { resident: true, @@ -83,28 +89,29 @@ fn actual_weight_content_separates_disk_and_prefix_keys_under_one_claimed_identi kv_recurrent: true, full_state: true, }), - content, - || Ok(Some(manager.clone())), + Some(manager.clone()), None, ) .unwrap() .unwrap() }; - std::fs::write(&model, b"first numerical weights").unwrap(); - let first = create(); - let same = create(); + let first = create(&config); + let same = create(&config); 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 changed_config = StageConfig { + source_model_sha256: Some("ef".repeat(32)), + ..config.clone() + }; + let changed = create(&changed_config); let first_l3 = first.l3.as_ref().unwrap(); let changed_l3 = changed.l3.as_ref().unwrap(); - assert_eq!( + assert_ne!( first_l3.model_identity(), changed_l3.model_identity(), - "canonical model lifecycle remains shared" + "different admitted weights have different model identities" ); assert_ne!(first_l3.state_identity(), changed_l3.state_identity()); let base = skippy_protocol::MessageBase { @@ -121,7 +128,7 @@ fn actual_weight_content_separates_disk_and_prefix_keys_under_one_claimed_identi 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]); + let changed_prefix = changed.prefill_identity(&changed_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!( @@ -156,7 +163,7 @@ fn injected_manager_is_shared_across_placement_equivalent_stages() { ..first.clone() }; - let first = KvStageIntegration::from_test_model_with_l3_manager( + let first = KvStageIntegration::from_loaded_model_with_l3_manager( &first, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -171,7 +178,7 @@ fn injected_manager_is_shared_across_placement_equivalent_stages() { ) .unwrap() .unwrap(); - let second = KvStageIntegration::from_test_model_with_l3_manager( + let second = KvStageIntegration::from_loaded_model_with_l3_manager( &second, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -216,7 +223,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_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -261,7 +268,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_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(skippy_runtime::MemoryCacheCapabilities { @@ -294,9 +301,9 @@ fn native_checkpoint_ram_budget_works_without_disk() { .kv_cache .as_mut() .expect("enabled cache config") - .l2_max_bytes = 64 * 1024 * 1024; + .l1_checkpoint_max_bytes = std::num::NonZeroU64::new(64 * 1024 * 1024); - let kv = KvStageIntegration::from_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Hybrid), Some(skippy_runtime::MemoryCacheCapabilities { diff --git a/crates/skippy-serving/src/kv_integration/exact_state.rs b/crates/skippy-serving/src/kv_integration/exact_state.rs index 78783234..0661624d 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state.rs @@ -15,8 +15,8 @@ use super::{ const MAX_PREFIX_PROBES: usize = 64; mod resident_preference; -use resident_preference::DurableRestoreLookup; pub(crate) use resident_preference::PreparedExactStateRestore; +use resident_preference::{DurableFill, DurableRestoreLookup}; mod restore; mod snapshot_headroom; @@ -83,15 +83,24 @@ 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 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. +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 @@ -110,14 +119,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) { @@ -134,7 +145,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 { @@ -154,7 +165,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; } @@ -244,6 +255,7 @@ impl KvStageIntegration { DurableRestoreLookup { started: lookup_started, location, + fill: candidate.fill, }, cold_prefill_cost, )? { @@ -319,6 +331,14 @@ impl KvStageIntegration { "cached KV page token range mismatch for exact-state checkpoint" )); } + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(false); + } let import_started = Instant::now(); runtime.import_kv_page(session_id, desc, kv.as_ref())?; kv_import_ms = import_started.elapsed().as_secs_f64() * 1000.0; @@ -414,6 +434,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) @@ -424,10 +445,11 @@ impl KvStageIntegration { payload, extra, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: stored_tokens, l3_fill_claim: None, write_through_l3: true, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost: None, admission_credit, }), @@ -753,6 +775,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)] @@ -794,6 +817,18 @@ impl KvStageIntegration { self.finish_record(&identity.page_id); return Ok(None); } + // Without L3 there is nowhere for a crowded-out snapshot to spill. + if !already_recorded + && (!write_through_l3 || self.l3.is_none()) + && exact_state_crowded_out( + &self.radix, + self.exact_max_entries, + identity.retention_priority(), + ) + { + self.finish_record(&identity.page_id); + return Ok(None); + } let Some(reservation) = self.reserve_snapshot_host_memory( runtime, session_id, @@ -851,10 +886,11 @@ impl KvStageIntegration { payload, extra, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: identity.token_ids.clone(), l3_fill_claim: None, write_through_l3, - l2_promotion_digest: None, + l2_promotion_manifest: None, l3_cost, admission_credit, }) { @@ -924,6 +960,9 @@ impl KvStageIntegration { { return Ok(Some(restored)); } + if matches!(lookup.fill, DurableFill::Skip) { + return Ok(None); + } // Segment and manifest digests intentionally deduplicate bytes across // numerical states. A fill claim must not: one state's fill cannot // warm another state's radix namespace, even when their payload bytes @@ -938,15 +977,8 @@ impl KvStageIntegration { return Ok(None); } } - let outcome = self.fill_and_import( - runtime, - session_id, - identity, - lookup.started, - l3, - location, - cold_prefill_cost, - ); + let outcome = + self.fill_and_import(runtime, session_id, identity, l3, lookup, cold_prefill_cost); // On success the claim travels with the re-warm record and the worker // releases it once the entry is radix-resident. On any other outcome // release it here. @@ -966,11 +998,12 @@ impl KvStageIntegration { runtime: &mut RuntimeState, session_id: &str, identity: &PrefillKvIdentity, - lookup_started: Instant, l3: &std::sync::Arc, - location: &skippy_cache::L3Location, + lookup: DurableRestoreLookup<'_>, cold_prefill_cost: Option, ) -> Result> { + let location = lookup.location; + let lookup_started = lookup.started; // Native page capability is checked from manifest metadata before the // tier reads any segment bytes. Runtime ABI, platform and numerical // mode are already bound by the tier's exact-state identity; the page @@ -978,18 +1011,24 @@ impl KvStageIntegration { let Ok(native_kv_desc) = preflight_l3_kv_location(location) else { return Ok(None); }; - let fill_started = Instant::now(); // A load failure (corrupt segment, now quarantined) is a miss, not a // request failure. Import failures below do propagate: the transaction // rolls the lane back and the caller falls back to cold prefill. - let fill = match l3.load(location) { - Ok(fill) => fill, - Err(_) => { - if let Some(l2) = &self.l2 { - l2.invalidate_digest(&location.manifest_key); + let (fill, fill_elapsed, prior_fill_elapsed) = match lookup.fill { + DurableFill::Staged(staged) => (staged.fill.clone(), staged.elapsed, staged.elapsed), + DurableFill::Inline => { + let started = Instant::now(); + match l3.load(location) { + Ok(fill) => (fill, started.elapsed(), std::time::Duration::ZERO), + Err(_) => { + if let Some(l2) = &self.l2 { + l2.invalidate_digest(&location.manifest_key); + } + return Ok(None); + } } - return Ok(None); } + DurableFill::Skip => return Ok(None), }; if fill.payload.byte_len() == 0 { return Ok(None); @@ -1005,7 +1044,7 @@ impl KvStageIntegration { if !self.native_payload_is_complete(fill.payload.kind()) { return Ok(None); } - let fill_ms = fill_started.elapsed().as_secs_f64() * 1000.0; + let fill_ms = fill_elapsed.as_secs_f64() * 1000.0; let token_count = fill.token_count; let kv_desc: Option = native_kv_desc.or_else(|| { fill.kv_desc_json @@ -1090,6 +1129,14 @@ impl KvStageIntegration { return Ok(None); } if let Some((kv, desc)) = kv_page { + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(None); + } let import_started = Instant::now(); if fill.cachegen_kv { runtime.import_cachegen_kv_page(session_id, desc, kv.as_ref())?; @@ -1123,26 +1170,28 @@ impl KvStageIntegration { fill.payload.byte_len() }; let payload_kind = fill.payload.kind(); - let restore_cost = lookup_started.elapsed().as_secs_f64() * 1_000.0; + let restore_cost = (prior_fill_elapsed + lookup_started.elapsed()).as_secs_f64() * 1_000.0; l3.benefit_observe_l3_restore( &identity.namespace, &identity.token_ids[..token_count as usize], - location, + &fill.manifest, cold_prefill_cost, restore_cost, ); - // 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 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); + let resident = self.records_resident_prefixes(); + let tokens = &identity.token_ids[..token_count as usize]; + if resident { + self.rewarm_resident_prefix(runtime, session_id, identity, tokens)?; } - if fill.cachegen_kv || self.records_resident_prefixes() { + let l2_promotion_manifest = if fill.cachegen_kv { + None + } else { + self.l2.as_ref().and_then(|l2| { + l2.consider_l3_fill(&location.manifest_key, token_count, fill.payload.byte_len()) + .then(|| Box::new(fill.manifest)) + }) + }; + if fill.cachegen_kv || (resident && l2_promotion_manifest.is_none()) { return Ok(Some(ExactStateRestore { page_id: identity.page_id.clone(), token_count: token_count as usize, @@ -1164,13 +1213,10 @@ impl KvStageIntegration { rewarm_enqueued: false, })); } - let l2_promotion_digest = self.l2.as_ref().and_then(|l2| { - l2.consider_l3_fill(&location.manifest_key, token_count, fill.payload.byte_len()) - .then(|| location.manifest_key.clone()) - }); let rewarm_enqueued = ExactStateAdmissionCredit::acquire( &self.admission_outstanding, &self.admission_best_effort_outstanding, + self.admission_total_cap, CaptureAdmission::BestEffort, ) .is_some_and(|admission_credit| { @@ -1180,10 +1226,11 @@ impl KvStageIntegration { payload: fill.payload, extra: ExactStateExtra { kv_desc }, namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), token_ids: identity.token_ids[..token_count as usize].to_vec(), l3_fill_claim: Some(l3_fill_claim_key(l3, location)), write_through_l3: false, - l2_promotion_digest, + l2_promotion_manifest, l3_cost: None, admission_credit, }), @@ -1255,6 +1302,25 @@ fn try_touch_exact_state( } } +/// Whether a new entry kept at `retention` would be evicted again as soon as +/// it is stored: the cache is full and every entry it could evict outranks +/// it (a higher request tier's). Exporting it would only cost the copy. +fn exact_state_crowded_out( + radix: &std::sync::Mutex< + skippy_cache::UnifiedRadixCache, + >, + max_entries: usize, + retention: u64, +) -> bool { + let Ok(radix) = radix.try_lock() else { + return false; + }; + radix.stats().recurrent_entries >= max_entries + && radix + .recurrent_victim_retention(super::RadixExactEntry::retention_priority) + .is_none_or(|victim| victim > retention) +} + fn is_native_kv_unavailable(error: &anyhow::Error) -> bool { error.chain().any(|cause| { let message = cause.to_string(); @@ -1309,7 +1375,10 @@ mod tests { use skippy_cache::{L3Location, UnifiedRadixCache}; - use super::{is_native_kv_unavailable, preflight_l3_kv_location, try_touch_exact_state}; + use super::{ + exact_state_crowded_out, is_native_kv_unavailable, preflight_l3_kv_location, + try_touch_exact_state, + }; type TestRadix = UnifiedRadixCache< crate::kv_integration::RadixResidentEntry, @@ -1322,6 +1391,35 @@ mod tests { assert!(is_native_kv_unavailable(&error)); } + #[test] + fn a_snapshot_every_stored_entry_outranks_is_not_exported_into_a_full_cache() { + let cache = Mutex::new(TestRadix::new()); + for (index, retention) in [(1, 2), (2, 2)] { + cache + .lock() + .unwrap() + .insert_recurrent( + "namespace", + &[index], + 32, + crate::kv_integration::RadixExactEntry::new( + format!("page-{index}"), + crate::kv_integration::ExactStatePayload::full_state(vec![1]), + crate::kv_integration::ExactStateExtra::default(), + false, + ) + .with_retention_priority(retention), + ) + .unwrap(); + } + // Full of entries kept at 2: a 0 would evict itself; a 2 evicts the + // older of its peers. + assert!(exact_state_crowded_out(&cache, 2, 0)); + assert!(!exact_state_crowded_out(&cache, 2, 2)); + // With room to spare, any snapshot is kept. + assert!(!exact_state_crowded_out(&cache, 3, 0)); + } + #[test] fn busy_exact_state_lock_skips_touch_without_waiting() { let cache = Arc::new(Mutex::new(TestRadix::new())); @@ -1442,6 +1540,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"); @@ -1456,17 +1555,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!( @@ -1479,11 +1581,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" @@ -1491,15 +1601,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!( @@ -1533,9 +1696,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)); } } @@ -1576,6 +1742,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"); @@ -1599,7 +1766,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" @@ -1630,10 +1798,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" @@ -1657,12 +1830,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"); @@ -1682,7 +1857,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" @@ -1710,8 +1886,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/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs index af1dcf16..db9ff57a 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference.rs @@ -1,14 +1,41 @@ //! Compare token metadata before choosing a warm alias or loading durable bytes. use super::*; +use std::{ + sync::atomic::{AtomicBool, Ordering}, + time::Duration, +}; pub(super) struct RestoreCandidate<'a> { pub(super) identity: &'a PrefillKvIdentity, pub(super) location: Option<&'a skippy_cache::L3Location>, + pub(super) fill: DurableFill<'a>, } pub(super) struct DurableRestoreLookup<'a> { pub(super) started: Instant, pub(super) location: &'a skippy_cache::L3Location, + pub(super) fill: DurableFill<'a>, +} + +#[derive(Clone, Copy)] +pub(super) enum DurableFill<'a> { + Inline, + Staged(&'a StagedL3Restore), + Skip, +} + +struct StagingLease(Arc); + +impl Drop for StagingLease { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +pub(super) struct StagedL3Restore { + pub(super) fill: skippy_cache::L3Fill, + pub(super) elapsed: Duration, + _lease: StagingLease, } /// Durable metadata resolved before entering a scheduled runtime operation. @@ -16,6 +43,8 @@ pub(super) struct DurableRestoreLookup<'a> { pub(crate) struct PreparedExactStateRestore { identities: Vec, locations: Vec>, + staged: Option, + allow_inline_fill: bool, } impl PreparedExactStateRestore { @@ -23,6 +52,20 @@ impl PreparedExactStateRestore { pub(crate) fn identities(&self) -> &[PrefillKvIdentity] { &self.identities } + + fn fill_for(&self, location: Option<&skippy_cache::L3Location>) -> DurableFill<'_> { + if self.allow_inline_fill { + return DurableFill::Inline; + } + match (&self.staged, location) { + (Some(staged), Some(location)) + if staged.fill.manifest.payload_digest == location.manifest_key => + { + DurableFill::Staged(staged) + } + _ => DurableFill::Skip, + } + } } impl KvStageIntegration { @@ -61,7 +104,102 @@ impl KvStageIntegration { PreparedExactStateRestore { identities: identities.to_vec(), locations, + staged: None, + allow_inline_fill: true, + } + } + + /// Stage one disk candidate before the standalone request takes the + /// runtime. A busy reader, expired budget or failed load is a cache miss. + pub(crate) fn prepare_standalone_restore( + &self, + identities: &[PrefillKvIdentity], + deadline: Instant, + estimate_prefill_ms: impl FnOnce(usize) -> Option, + ) -> PreparedExactStateRestore { + let mut prepared = self.prepare_exact_state_restore(identities, false); + prepared.allow_inline_fill = false; + let candidate = self + .ordered_restore_candidates(&prepared) + .into_iter() + .find(|candidate| { + candidate + .location + .is_some_and(|location| preflight_l3_kv_location(location).is_ok()) + }); + if let Some(candidate) = candidate + && let Some(location) = candidate.location + && !self + .l2 + .as_ref() + .is_some_and(|tier| tier.contains_location(candidate.identity, location)) + && let Some(l3) = &self.l3 + { + let resident = self.longest_resident(&prepared.identities); + let saved = usize::try_from(location.token_count.saturating_sub(resident)).unwrap_or(0); + let recompute_ms = estimate_prefill_ms(saved).filter(|ms| ms.is_finite() && *ms > 0.0); + let wait = recompute_ms.map_or(Duration::from_secs(1), |ms| { + Duration::from_secs_f64(ms.min(1000.0) / 1000.0) + }); + let available = wait.min(deadline.saturating_duration_since(Instant::now())); + if !available.is_zero() { + let staged = self.stage_l3_fill(l3.clone(), location.clone(), available); + if staged.is_some() + && let Some(sender) = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + { + sender.remember_loaded( + &candidate.identity.namespace, + &candidate.identity.token_ids, + location, + ); + } + prepared.staged = staged; + } } + prepared + } + + fn stage_l3_fill( + &self, + tier: Arc, + location: skippy_cache::L3Location, + wait: Duration, + ) -> Option { + self.l3_staging + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .ok()?; + let lease = StagingLease(self.l3_staging.clone()); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + std::thread::Builder::new() + .name("skippy-l3-read".into()) + .spawn(move || { + let start = Instant::now(); + if let Ok(fill) = + tier.load_bounded(&location, super::super::EXACT_STATE_RECORD_QUEUE_BYTES) + { + let _ = tx.send(StagedL3Restore { + fill, + elapsed: start.elapsed(), + _lease: lease, + }); + } + }) + .ok()?; + rx.recv_timeout(wait).ok() + } + + fn longest_resident(&self, identities: &[PrefillKvIdentity]) -> u64 { + identities + .iter() + .filter_map(|identity| self.probe_resident_prefix(identity)) + .map(|hit| hit.token_count as u64) + .max() + .unwrap_or(0) } pub(super) fn ordered_restore_candidates<'a>( @@ -76,16 +214,11 @@ impl KvStageIntegration { .map(|(identity, location)| RestoreCandidate { identity, location: location.as_ref(), + fill: prepared.fill_for(location.as_ref()), }) .collect(); } - 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 resident = self.longest_resident(&prepared.identities); let mut durable = prepared .identities .iter() @@ -98,6 +231,7 @@ impl KvStageIntegration { RestoreCandidate { identity, location: Some(location), + fill: prepared.fill_for(Some(location)), }, )) }) diff --git a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs index 32f22f0c..acd041df 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/resident_preference/tests.rs @@ -22,6 +22,7 @@ fn fixture(root: &Path) -> (KvStageIntegration, PrefillKvIdentity) { max_entries: 8, max_bytes: 0, l2_max_bytes: 1024, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), shared_prefix_stride_tokens: 1, @@ -31,7 +32,7 @@ fn fixture(root: &Path) -> (KvStageIntegration, PrefillKvIdentity) { }), ..StageConfig::default() }; - let kv = KvStageIntegration::from_test_model_with_l3_manager( + let kv = KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(MemoryCacheCapabilities { @@ -83,6 +84,7 @@ fn resident(kv: &KvStageIntegration, identity: &PrefillKvIdentity, count: usize, seq_id: seq, token_count: count as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); diff --git a/crates/skippy-serving/src/kv_integration/exact_state/restore.rs b/crates/skippy-serving/src/kv_integration/exact_state/restore.rs index d69067c3..2a42aa48 100644 --- a/crates/skippy-serving/src/kv_integration/exact_state/restore.rs +++ b/crates/skippy-serving/src/kv_integration/exact_state/restore.rs @@ -2,6 +2,37 @@ use super::*; impl KvStageIntegration { + /// Exact prefix import materializes KV cells before suffix admission. + /// Make room in the same runtime operation as the import. Protect a + /// matching resident prefix so it can still serve a failed durable fill. + pub(in crate::kv_integration) fn admit_native_prefix_import( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_count: u64, + ) -> Result { + if self.payload != StagePrefixCachePayload::ResidentKv + || runtime.session_token_count(session_id).unwrap_or_default() != 0 + { + // In-place imports own an existing range and can replace its cells. + return Ok(true); + } + let capacity = u64::from(runtime.kv_pool_tokens()); + if token_count > capacity { + return Ok(false); + } + runtime.ensure_session_active(session_id)?; + let free_cells = capacity.saturating_sub(runtime.memory_used_cells(session_id)?); + if free_cells >= token_count { + return Ok(true); + } + let protected = self.probe_resident_prefix(identity).map(|hit| hit.seq_id); + Ok(self + .admit_resident_capacity(runtime, session_id, token_count, 0, 0, protected)? + .admitted) + } + /// 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( diff --git a/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs b/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs new file mode 100644 index 00000000..3ff4a664 --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/exact_state_record_queue_tests.rs @@ -0,0 +1,521 @@ +//! Tests for the bounded exact-state record queue and its worker. + +use skippy_cache::ExactStatePayload; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, + mpsc::sync_channel, +}; + +use super::{ + BTreeSet, EXACT_STATE_RECORD_CAPACITY, ExactStateExtra, ExactStateRecordAdmission, + ExactStateRecordWorker, ExactStateWorkerHandles, KvLifecycleEvent, KvLifecycleObserver, + PendingExactStateRecord, enqueue_exact_state_record, run_exact_state_record_job, +}; +use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; + +/// A fresh, observable budget: the SAME counters back every credit a test +/// creates, so release paths are asserted on real accounting, not on +/// throwaway stubs. +fn budget() -> (Arc, Arc) { + (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))) +} + +fn credit( + total: &Arc, + best_effort: &Arc, + class: CaptureAdmission, +) -> ExactStateAdmissionCredit { + ExactStateAdmissionCredit::acquire( + total, + best_effort, + crate::kv_integration::exact_state::EXACT_STATE_ADMISSION_TOTAL, + class, + ) + .expect("a fresh budget must admit") +} + +struct RecordingObserver(Arc>>); + +impl KvLifecycleObserver for RecordingObserver { + fn observe(&self, event: KvLifecycleEvent) { + self.0.lock().unwrap().push(event); + } +} + +fn pending(page_id: &str, admission_credit: ExactStateAdmissionCredit) -> PendingExactStateRecord { + PendingExactStateRecord { + page_id: page_id.to_string(), + payload: ExactStatePayload::full_state(vec![1]), + extra: ExactStateExtra::default(), + namespace: "test".to_string(), + retention_priority: 0, + token_ids: vec![1], + l3_fill_claim: None, + write_through_l3: true, + l2_promotion_manifest: None, + l3_cost: None, + admission_credit, + } +} + +fn pending_with_bytes(page_id: &str, bytes: usize) -> PendingExactStateRecord { + let (total, best_effort) = budget(); + PendingExactStateRecord { + payload: ExactStatePayload::full_state(vec![1; bytes]), + ..pending( + page_id, + credit(&total, &best_effort, CaptureAdmission::BestEffort), + ) + } +} + +const CAP: u64 = 1024; + +#[test] +fn final_worker_owner_drains_queued_records_before_drop_returns() { + let (sender, receiver) = sync_channel(2); + let completed = Arc::new(AtomicUsize::new(0)); + let worker_completed = completed.clone(); + let task = std::thread::spawn(move || { + while receiver.recv().is_ok() { + worker_completed.fetch_add(1, Ordering::Release); + } + }); + let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None, None)); + let (total, best_effort) = budget(); + worker.with_sender(|sender| { + sender + .unwrap() + .send(pending( + "latest", + credit(&total, &best_effort, CaptureAdmission::BestEffort), + )) + .unwrap() + }); + + drop(worker); + + assert_eq!(completed.load(Ordering::Acquire), 1); +} + +#[test] +fn queue_is_bounded_in_bytes_not_entries() { + let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); + let inflight = Mutex::new(BTreeSet::from(["a".to_string(), "b".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("a", 700), + ), + ExactStateRecordAdmission::Queued + ); + assert_eq!(queue_bytes.load(Ordering::Relaxed), 700); + + // Plenty of entry slots left; the bytes are what is full. + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("b", 700), + ), + ExactStateRecordAdmission::DroppedFull + ); + assert_eq!( + queue_bytes.load(Ordering::Relaxed), + 700, + "a dropped record left bytes claimed" + ); + assert!(!inflight.lock().unwrap().contains("b")); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 1); +} + +#[test] +fn one_oversized_record_is_admitted_into_an_empty_queue() { + let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); + let inflight = Mutex::new(BTreeSet::from(["huge".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending_with_bytes("huge", 4096), + ), + ExactStateRecordAdmission::Queued, + "a large model could never record if one export over the cap were refused" + ); + assert_eq!(queue_bytes.load(Ordering::Relaxed), 4096); + assert!(queue_bytes.load(Ordering::Acquire) >= CAP); +} + +#[test] +fn finishing_a_record_releases_its_bytes() { + let inflight = Mutex::new(BTreeSet::from(["done".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(300); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + None, + pending_with_bytes("done", 300), + |_| Ok(()), + ); + + assert_eq!(queue_bytes.load(Ordering::Relaxed), 0); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!(dropped.load(Ordering::Relaxed), 0); +} + +#[test] +fn full_queue_drops_optional_record_and_releases_inflight_page() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + // One BestEffort record occupies the channel buffer; its credit stays + // observable in `total`. + sender + .send(pending( + "queued", + credit(&total, &best_effort, CaptureAdmission::BestEffort), + )) + .unwrap(); + let inflight = Mutex::new(BTreeSet::from(["dropped".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "dropped", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::DroppedFull + ); + assert!(!inflight.lock().unwrap().contains("dropped")); + assert_eq!(queued.load(Ordering::Relaxed), 0); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 1, + "the Full rejection must release the dropped record's credit; the buffered one stays" + ); + assert_eq!( + best_effort.load(Ordering::Acquire), + 1, + "the buffered BestEffort credit is still outstanding" + ); + + // Receiver drop: discarding the channel drops the buffered record and + // releases its credit too. + drop(sender); + drop(receiver); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "receiver drop released the buffered credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn disconnected_worker_releases_inflight_page() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + drop(receiver); + let inflight = Mutex::new(BTreeSet::from(["orphaned".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(0); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "orphaned", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::WorkerStopped + ); + assert!(!inflight.lock().unwrap().contains("orphaned")); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the disconnected channel must release the orphaned credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn worker_keeps_page_inflight_until_record_finishes() { + let (total, best_effort) = budget(); + let (sender, receiver) = sync_channel(1); + let inflight = Arc::new(Mutex::new(BTreeSet::from(["page".to_string()]))); + let worker_inflight = inflight.clone(); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = Arc::new(AtomicUsize::new(0)); + let worker_pending_count = pending_count.clone(); + let queue_bytes = AtomicU64::new(0); + let worker_healthy = AtomicBool::new(true); + + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "page", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::Queued + ); + assert!(inflight.lock().unwrap().contains("page")); + assert_eq!( + total.load(Ordering::Acquire), + 1, + "the credit is outstanding while the record sits in the channel" + ); + + let worker = std::thread::spawn(move || { + let pending = receiver.recv().unwrap(); + assert!(worker_inflight.lock().unwrap().contains(&pending.page_id)); + worker_inflight.lock().unwrap().remove(&pending.page_id); + worker_pending_count.fetch_sub(1, Ordering::Relaxed); + // `pending` (and its credit) drops when this closure returns. + }); + worker.join().unwrap(); + + assert!(!inflight.lock().unwrap().contains("page")); + assert_eq!(queued.load(Ordering::Relaxed), 1); + assert_eq!(dropped.load(Ordering::Relaxed), 0); + assert_eq!(pending_count.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the credit released when the record dropped after processing" + ); +} + +#[test] +fn worker_success_notifies_completed_not_mere_admission() { + let inflight = Mutex::new(BTreeSet::from(["written".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let events: Arc>> = Arc::default(); + let observer: Arc = Arc::new(RecordingObserver(events.clone())); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + Some(&observer), + pending( + "written", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| Ok(()), + ); + + assert_eq!( + *events.lock().unwrap(), + vec![KvLifecycleEvent::ExactStateRecordCompleted] + ); + assert_eq!(dropped.load(Ordering::Relaxed), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "successful completion released the real credit" + ); +} + +#[test] +fn worker_write_error_notifies_failed_not_completed() { + let inflight = Mutex::new(BTreeSet::from(["broken".to_string()])); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let events: Arc>> = Arc::default(); + let observer: Arc = Arc::new(RecordingObserver(events.clone())); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + Some(&observer), + pending( + "broken", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| anyhow::bail!("simulated write failure"), + ); + + assert_eq!( + *events.lock().unwrap(), + vec![KvLifecycleEvent::ExactStateRecordFailed] + ); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the worker error path released the real credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); +} + +#[test] +fn worker_panic_fails_closed_and_releases_all_record_bookkeeping() { + let (sender, _receiver) = sync_channel(1); + let inflight = Mutex::new(BTreeSet::from(["panicked".to_string()])); + let queued = AtomicU64::new(0); + let dropped = AtomicU64::new(0); + let pending_count = AtomicUsize::new(1); + let queue_bytes = AtomicU64::new(1); + let worker_healthy = AtomicBool::new(true); + let worker_panics = AtomicU64::new(0); + let (total, best_effort) = budget(); + + run_exact_state_record_job( + ExactStateWorkerHandles { + inflight_records: &inflight, + dropped: &dropped, + pending_count: &pending_count, + queue_bytes: &queue_bytes, + worker_healthy: &worker_healthy, + worker_panics: &worker_panics, + }, + None, + pending( + "panicked", + credit(&total, &best_effort, CaptureAdmission::Continuation), + ), + |_| panic!("injected exact-record worker failure"), + ); + + assert!(!worker_healthy.load(Ordering::Acquire)); + assert_eq!(worker_panics.load(Ordering::Relaxed), 1); + assert_eq!(dropped.load(Ordering::Relaxed), 1); + assert_eq!(pending_count.load(Ordering::Acquire), 0); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the unwind dropped the record and released its real credit" + ); + assert_eq!(best_effort.load(Ordering::Acquire), 0); + + inflight.lock().unwrap().insert("later".to_string()); + assert_eq!( + enqueue_exact_state_record( + &sender, + &inflight, + &queued, + &dropped, + &pending_count, + &queue_bytes, + CAP, + &worker_healthy, + pending( + "later", + credit(&total, &best_effort, CaptureAdmission::Continuation) + ), + ), + ExactStateRecordAdmission::WorkerStopped + ); + assert!(inflight.lock().unwrap().is_empty()); + assert_eq!(dropped.load(Ordering::Relaxed), 2); + assert_eq!(pending_count.load(Ordering::Acquire), 0); + assert_eq!( + total.load(Ordering::Acquire), + 0, + "the WorkerStopped follow-up also released its real credit" + ); +} diff --git a/crates/skippy-serving/src/kv_integration/identity.rs b/crates/skippy-serving/src/kv_integration/identity.rs index 675c8359..a1f4c7ad 100644 --- a/crates/skippy-serving/src/kv_integration/identity.rs +++ b/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: self.bind_model_content(prefix.prefix_hash.clone()), + prefix_hash: prefix.prefix_hash, session_id: base.session_id.clone(), token_start, token_count: prefix.token_count, @@ -46,25 +46,21 @@ impl KvStageIntegration { position_config_hash: format!("ctx:{}", config.ctx_size), kv_dtype: NATIVE_KV_DTYPE.to_string(), }; + let namespace = + prefix_namespace_hash(config, token_start, base.chat_template_id.as_deref()); + let namespace = self + .l3 + .as_ref() + .map(|tier| durable_namespace(&namespace, tier.state_identity())) + .unwrap_or(namespace); PrefillKvIdentity { identity, - 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(), - )), + page_id: prefix.page_id, + namespace, 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, @@ -203,6 +199,17 @@ impl KvStageIntegration { } } +/// Extend the serving radix namespace without changing the public page ID. +/// Distinct native identities must have separate durable prefix indexes even +/// when they use byte-identical user prompts and cache scopes. +pub(super) fn durable_namespace(prefix_namespace: &str, state_identity: &str) -> String { + let mut hash = blake3::Hasher::new(); + hash.update(b"skippy-durable-prefix-v1"); + hash.update(prefix_namespace.as_bytes()); + hash.update(state_identity.as_bytes()); + format!("blake3:{}", hash.finalize().to_hex()) +} + #[cfg(test)] mod tests { use crate::kv_integration::ExactStateExtra; @@ -261,6 +268,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 64, shared_prefix_stride_tokens: 32, diff --git a/crates/skippy-serving/src/kv_integration/l2_serving.rs b/crates/skippy-serving/src/kv_integration/l2_serving.rs index 3bb264da..3963239d 100644 --- a/crates/skippy-serving/src/kv_integration/l2_serving.rs +++ b/crates/skippy-serving/src/kv_integration/l2_serving.rs @@ -5,7 +5,7 @@ use std::{ }; use anyhow::{Context, Result}; -use skippy_cache::{L2Hit, L2Origin, L2Stats, L2Tier, l2_cache_key}; +use skippy_cache::{ExactStatePayload, L2Hit, L2Stats, L2Tier, l2_cache_key}; use skippy_runtime::RuntimeKvPageDesc; use crate::runtime_state::RuntimeState; @@ -18,7 +18,6 @@ use super::{ records::add_reconstruct_stats, }; -const PROMOTION_MAX_BYTES: u64 = 64 * 1024 * 1024; const RESTORE_WORTH_TOKENS: u64 = 4_096; const SECOND_HIT_WINDOW: Duration = Duration::from_secs(10 * 60); const MAX_PROMOTION_OBSERVATIONS: usize = 4_096; @@ -75,6 +74,25 @@ impl StageL2 { let _ = self.tier.remove(key); } + pub(super) fn contains_location( + &self, + identity: &PrefillKvIdentity, + location: &skippy_cache::L3Location, + ) -> bool { + let Ok(token_count) = usize::try_from(location.token_count) else { + return false; + }; + let Some(tokens) = identity.token_ids.get(..token_count) else { + return false; + }; + self.tier + .peek(&self.cache_key(&identity.namespace, tokens)) + .is_some_and(|hit| { + hit.token_count == location.token_count + && hit.payload_digest == location.manifest_key + }) + } + pub(crate) fn invalidate_digest(&self, payload_digest: &str) { let _ = self.tier.remove_by_digest(payload_digest); } @@ -92,31 +110,19 @@ impl StageL2 { &self, namespace: &str, tokens: &[i32], - expected_payload_digest: &str, + manifest: &skippy_cache::HandoffManifest, payload: &skippy_cache::ExactStatePayload, - extra: &ExactStateExtra, ) -> bool { let key = self.cache_key(namespace, tokens); - let kv_desc_json = extra - .kv_desc - .as_ref() - .and_then(|desc| serde_json::to_string(desc).ok()); let admitted = self .tier - .admit_payload( - key, - tokens.len() as u64, - expected_payload_digest, - payload, - kv_desc_json, - L2Origin::FromL3, - ) + .admit_manifest_payload(key, manifest, payload) .is_ok(); if let Some(observation) = self .promotions .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .get_mut(expected_payload_digest) + .get_mut(&manifest.payload_digest) { observation.terminal = true; } @@ -137,6 +143,11 @@ impl StageL2 { } fn should_promote(&self, manifest_key: &str, token_count: u64, payload_bytes: u64) -> bool { + // A complete hybrid snapshot may be large even for a short prefix. + // The configured host budget bounds admission for every state layout. + if payload_bytes > self.tier.budget_bytes() { + return false; + } let now = Instant::now(); let mut observations = self .promotions @@ -171,10 +182,6 @@ impl StageL2 { return false; } observation.hits = observation.hits.saturating_add(1); - if payload_bytes > PROMOTION_MAX_BYTES { - observation.terminal = true; - return false; - } // Keep the observation eligible until the worker has attempted the // promotion. If the bounded worker queue drops this fill, the next L3 // restore may retry instead of suppressing the entry for ten minutes. @@ -248,29 +255,68 @@ impl KvStageIntegration { kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; } StagePrefixCachePayload::KvRecurrent => { - if let Some((kv, stats)) = payload - .kv_bytes_timed() - .context("reconstruct L2 KV payload") - .map_err(|error| mark_failure(&mut deterministic_failure, error))? - { - add_reconstruct_stats( - &mut reconstruct_ms, - &mut reconstruct_bytes, - &mut reconstruct_blocks, - stats, - ); + let (recurrent, stats) = payload + .recurrent_state_bytes_timed() + .context("reconstruct L2 recurrent payload") + .map_err(|error| mark_failure(&mut deterministic_failure, error))?; + if recurrent.is_empty() && !self.dense_without_recurrent { + deterministic_failure = true; + anyhow::bail!("L2 recurrent-state payload is empty"); + } + add_reconstruct_stats( + &mut reconstruct_ms, + &mut reconstruct_bytes, + &mut reconstruct_blocks, + stats, + ); + if let ExactStatePayload::KvRecurrent { kv, .. } = &payload { match kv_desc.as_ref() { Some(desc) => { - desc.validate_payload(kv.len()).map_err(|error| { + let kv_len = usize::try_from(kv.len()) + .context("L2 KV payload exceeds addressable memory") + .map_err(|error| { + mark_failure(&mut deterministic_failure, error) + })?; + desc.validate_payload(kv_len).map_err(|error| { mark_failure(&mut deterministic_failure, error) })?; if desc.token_start != 0 || desc.token_count != token_count { deterministic_failure = true; anyhow::bail!("L2 KV page token range mismatch"); } + if !self.admit_native_prefix_import( + runtime, + session_id, + identity, + token_count, + )? { + return Ok(false); + } let started = Instant::now(); - runtime.import_kv_page(session_id, desc, kv.as_ref())?; - kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + let imported = match hit.kv_chunks() { + Some(chunks) => runtime + .try_import_kv_page_chunks(session_id, desc, chunks)?, + None => false, + }; + if imported { + kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + } else { + let (bytes, stats) = kv + .as_cow_timed() + .context("reconstruct L2 KV payload") + .map_err(|error| { + mark_failure(&mut deterministic_failure, error) + })?; + add_reconstruct_stats( + &mut reconstruct_ms, + &mut reconstruct_bytes, + &mut reconstruct_blocks, + stats, + ); + let started = Instant::now(); + runtime.import_kv_page(session_id, desc, bytes.as_ref())?; + kv_import_ms = started.elapsed().as_secs_f64() * 1000.0; + } } None if !kv.is_empty() => { deterministic_failure = true; @@ -279,20 +325,6 @@ impl KvStageIntegration { None => {} } } - let (recurrent, stats) = payload - .recurrent_state_bytes_timed() - .context("reconstruct L2 recurrent payload") - .map_err(|error| mark_failure(&mut deterministic_failure, error))?; - if recurrent.is_empty() && !self.dense_without_recurrent { - deterministic_failure = true; - anyhow::bail!("L2 recurrent-state payload is empty"); - } - add_reconstruct_stats( - &mut reconstruct_ms, - &mut reconstruct_bytes, - &mut reconstruct_blocks, - stats, - ); let started = Instant::now(); if recurrent.is_empty() { runtime.set_session_position(session_id, token_count)?; @@ -325,29 +357,37 @@ impl KvStageIntegration { } let logical_bytes = payload.byte_len(); let payload_kind = payload.kind(); - let rewarm_enqueued = ExactStateAdmissionCredit::acquire( - &self.admission_outstanding, - &self.admission_best_effort_outstanding, - CaptureAdmission::BestEffort, - ) - .is_some_and(|admission_credit| { - self.try_begin_record(&identity.page_id) - && matches!( - self.enqueue_exact_state_record(PendingExactStateRecord { - page_id: identity.page_id.clone(), - payload, - extra: ExactStateExtra { kv_desc }, - namespace: identity.namespace.clone(), - token_ids: identity.token_ids[..token_count as usize].to_vec(), - l3_fill_claim: None, - write_through_l3: false, - l2_promotion_digest: None, - l3_cost: None, - admission_credit, - }), - ExactStateRecordAdmission::Queued - ) - }); + let tokens = &identity.token_ids[..token_count as usize]; + let rewarm_enqueued = if self.records_resident_prefixes() { + self.rewarm_resident_prefix(runtime, session_id, identity, tokens)?; + false + } else { + ExactStateAdmissionCredit::acquire( + &self.admission_outstanding, + &self.admission_best_effort_outstanding, + self.admission_total_cap, + CaptureAdmission::BestEffort, + ) + .is_some_and(|admission_credit| { + self.try_begin_record(&identity.page_id) + && matches!( + self.enqueue_exact_state_record(PendingExactStateRecord { + page_id: identity.page_id.clone(), + payload, + extra: ExactStateExtra { kv_desc }, + namespace: identity.namespace.clone(), + retention_priority: identity.retention_priority(), + token_ids: tokens.to_vec(), + l3_fill_claim: None, + write_through_l3: false, + l2_promotion_manifest: None, + l3_cost: None, + admission_credit, + }), + ExactStateRecordAdmission::Queued + ) + }) + }; Ok(Some(ExactStateRestore { page_id: identity.page_id.clone(), token_count: token_count as usize, @@ -372,6 +412,30 @@ fn mark_failure(deterministic: &mut bool, error: anyhow::Error) -> anyhow::Error error } +#[cfg(test)] +pub(super) fn legacy_test_manifest( + token_count: u64, + bytes: &[u8], +) -> skippy_cache::HandoffManifest { + let mut manifest = + skippy_cache::HandoffManifest::new("test".to_owned(), "full-state".to_owned()); + manifest.token_count = token_count; + manifest.total_bytes = bytes.len() as u64; + manifest.kv_bytes = manifest.total_bytes; + manifest.payload_digest = skippy_cache::segment_digest(bytes); + manifest.segments.push(skippy_cache::HandoffSegmentRef { + index: 0, + offset: 0, + bytes: manifest.total_bytes, + digest: manifest.payload_digest.clone(), + codec_identity: Some(skippy_cache::SegmentCodecIdentity::raw( + manifest.total_bytes, + )), + meta_json: None, + }); + manifest +} + #[cfg(test)] mod tests { use super::*; @@ -413,9 +477,8 @@ mod tests { assert!(l2.promote( &identity.namespace, &identity.token_ids[..3], - &digest, + &legacy_test_manifest(3, &[7; 128]), &payload, - &ExactStateExtra { kv_desc: None }, )); assert!(!l2.consider_l3_fill(&digest, 3, payload.byte_len())); @@ -428,25 +491,26 @@ mod tests { #[test] fn restart_class_prefix_promotes_on_first_fill_but_oversized_payload_does_not() { - let l2 = StageL2::new(1 << 20, "model".to_string(), "state".to_string()); - assert!(l2.consider_l3_fill("restart", RESTORE_WORTH_TOKENS, 1 << 20)); - assert!(!l2.consider_l3_fill("oversized", RESTORE_WORTH_TOKENS, PROMOTION_MAX_BYTES + 1,)); - assert!(!l2.consider_l3_fill("oversized", RESTORE_WORTH_TOKENS, PROMOTION_MAX_BYTES,)); + let budget = 128 * 1024 * 1024; + let l2 = StageL2::new(budget, "model".to_string(), "state".to_string()); + assert!(l2.consider_l3_fill("restart", RESTORE_WORTH_TOKENS, budget)); + assert!(!l2.consider_l3_fill("oversized", RESTORE_WORTH_TOKENS, budget + 1)); + let hybrid_bytes = 84 * 1024 * 1024; + assert!(!l2.consider_l3_fill("hybrid", 532, hybrid_bytes)); + assert!(l2.consider_l3_fill("hybrid", 532, hybrid_bytes)); } #[test] fn a_changed_durable_digest_invalidates_the_mirror() { let l2 = StageL2::new(1 << 20, "model".to_string(), "state".to_string()); let bytes = vec![7; 128]; - let digest = skippy_cache::segment_digest(&bytes); let payload = skippy_cache::ExactStatePayload::full_state(bytes); let identity = identity(vec![1, 2, 3]); assert!(l2.promote( &identity.namespace, &identity.token_ids, - &digest, + &legacy_test_manifest(3, &[7; 128]), &payload, - &ExactStateExtra { kv_desc: None }, )); let changed = location(3, skippy_cache::segment_digest(b"changed")); diff --git a/crates/skippy-serving/src/kv_integration/mod.rs b/crates/skippy-serving/src/kv_integration/mod.rs index 2af9a3cd..a079a6cb 100644 --- a/crates/skippy-serving/src/kv_integration/mod.rs +++ b/crates/skippy-serving/src/kv_integration/mod.rs @@ -159,13 +159,14 @@ 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)] 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. @@ -206,6 +207,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 @@ -253,6 +257,7 @@ pub struct KvStageIntegration { /// stored prefix must not each read it from disk: the loser prefills /// normally while the winner re-warms the radix for everyone. pub(crate) inflight_fills: Arc>>, + l3_staging: Arc, /// The model has attention KV but no recurrent memory, so an exact-state /// entry legitimately carries an empty recurrent snapshot. Restores set /// the position directly instead of importing one. Never true for a @@ -269,8 +274,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 @@ -285,6 +289,9 @@ pub(crate) struct PendingExactStateRecord { pub(crate) payload: ExactStatePayload, pub(crate) extra: ExactStateExtra, pub(crate) namespace: String, + /// Eviction order: lower values are evicted first. See + /// [`PrefillKvIdentity::retention_priority`]. + pub(crate) retention_priority: u64, pub(crate) token_ids: Vec, /// When this record re-warms the radix after an L3 fill, the fill's /// claim key. The worker releases it only once the radix insert lands, @@ -294,9 +301,9 @@ pub(crate) struct PendingExactStateRecord { /// Only freshly exported request state writes through. Tier fills that /// merely re-warm L1 must not rewrite their existing durable entry. pub(crate) write_through_l3: bool, - /// Durable manifest digest to mirror into L2 on this worker job. `None` + /// Durable manifest to mirror into L2 on this worker job. `None` /// leaves the payload out of L2. - pub(crate) l2_promotion_digest: Option, + pub(crate) l2_promotion_manifest: Option>, /// Measured cold-versus-restore cost for L3 benefit admission. Missing /// telemetry preserves the established LRU write-through behavior. pub(crate) l3_cost: Option, @@ -315,6 +322,9 @@ pub(crate) struct RadixResidentEntry { /// Deterministic first-order estimate of work needed to recreate this /// entry: cached tokens multiplied by stage-local layer count. pub(crate) recompute_cost: u64, + /// Eviction order: entries with a lower value are evicted first. See + /// [`PrefillKvIdentity::retention_priority`]. + pub(crate) retention_priority: u64, } #[derive(Debug, Clone)] @@ -324,6 +334,8 @@ pub(crate) struct RadixExactEntry { pub(crate) extra: ExactStateExtra, /// Whether a later resident hit may promote this entry into durable L3. pub(crate) l3_promotion_eligible: bool, + /// Eviction order; see [`RadixResidentEntry::retention_priority`]. + retention_priority: u64, } impl RadixExactEntry { @@ -338,8 +350,20 @@ impl RadixExactEntry { payload, extra, l3_promotion_eligible, + retention_priority: skippy_inference_api::InferenceRequestTier::Local.priority(), } } + + /// Record the tier priority of the request that produced this state. + pub(crate) fn with_retention_priority(mut self, retention_priority: u64) -> Self { + self.retention_priority = retention_priority; + self + } + + /// Eviction order: lower values are evicted first. + pub(crate) fn retention_priority(&self) -> u64 { + self.retention_priority + } } #[derive(Debug)] @@ -623,16 +647,6 @@ 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] @@ -1395,524 +1409,7 @@ fn local_trust_checksum(page_id: &str, byte_size: u64) -> Checksum { } #[cfg(test)] -mod exact_state_record_queue_tests { - use skippy_cache::ExactStatePayload; - use std::sync::{ - Arc, Mutex, - atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, - mpsc::sync_channel, - }; - - use super::{ - BTreeSet, EXACT_STATE_RECORD_CAPACITY, ExactStateExtra, ExactStateRecordAdmission, - ExactStateRecordWorker, ExactStateWorkerHandles, KvLifecycleEvent, KvLifecycleObserver, - PendingExactStateRecord, enqueue_exact_state_record, run_exact_state_record_job, - }; - use crate::kv_integration::exact_state::{CaptureAdmission, ExactStateAdmissionCredit}; - - /// A fresh, observable budget: the SAME counters back every credit a test - /// creates, so release paths are asserted on real accounting, not on - /// throwaway stubs. - fn budget() -> (Arc, Arc) { - (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))) - } - - fn credit( - total: &Arc, - best_effort: &Arc, - class: CaptureAdmission, - ) -> ExactStateAdmissionCredit { - ExactStateAdmissionCredit::acquire(total, best_effort, class) - .expect("a fresh budget must admit") - } - - struct RecordingObserver(Arc>>); - - impl KvLifecycleObserver for RecordingObserver { - fn observe(&self, event: KvLifecycleEvent) { - self.0.lock().unwrap().push(event); - } - } - - fn pending( - page_id: &str, - admission_credit: ExactStateAdmissionCredit, - ) -> PendingExactStateRecord { - PendingExactStateRecord { - page_id: page_id.to_string(), - payload: ExactStatePayload::full_state(vec![1]), - extra: ExactStateExtra::default(), - namespace: "test".to_string(), - token_ids: vec![1], - l3_fill_claim: None, - write_through_l3: true, - l2_promotion_digest: None, - l3_cost: None, - admission_credit, - } - } - - fn pending_with_bytes(page_id: &str, bytes: usize) -> PendingExactStateRecord { - let (total, best_effort) = budget(); - PendingExactStateRecord { - payload: ExactStatePayload::full_state(vec![1; bytes]), - ..pending( - page_id, - credit(&total, &best_effort, CaptureAdmission::BestEffort), - ) - } - } - - const CAP: u64 = 1024; - - #[test] - fn final_worker_owner_drains_queued_records_before_drop_returns() { - let (sender, receiver) = sync_channel(2); - let completed = Arc::new(AtomicUsize::new(0)); - let worker_completed = completed.clone(); - let task = std::thread::spawn(move || { - while receiver.recv().is_ok() { - worker_completed.fetch_add(1, Ordering::Release); - } - }); - let worker = Arc::new(ExactStateRecordWorker::new(sender, task, None, None)); - let (total, best_effort) = budget(); - worker.with_sender(|sender| { - sender - .unwrap() - .send(pending( - "latest", - credit(&total, &best_effort, CaptureAdmission::BestEffort), - )) - .unwrap() - }); - - drop(worker); - - assert_eq!(completed.load(Ordering::Acquire), 1); - } - - #[test] - fn queue_is_bounded_in_bytes_not_entries() { - let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); - let inflight = Mutex::new(BTreeSet::from(["a".to_string(), "b".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("a", 700), - ), - ExactStateRecordAdmission::Queued - ); - assert_eq!(queue_bytes.load(Ordering::Relaxed), 700); - - // Plenty of entry slots left; the bytes are what is full. - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("b", 700), - ), - ExactStateRecordAdmission::DroppedFull - ); - assert_eq!( - queue_bytes.load(Ordering::Relaxed), - 700, - "a dropped record left bytes claimed" - ); - assert!(!inflight.lock().unwrap().contains("b")); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 1); - } - - #[test] - fn one_oversized_record_is_admitted_into_an_empty_queue() { - let (sender, _receiver) = sync_channel(EXACT_STATE_RECORD_CAPACITY); - let inflight = Mutex::new(BTreeSet::from(["huge".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending_with_bytes("huge", 4096), - ), - ExactStateRecordAdmission::Queued, - "a large model could never record if one export over the cap were refused" - ); - assert_eq!(queue_bytes.load(Ordering::Relaxed), 4096); - assert!(queue_bytes.load(Ordering::Acquire) >= CAP); - } - - #[test] - fn finishing_a_record_releases_its_bytes() { - let inflight = Mutex::new(BTreeSet::from(["done".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(300); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - None, - pending_with_bytes("done", 300), - |_| Ok(()), - ); - - assert_eq!(queue_bytes.load(Ordering::Relaxed), 0); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - } - - #[test] - fn full_queue_drops_optional_record_and_releases_inflight_page() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - // One BestEffort record occupies the channel buffer; its credit stays - // observable in `total`. - sender - .send(pending( - "queued", - credit(&total, &best_effort, CaptureAdmission::BestEffort), - )) - .unwrap(); - let inflight = Mutex::new(BTreeSet::from(["dropped".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "dropped", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::DroppedFull - ); - assert!(!inflight.lock().unwrap().contains("dropped")); - assert_eq!(queued.load(Ordering::Relaxed), 0); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 1, - "the Full rejection must release the dropped record's credit; the buffered one stays" - ); - assert_eq!( - best_effort.load(Ordering::Acquire), - 1, - "the buffered BestEffort credit is still outstanding" - ); - - // Receiver drop: discarding the channel drops the buffered record and - // releases its credit too. - drop(sender); - drop(receiver); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "receiver drop released the buffered credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn disconnected_worker_releases_inflight_page() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - drop(receiver); - let inflight = Mutex::new(BTreeSet::from(["orphaned".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(0); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "orphaned", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::WorkerStopped - ); - assert!(!inflight.lock().unwrap().contains("orphaned")); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the disconnected channel must release the orphaned credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn worker_keeps_page_inflight_until_record_finishes() { - let (total, best_effort) = budget(); - let (sender, receiver) = sync_channel(1); - let inflight = Arc::new(Mutex::new(BTreeSet::from(["page".to_string()]))); - let worker_inflight = inflight.clone(); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = Arc::new(AtomicUsize::new(0)); - let worker_pending_count = pending_count.clone(); - let queue_bytes = AtomicU64::new(0); - let worker_healthy = AtomicBool::new(true); - - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "page", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::Queued - ); - assert!(inflight.lock().unwrap().contains("page")); - assert_eq!( - total.load(Ordering::Acquire), - 1, - "the credit is outstanding while the record sits in the channel" - ); - - let worker = std::thread::spawn(move || { - let pending = receiver.recv().unwrap(); - assert!(worker_inflight.lock().unwrap().contains(&pending.page_id)); - worker_inflight.lock().unwrap().remove(&pending.page_id); - worker_pending_count.fetch_sub(1, Ordering::Relaxed); - // `pending` (and its credit) drops when this closure returns. - }); - worker.join().unwrap(); - - assert!(!inflight.lock().unwrap().contains("page")); - assert_eq!(queued.load(Ordering::Relaxed), 1); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - assert_eq!(pending_count.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the credit released when the record dropped after processing" - ); - } - - #[test] - fn worker_success_notifies_completed_not_mere_admission() { - let inflight = Mutex::new(BTreeSet::from(["written".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let events: Arc>> = Arc::default(); - let observer: Arc = Arc::new(RecordingObserver(events.clone())); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - Some(&observer), - pending( - "written", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| Ok(()), - ); - - assert_eq!( - *events.lock().unwrap(), - vec![KvLifecycleEvent::ExactStateRecordCompleted] - ); - assert_eq!(dropped.load(Ordering::Relaxed), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "successful completion released the real credit" - ); - } - - #[test] - fn worker_write_error_notifies_failed_not_completed() { - let inflight = Mutex::new(BTreeSet::from(["broken".to_string()])); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let events: Arc>> = Arc::default(); - let observer: Arc = Arc::new(RecordingObserver(events.clone())); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - Some(&observer), - pending( - "broken", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| anyhow::bail!("simulated write failure"), - ); - - assert_eq!( - *events.lock().unwrap(), - vec![KvLifecycleEvent::ExactStateRecordFailed] - ); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the worker error path released the real credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - } - - #[test] - fn worker_panic_fails_closed_and_releases_all_record_bookkeeping() { - let (sender, _receiver) = sync_channel(1); - let inflight = Mutex::new(BTreeSet::from(["panicked".to_string()])); - let queued = AtomicU64::new(0); - let dropped = AtomicU64::new(0); - let pending_count = AtomicUsize::new(1); - let queue_bytes = AtomicU64::new(1); - let worker_healthy = AtomicBool::new(true); - let worker_panics = AtomicU64::new(0); - let (total, best_effort) = budget(); - - run_exact_state_record_job( - ExactStateWorkerHandles { - inflight_records: &inflight, - dropped: &dropped, - pending_count: &pending_count, - queue_bytes: &queue_bytes, - worker_healthy: &worker_healthy, - worker_panics: &worker_panics, - }, - None, - pending( - "panicked", - credit(&total, &best_effort, CaptureAdmission::Continuation), - ), - |_| panic!("injected exact-record worker failure"), - ); - - assert!(!worker_healthy.load(Ordering::Acquire)); - assert_eq!(worker_panics.load(Ordering::Relaxed), 1); - assert_eq!(dropped.load(Ordering::Relaxed), 1); - assert_eq!(pending_count.load(Ordering::Acquire), 0); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the unwind dropped the record and released its real credit" - ); - assert_eq!(best_effort.load(Ordering::Acquire), 0); - - inflight.lock().unwrap().insert("later".to_string()); - assert_eq!( - enqueue_exact_state_record( - &sender, - &inflight, - &queued, - &dropped, - &pending_count, - &queue_bytes, - CAP, - &worker_healthy, - pending( - "later", - credit(&total, &best_effort, CaptureAdmission::Continuation) - ), - ), - ExactStateRecordAdmission::WorkerStopped - ); - assert!(inflight.lock().unwrap().is_empty()); - assert_eq!(dropped.load(Ordering::Relaxed), 2); - assert_eq!(pending_count.load(Ordering::Acquire), 0); - assert_eq!( - total.load(Ordering::Acquire), - 0, - "the WorkerStopped follow-up also released its real credit" - ); - } -} +mod exact_state_record_queue_tests; #[cfg(test)] mod telemetry_error_class_tests { diff --git a/crates/skippy-serving/src/kv_integration/records.rs b/crates/skippy-serving/src/kv_integration/records.rs index 4354a05d..fe9114ae 100644 --- a/crates/skippy-serving/src/kv_integration/records.rs +++ b/crates/skippy-serving/src/kv_integration/records.rs @@ -11,6 +11,17 @@ pub struct PrefillKvIdentity { pub token_ids: Vec, } +impl PrefillKvIdentity { + /// Eviction order for entries recorded under this identity: the tier + /// priority of the request class its cache namespace was built for. + pub fn retention_priority(&self) -> u64 { + let namespace = Some(self.identity.chat_template_id.as_str()).filter(|ns| !ns.is_empty()); + skippy_inference_api::InferenceRequestClass::from_cache_namespace(namespace) + .tier() + .priority() + } +} + #[derive(Debug, Clone)] pub struct LookupBatchOutcome { pub pages: Vec, diff --git a/crates/skippy-serving/src/kv_integration/resident_offload.rs b/crates/skippy-serving/src/kv_integration/resident_offload.rs index 85f74f4a..b4f0a943 100644 --- a/crates/skippy-serving/src/kv_integration/resident_offload.rs +++ b/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -1,7 +1,13 @@ -//! Materialize a native prefix only when releasing it to the persistent tier. +//! Capture resident prefixes for optional persistence between scheduler work turns. use super::*; use crate::runtime_state::RuntimeState; -use config::durable_spill::PendingDurableSpill; +use config::durable_spill::{DurableSpillSender, NativeSpillExtension}; +use std::num::NonZeroU64; + +mod kv_chunks; +mod work; + +pub(in crate::kv_integration) use work::NativeCapturePayload; #[derive(Debug)] pub(super) struct NativeOffloadClaim { @@ -43,6 +49,21 @@ impl Drop for NativeOffloadClaim { } impl KvStageIntegration { + pub(super) fn rewarm_resident_prefix( + &self, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + tokens: &[i32], + ) -> Result<()> { + runtime.restore_token_history(session_id, tokens)?; + let mut prefix = identity.clone(); + prefix.token_ids = tokens.to_vec(); + prefix.identity.token_count = tokens.len() as u64; + let _ = self.record_resident_prefix(runtime, session_id, &prefix, tokens); + Ok(()) + } + pub(super) fn native_payload_is_complete( &self, kind: skippy_cache::ExactStatePayloadKind, @@ -79,112 +100,79 @@ impl KvStageIntegration { 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( + pub(crate) fn offer_prefix_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: PrefillKvIdentity, + preferred: bool, + ) { + let cache = Arc::downgrade(self); + let mut capture = None; + runtime.offer_prefix_capture(session_id, preferred, move |runtime, session| { + let Some(cache) = cache.upgrade() else { + return std::ops::ControlFlow::Break(()); + }; + match cache.advance_prefix_capture(runtime, session, &identity, &mut capture) { + Ok(std::ops::ControlFlow::Continue(())) => std::ops::ControlFlow::Continue(()), + Ok(std::ops::ControlFlow::Break(_)) => std::ops::ControlFlow::Break(()), + Err(error) => { + tracing::debug!(%error, "durable prefix capture abandoned"); + std::ops::ControlFlow::Break(()) + } + } + }); + } + + #[cfg(test)] + pub(crate) fn capture_resident_prefix_for_l3( &self, runtime: &mut RuntimeState, - session: &str, - victim: &skippy_cache::RadixEvictionCandidate, + identity: &PrefillKvIdentity, ) -> 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); - }; - if self.l3.is_none() { - 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) + let mut capture = None; + const SESSION: &str = "test-durable-prefix-capture"; + runtime.ensure_session_active(SESSION)?; + let result = loop { + match self.advance_prefix_capture(runtime, SESSION, identity, &mut capture) { + Ok(std::ops::ControlFlow::Continue(())) => {} + Ok(std::ops::ControlFlow::Break(committed)) => break Ok(committed), + Err(error) => break Err(error), + } }; - 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, - )) + runtime.drop_session_timed(SESSION)?; + result + } +} + +fn incremental_capture( + sender: &DurableSpillSender, + identity: &PrefillKvIdentity, + full: &skippy_runtime::RuntimeKvPageDesc, + recurrent_bytes: usize, +) -> Option { + let base = sender.native_base(&identity.namespace, &identity.token_ids)?; + let base_desc = serde_json::from_str(base.kv_desc_json.as_deref()?).ok()?; + let base_geometry = config::kv_page_geometry(&base_desc, base.kv_bytes)?; + let total = full.payload_bytes.checked_add(recurrent_bytes as u64)?; + let geometry = config::kv_page_geometry(full, total)?; + if base_geometry.blocks != geometry.blocks + || base_geometry.window_rows != geometry.window_rows + || base_geometry.rows != base.token_count + || full.token_start != 0 + { + return None; } + let reused_rows = + NonZeroU64::new(base.token_count / geometry.window_rows * geometry.window_rows)?; + Some(NativeSpillExtension { + base, + reused_rows, + geometry, + }) } #[cfg(test)] diff --git a/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs b/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs new file mode 100644 index 00000000..237c3b02 --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/resident_offload/kv_chunks.rs @@ -0,0 +1,374 @@ +//! Collect independently exported token ranges in native K, V and index order. +//! +//! A native range contains complete runs for its own token window. Joining +//! whole window buffers would put V before K for later windows, so assemble the +//! runs on the spill worker, after releasing the serving runtime. + +use std::num::NonZeroU64; +use std::ops::Range; + +use anyhow::{Context, Result, ensure}; +use skippy_runtime::{ + KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentRole, RuntimeKvPage, RuntimeKvPageDesc, +}; + +use crate::runtime_state::RuntimeState; + +#[derive(Debug)] +pub(super) struct AttentionCapture { + page: RuntimeKvPageDesc, + parts: Vec<(Option, KvCaptureChunks)>, +} + +impl AttentionCapture { + pub(super) fn new(page: RuntimeKvPageDesc, step_bytes: u64) -> Result> { + page.validate_payload(usize::try_from(page.payload_bytes)?)?; + let parts = if page.has_sliding_window_component() { + [KvPageComponentRole::Base, KvPageComponentRole::Swa] + .into_iter() + .map(|role| { + let component = page.component_page(role)?; + Some((Some(role), KvCaptureChunks::try_new(component, step_bytes)?)) + }) + .collect::>>() + } else { + KvCaptureChunks::try_new(page.clone(), step_bytes).map(|part| vec![(None, part)]) + }; + Ok(parts.map(|parts| Self { page, parts })) + } + + pub(super) fn step( + &mut self, + runtime: &mut RuntimeState, + session: &str, + sequence: i32, + ) -> Result { + for (role, part) in &mut self.parts { + if let Some(range) = part.next_range() { + let bytes = part.range_bytes(&range)?; + part.append( + runtime.export_resident_kv_page(session, sequence, range, bytes, *role)?, + )?; + return Ok(true); + } + } + Ok(false) + } + + pub(super) fn byte_len(&self) -> u64 { + self.page.payload_bytes + } + + pub(super) fn assemble(self) -> Result> { + let mut parts = self.parts.into_iter(); + let (_, first) = parts + .next() + .context("native attention capture has no parts")?; + let mut payload = first.assemble()?; + let total = usize::try_from(self.page.payload_bytes)?; + payload.reserve_exact( + total + .checked_sub(payload.len()) + .context("native capture exceeds the page")?, + ); + for (_, part) in parts { + payload.extend(part.assemble()?); + } + self.page.validate_payload(payload.len())?; + Ok(payload) + } +} + +#[derive(Debug)] +struct KvCaptureChunks { + full: RuntimeKvPageDesc, + tokens_per_step: NonZeroU64, + bytes_per_token: u64, + next_token: u64, + end_token: u64, + runs: [(u64, u64); 3], + chunks: Vec>, +} + +impl KvCaptureChunks { + pub(super) fn try_new(full: RuntimeKvPageDesc, step_bytes: u64) -> Option { + if full.component_count != 0 + || full.token_count == 0 + || full.layer_count == 0 + || full.k_row_bytes == 0 + || !full.payload_bytes.is_multiple_of(full.token_count) + { + return None; + } + let layers = u64::from(full.layer_count); + let bytes_per_token = full.payload_bytes / full.token_count; + let tokens_per_step = NonZeroU64::new(step_bytes.checked_div(bytes_per_token)?)?; + let key = u64::from(full.k_row_bytes); + let index = u64::from(full.k_idx_row_bytes); + let other_bytes = layers.checked_mul(key.checked_add(index)?)?; + let value_bytes = bytes_per_token.checked_sub(other_bytes)?; + let (values, stride) = if full.flags & KV_PAGE_FLAG_V_TRANSPOSED == 0 { + let stride = u64::from(full.v_row_bytes); + if value_bytes != layers.checked_mul(stride)? { + return None; + } + (layers, stride) + } else { + let stride = NonZeroU64::new(u64::from(full.v_element_bytes))?.get(); + if !value_bytes.is_multiple_of(stride) { + return None; + } + (value_bytes / stride, stride) + }; + + Some(Self { + tokens_per_step, + bytes_per_token, + next_token: full.token_start, + end_token: full.token_start.checked_add(full.token_count)?, + full, + runs: [(layers, key), (values, stride), (layers, index)], + chunks: Vec::new(), + }) + } + + pub(super) fn next_range(&self) -> Option> { + (self.next_token < self.end_token).then(|| { + self.next_token + ..self + .next_token + .saturating_add(self.tokens_per_step.get()) + .min(self.end_token) + }) + } + + pub(super) fn range_bytes(&self, range: &Range) -> Result { + usize::try_from((range.end - range.start) * self.bytes_per_token) + .context("KV capture slice length exceeds usize") + } + + pub(super) fn append(&mut self, page: RuntimeKvPage) -> Result<()> { + let range = self + .next_range() + .context("KV capture is already complete")?; + let expected = self.range_bytes(&range)?; + let RuntimeKvPage { mut desc, payload } = page; + ensure!( + desc.token_start == range.start + && desc.token_count == range.end - range.start + && desc.payload_bytes == expected as u64 + && payload.len() == expected, + "native export does not match the capture slice" + ); + desc.token_start = self.full.token_start; + desc.token_count = self.full.token_count; + desc.payload_bytes = self.full.payload_bytes; + ensure!(desc == self.full, "native KV layout changed during capture"); + self.chunks.push(payload); + self.next_token = range.end; + Ok(()) + } + + fn assemble(self) -> Result> { + ensure!(self.next_range().is_none(), "KV capture is incomplete"); + if self.chunks.len() == 1 { + return Ok(self.chunks.into_iter().next().unwrap_or_default()); + } + + // One iterator per window. Interleave one run of each iterator at a + // time to reconstruct the original full-length native runs. + let mut windows: Vec<_> = self + .chunks + .iter() + .map(|bytes| { + let count = u64::try_from(bytes.len())? / self.bytes_per_token; + Ok((usize::try_from(count)?, bytes.as_slice())) + }) + .collect::>()?; + let mut payload = Vec::with_capacity(usize::try_from(self.full.payload_bytes)?); + for (count, stride) in self.runs { + let stride = usize::try_from(stride)?; + if stride == 0 { + continue; + } + for _ in 0..count { + for (tokens, remaining) in &mut windows { + let (run, suffix) = remaining + .split_at_checked(*tokens * stride) + .context("native KV capture window is truncated")?; + payload.extend_from_slice(run); + *remaining = suffix; + } + } + } + ensure!( + windows.iter().all(|(_, remaining)| remaining.is_empty()), + "native KV capture has trailing bytes" + ); + self.full.validate_payload(payload.len())?; + Ok(payload) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_runtime::KV_PAGE_FLAG_HAS_K_IDX; + + #[test] + fn composite_capture_preserves_base_and_sliding_window_byte_order() { + let mut page = RuntimeKvPageDesc { + version: 2, + codec: 2, + layer_start: 0, + layer_end: 1, + layer_count: 0, + token_start: 0, + token_count: 4, + k_type: 0, + v_type: 0, + k_row_bytes: 0, + v_row_bytes: 0, + v_element_bytes: 0, + k_idx_row_bytes: 0, + payload_bytes: 6, + flags: 0, + component_count: 2, + components: Box::default(), + }; + let [base, swa] = page.components.as_mut(); + base.version = 1; + base.role = KvPageComponentRole::Base as u32; + base.token_count = 4; + base.layer_count = 1; + base.k_row_bytes = 1; + base.payload_bytes = 4; + *swa = *base; + swa.role = KvPageComponentRole::Swa as u32; + swa.token_start = 2; + swa.token_count = 2; + swa.payload_offset = 4; + swa.payload_bytes = 2; + let mut capture = AttentionCapture::new(page, 2).unwrap().unwrap(); + for (role, part) in &mut capture.parts { + while let Some(range) = part.next_range() { + let mut desc = part.full.clone(); + desc.token_start = range.start; + desc.token_count = range.end - range.start; + desc.payload_bytes = desc.token_count; + let base = u8::from(*role == Some(KvPageComponentRole::Swa)) * 16; + let payload = range + .map(|token| base + u8::try_from(token).unwrap()) + .collect(); + part.append(RuntimeKvPage { desc, payload }).unwrap(); + } + } + assert_eq!(capture.assemble().unwrap(), [0, 1, 2, 3, 18, 19]); + } + + fn descriptor(transposed: bool) -> RuntimeKvPageDesc { + RuntimeKvPageDesc { + version: 1, + codec: 1, + layer_start: 0, + layer_end: 1, + layer_count: 1, + token_start: 64, + token_count: 3, + k_type: 1, + v_type: 1, + k_row_bytes: 2, + v_row_bytes: if transposed { 0 } else { 3 }, + v_element_bytes: u32::from(transposed), + k_idx_row_bytes: 1, + payload_bytes: 18, + flags: KV_PAGE_FLAG_HAS_K_IDX + | if transposed { + KV_PAGE_FLAG_V_TRANSPOSED + } else { + 0 + }, + component_count: 0, + components: Default::default(), + } + } + + #[test] + fn token_windows_reassemble_in_native_order() { + let first_key = [10, 11, 12, 13]; + let last_key = [14, 15]; + let first_index = [30, 31]; + let last_index = [32]; + for (transposed, first_value, last_value, full_value) in [ + ( + false, + [20, 21, 22, 23, 24, 25], + [26, 27, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28], + ), + ( + true, + [20, 21, 23, 24, 26, 27], + [22, 25, 28], + [20, 21, 22, 23, 24, 25, 26, 27, 28], + ), + ] { + let desc = descriptor(transposed); + let mut chunks = KvCaptureChunks::try_new(desc.clone(), 12).unwrap(); + assert_eq!(chunks.next_range(), Some(64..66)); + chunks + .append(RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_count: 2, + payload_bytes: 12, + ..desc.clone() + }, + payload: [&first_key[..], &first_value, &first_index].concat(), + }) + .unwrap(); + assert_eq!(chunks.next_range(), Some(66..67)); + chunks + .append(RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_start: 66, + token_count: 1, + payload_bytes: 6, + ..desc + }, + payload: [&last_key[..], &last_value, &last_index].concat(), + }) + .unwrap(); + assert_eq!( + chunks.assemble().unwrap(), + [ + &first_key[..], + &last_key, + &full_value, + &first_index, + &last_index + ] + .concat() + ); + } + } + + #[test] + fn token_windows_reject_a_wrong_layout_and_unfinished_capture() { + let desc = descriptor(false); + let mut chunks = KvCaptureChunks::try_new(desc.clone(), 12).unwrap(); + let bad = RuntimeKvPage { + desc: RuntimeKvPageDesc { + token_count: 2, + payload_bytes: 12, + // A raw KV page with a different value type cannot be mixed + // with the descriptor used to size the complete checkpoint. + v_type: desc.v_type + 1, + ..desc + }, + payload: vec![0; 12], + }; + assert!(chunks.append(bad).is_err()); + assert_eq!(chunks.next_range(), Some(64..66)); + assert!(chunks.assemble().is_err()); + } +} diff --git a/crates/skippy-serving/src/kv_integration/resident_offload/work.rs b/crates/skippy-serving/src/kv_integration/resident_offload/work.rs new file mode 100644 index 00000000..9b6376fc --- /dev/null +++ b/crates/skippy-serving/src/kv_integration/resident_offload/work.rs @@ -0,0 +1,246 @@ +//! A durable capture owns the host bytes it has copied. A resident entry can +//! leave L1 between steps. Its eviction cancels the unfinished copy and never +//! runs or waits for the exporter. + +use std::ops::ControlFlow; + +use anyhow::{Context, ensure}; + +use super::kv_chunks::AttentionCapture; +use super::*; +use crate::kv_integration::config::durable_spill::{ + DurableSpillPayload, DurableSpillReservation, PendingDurableSpill, +}; + +const CAPTURE_STEP_BYTES: usize = 8 * 1024 * 1024; +const MAX_CAPTURE_BYTES: u64 = 1024 * 1024 * 1024; + +pub(super) struct NativePrefixCapture { + entry: RadixResidentEntry, + full_desc: Option, + payload: NativeCapturePayload, + extension: Option, + reservation: DurableSpillReservation, + claim: NativeOffloadClaim, +} + +#[derive(Debug)] +pub(in crate::kv_integration) struct NativeCapturePayload { + attention: Option, + recurrent_bytes: usize, + recurrent_copied: usize, + recurrent_chunks: Vec>, +} + +impl NativeCapturePayload { + fn step(&mut self, runtime: &mut RuntimeState, session: &str, sequence: i32) -> Result { + if let Some(attention) = self.attention.as_mut() + && attention.step(runtime, session, sequence)? + { + return Ok(true); + } + if self.recurrent_copied == self.recurrent_bytes { + return Ok(false); + } + let bytes = (self.recurrent_bytes - self.recurrent_copied).min(CAPTURE_STEP_BYTES); + let mut chunk = vec![0; bytes]; + runtime.copy_resident_recurrent_range( + session, + sequence, + self.recurrent_copied, + &mut chunk, + )?; + self.recurrent_copied += bytes; + self.recurrent_chunks.push(chunk); + Ok(true) + } + + pub(in crate::kv_integration) fn byte_len(&self) -> u64 { + self.attention + .as_ref() + .map_or(0, AttentionCapture::byte_len) + + self.recurrent_bytes as u64 + } + + pub(in crate::kv_integration) fn assemble(mut self) -> Result { + ensure!( + self.recurrent_copied == self.recurrent_bytes, + "resident recurrent copy is incomplete" + ); + let recurrent = if self.recurrent_chunks.len() == 1 { + self.recurrent_chunks.pop().unwrap_or_default() + } else { + let mut recurrent = Vec::with_capacity(self.recurrent_bytes); + for chunk in self.recurrent_chunks { + recurrent.extend(chunk); + } + recurrent + }; + match self.attention { + Some(attention) => Ok(ExactStatePayload::kv_recurrent( + attention.assemble()?, + recurrent, + )), + None => Ok(ExactStatePayload::recurrent_only(recurrent)), + } + } +} + +impl KvStageIntegration { + pub(super) fn advance_prefix_capture( + &self, + runtime: &mut RuntimeState, + session: &str, + identity: &PrefillKvIdentity, + state: &mut Option, + ) -> Result> { + let entry = self + .radix + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .resident_exact(&identity.namespace, &identity.token_ids) + .map(|entry| entry.value); + let Some(entry) = entry else { + return Ok(ControlFlow::Break(false)); + }; + let Some(capture) = state.as_mut() else { + *state = self.prepare_prefix_capture(runtime, session, identity, entry)?; + return Ok(if state.is_some() { + ControlFlow::Continue(()) + } else { + ControlFlow::Break(false) + }); + }; + if capture.entry.seq_id != entry.seq_id || capture.entry.page_id != entry.page_id { + return Ok(ControlFlow::Break(false)); + } + if capture.payload.step(runtime, session, entry.seq_id)? { + return Ok(ControlFlow::Continue(())); + } + + let capture = state.take().context("missing durable prefix capture")?; + // A paused capture must not keep the spill channel open. The cache + // can lose its last owner on this scheduler thread, and its drop + // joins the spill worker before the paused captures are dropped. + let sender = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(sender) = sender.as_ref() else { + return Ok(ControlFlow::Break(false)); + }; + Ok(ControlFlow::Break(sender.send_reserved( + PendingDurableSpill { + page_id: entry.page_id, + payload: DurableSpillPayload::Native(capture.payload), + extra: ExactStateExtra { + kv_desc: capture.full_desc, + }, + namespace: identity.namespace.clone(), + token_ids: identity.token_ids.to_vec(), + l3_cost: None, + native_raw: true, + extension: capture.extension, + }, + capture.reservation, + capture.claim, + ))) + } + + fn prepare_prefix_capture( + &self, + runtime: &mut RuntimeState, + session: &str, + identity: &PrefillKvIdentity, + entry: RadixResidentEntry, + ) -> Result> { + let sender = self + .exact_state_record_worker + .durable_sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let (Some(sender), Some(capabilities)) = (sender, self.loaded_memory_cache) else { + return Ok(None); + }; + if self.l3.is_none() + || sender.has_native_checkpoint(&identity.namespace, &identity.token_ids) + { + return Ok(None); + } + let Some(claim) = NativeOffloadClaim::acquire( + &self.inflight_records, + &identity.namespace, + &identity.token_ids, + ) else { + return Ok(None); + }; + let sequence = entry.seq_id; + let tokens = entry.token_count; + let full_desc = capabilities + .resident_attention + .then(|| runtime.resident_kv_page_desc(session, sequence, 0..tokens)) + .transpose()?; + let recurrent_bytes = if capabilities.resident_checkpoint { + runtime.resident_recurrent_state_bytes(session, sequence)? + } else { + 0 + }; + let incremental = full_desc + .as_ref() + .and_then(|full| incremental_capture(&sender, identity, full, recurrent_bytes)) + .and_then(|extension| { + let start = extension.reused_rows.get(); + let tail = runtime + .resident_kv_page_desc(session, sequence, start..tokens) + .ok()?; + let geometry = config::kv_page_geometry(&tail, tail.payload_bytes)?; + (tail.token_start == start + && tail.token_count == tokens - start + && geometry.blocks == extension.geometry.blocks + && geometry.window_rows == extension.geometry.window_rows) + .then_some((extension, tail)) + }); + let (extension, capture_desc) = match incremental { + Some((extension, tail)) => (Some(extension), Some(tail)), + None => (None, full_desc.clone()), + }; + let kv_bytes = capture_desc.as_ref().map_or(0, |desc| desc.payload_bytes); + let bytes = kv_bytes + .checked_add(recurrent_bytes as u64) + .context("native offload size overflow")?; + if bytes == 0 || bytes > MAX_CAPTURE_BYTES { + return Ok(None); + } + let attention = match capture_desc { + Some(desc) => { + let Some(attention) = AttentionCapture::new(desc, CAPTURE_STEP_BYTES as u64)? + else { + return Ok(None); + }; + Some(attention) + } + None => None, + }; + // Reserve room for simultaneous source slices and their assembled + // payload. The serving scheduler never allocates the assembled copy. + let reserved = 2 * bytes; + let Some(reservation) = sender.try_reserve(reserved) else { + return Ok(None); + }; + Ok(Some(NativePrefixCapture { + entry, + full_desc, + payload: NativeCapturePayload { + attention, + recurrent_bytes, + recurrent_copied: 0, + recurrent_chunks: Vec::new(), + }, + extension, + reservation, + claim, + })) + } +} diff --git a/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs b/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs index 0154403d..02737402 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefill_tests.rs @@ -16,6 +16,7 @@ fn config(capacity: u32) -> StageConfig { max_entries: 32, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, min_tokens: 1, shared_prefix_stride_tokens: 32, shared_prefix_record_limit: 32, @@ -58,6 +59,7 @@ fn prefill_keeps_a_healthy_resident_cache() -> Result<()> { seq_id, token_count: 64, recompute_cost: 64, + retention_priority: skippy_inference_api::InferenceRequestTier::Local.priority(), }, )?; let mut runtime = diff --git a/crates/skippy-serving/src/kv_integration/resident_prefix.rs b/crates/skippy-serving/src/kv_integration/resident_prefix.rs index 8fda6e68..5a32d673 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefix.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefix.rs @@ -262,6 +262,7 @@ impl KvStageIntegration { units: resident_candidate_units(candidate), recompute_cost: candidate.value.recompute_cost, last_used: candidate.last_used, + retention_priority: candidate.value.retention_priority, }) .collect::>(); rank_eviction_candidates(&mut ranked); @@ -486,9 +487,11 @@ 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, |victim| { - self.release_native_prefix(runtime, session_id, victim) - })? + // Live requests need the KV now, whichever tier stored it. + let Some(removed) = + evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { + self.release_native_prefix(runtime, session_id, victim) + })? else { break; }; @@ -578,12 +581,16 @@ impl KvStageIntegration { } } +/// Evict the best resident victim whose retention is at most +/// `max_victim_retention`, so a record never displaces a higher tier's entry. fn evict_one_resident( radix: &mut skippy_cache::UnifiedRadixCache, sequences: &mut ResidentSequencePool, + max_victim_retention: u64, mut drop_native: impl FnMut(&skippy_cache::RadixEvictionCandidate) -> Result<()>, ) -> Result>> { - let candidates = radix.resident_eviction_candidates(); + let mut candidates = radix.resident_eviction_candidates(); + candidates.retain(|candidate| candidate.value.retention_priority <= max_victim_retention); if candidates.is_empty() { return Ok(None); } @@ -603,6 +610,7 @@ fn evict_one_resident( units: resident_candidate_units(candidate), recompute_cost: candidate.value.recompute_cost, last_used: candidate.last_used, + retention_priority: candidate.value.retention_priority, }) .collect(), }, @@ -724,6 +732,7 @@ mod proactive_eviction_tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -765,6 +774,7 @@ mod proactive_eviction_tests { seq_id, token_count: 8, recompute_cost: 8, + retention_priority: 0, }, ) .unwrap(); @@ -800,6 +810,7 @@ mod proactive_eviction_tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, @@ -841,6 +852,7 @@ mod proactive_eviction_tests { seq_id, token_count: tokens, recompute_cost: tokens, + retention_priority: 0, }, ) .unwrap(); @@ -886,11 +898,12 @@ mod proactive_eviction_tests { seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); - let error = evict_one_resident(&mut radix, &mut sequences, |_| { + let error = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |_| { anyhow::bail!("native drop failed") }) .unwrap_err(); @@ -915,13 +928,14 @@ mod proactive_eviction_tests { seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); radix.acquire_resident("stage", &[1, 2, 3]).unwrap(); let mut dropped = false; - let removed = evict_one_resident(&mut radix, &mut sequences, |_| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |_| { dropped = true; Ok(()) }) @@ -947,12 +961,13 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, ) .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) @@ -981,6 +996,7 @@ mod proactive_eviction_tests { seq_id: 1, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); @@ -1021,6 +1037,7 @@ mod proactive_eviction_tests { seq_id: expensive_seq_id, token_count: 3, recompute_cost: 300, + retention_priority: 0, }, ) .unwrap(); @@ -1035,12 +1052,13 @@ mod proactive_eviction_tests { seq_id: cheap_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); let mut dropped = None; - let removed = evict_one_resident(&mut radix, &mut sequences, |victim| { + let removed = evict_one_resident(&mut radix, &mut sequences, u64::MAX, |victim| { let seq_id = victim.value.seq_id; dropped = Some(seq_id); Ok(()) @@ -1071,6 +1089,7 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, |seq_id| { dropped = Some(seq_id); @@ -1105,6 +1124,7 @@ mod proactive_eviction_tests { seq_id, token_count: 0, recompute_cost: 0, + retention_priority: 0, }, |_| anyhow::bail!("native drop failed"), ) @@ -1147,6 +1167,7 @@ mod proactive_eviction_tests { seq_id: existing_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, ) .unwrap(); @@ -1164,6 +1185,7 @@ mod proactive_eviction_tests { seq_id: duplicate_seq_id, token_count: 3, recompute_cost: 3, + retention_priority: 0, }, |seq_id| { dropped = Some(seq_id); diff --git a/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs b/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs index 93a95db6..85809a7c 100644 --- a/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs +++ b/crates/skippy-serving/src/kv_integration/resident_prefix/recording.rs @@ -12,6 +12,37 @@ impl KvStageIntegration { .map(ResidentRecordOutcome::into_record) } + pub(crate) fn record_resident_prefix_for_idle_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + ) -> Result> { + self.record_resident_prefix_with_capture(runtime, session_id, identity, token_ids, false) + } + + pub(crate) fn record_resident_prefix_with_capture( + self: &Arc, + runtime: &mut RuntimeState, + session_id: &str, + identity: &PrefillKvIdentity, + token_ids: &[i32], + prefer_full_prompt: bool, + ) -> Result> { + let record = self.record_resident_prefix(runtime, session_id, identity, token_ids)?; + if let Some(record) = &record + && self.l3.is_some() + { + let mut identity = identity.clone(); + identity.token_ids.truncate(record.token_count); + identity.identity.token_count = record.token_count as u64; + let preferred = prefer_full_prompt && record.token_count == token_ids.len(); + self.offer_prefix_capture(runtime, session_id, identity, preferred); + } + Ok(record) + } + /// Record a resident prefix, saying why when none is kept. pub fn record_resident_prefix_outcome( &self, @@ -56,11 +87,13 @@ impl KvStageIntegration { }, )); } + let retention = identity.retention_priority(); if !make_record_room( self.resident_config, &mut radix, &mut sequences, checkpoint_bytes, + retention, &mut evicted, |victim| self.release_native_prefix(runtime, session_id, victim), )? { @@ -87,10 +120,21 @@ impl KvStageIntegration { 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 removed = + evict_one_resident(&mut radix, &mut sequences, retention, |victim| { + self.release_native_prefix(runtime, session_id, victim) + })?; let Some(removed) = removed else { + // The evictable sequences hold higher tiers' prefixes: keep them. + if radix + .resident_eviction_candidates() + .iter() + .any(|candidate| candidate.value.retention_priority > retention) + { + return Ok(ResidentRecordOutcome::Skipped(ResidentRecordSkip::NoRoom { + bytes: checkpoint_bytes, + })); + } return Err(error); }; evicted.0 += 1; @@ -112,6 +156,7 @@ impl KvStageIntegration { seq_id, token_count: token_count as u64, recompute_cost: (token_count as u64).saturating_mul(u64::from(layers)), + retention_priority: identity.retention_priority(), }; let candidate = skippy_cache::RadixEvictionCandidate { namespace: identity.namespace.clone(), @@ -138,6 +183,7 @@ impl KvStageIntegration { &mut radix, &mut sequences, bytes, + retention, &mut evicted, |victim| self.release_native_prefix(runtime, session_id, victim), ) @@ -257,11 +303,14 @@ fn make_record_room( radix: &mut skippy_cache::UnifiedRadixCache, sequences: &mut ResidentSequencePool, bytes: u64, + incoming_retention: 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 { + let Some(removed) = + evict_one_resident(radix, sequences, incoming_retention, &mut drop_native)? + else { return Ok(false); }; evicted.0 = evicted.0.saturating_add(1); @@ -348,6 +397,7 @@ mod resident_record_cap_tests { seq_id, token_count: 100, recompute_cost: 100, + retention_priority: 0, }, ) .unwrap(); @@ -363,6 +413,97 @@ mod resident_record_cap_tests { mod checkpoint_budget_tests { use super::*; + /// A cache holding one resident entry per `(tokens, retention)` pair. + fn tiered_cache( + entries: &[(&[i32], u64)], + ) -> ( + skippy_cache::UnifiedRadixCache, + ResidentSequencePool, + ) { + let mut radix = skippy_cache::UnifiedRadixCache::new(); + let mut sequences = ResidentSequencePool::new(4); + for (tokens, retention) in entries { + let seq = sequences.allocate().unwrap(); + radix + .insert_resident( + "model", + tokens, + 10, + RadixResidentEntry { + page_id: seq.to_string(), + seq_id: seq, + token_count: tokens.len() as u64, + recompute_cost: 1, + retention_priority: *retention, + }, + ) + .unwrap(); + } + (radix, sequences) + } + + #[test] + fn a_record_evicts_only_entries_at_or_below_its_tier() { + let config = skippy_cache::ResidentCacheConfig { + max_entries: 2, + max_bytes: 0, + min_tokens: 1, + reserved_seq_count: 4, + max_resident_tokens: 0, + }; + let (mut radix, mut sequences) = tiered_cache(&[(&[1], 2), (&[2], 2)]); + assert!( + !make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 0, + &mut (0, 0), + |_| { panic!("a lower tier's record must not evict a higher tier's prefix") } + ) + .unwrap() + ); + assert_eq!(radix.stats().resident_entries, 2); + + let mut dropped = Vec::new(); + assert!( + make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 2, + &mut (0, 0), + |victim| { + dropped.push(victim.value.retention_priority); + Ok(()) + } + ) + .unwrap() + ); + assert_eq!(dropped, [2]); + + let (mut radix, mut sequences) = tiered_cache(&[(&[1], 2), (&[2], 0)]); + let mut dropped = Vec::new(); + assert!( + make_record_room( + config, + &mut radix, + &mut sequences, + 0, + 0, + &mut (0, 0), + |victim| { + dropped.push(victim.tokens.clone()); + Ok(()) + } + ) + .unwrap() + ); + assert_eq!(dropped, [vec![2]]); + } + #[test] fn native_host_bytes_evict_unpinned_owner_without_summing_shared_kv() { let mut radix = skippy_cache::UnifiedRadixCache::new(); @@ -380,6 +521,7 @@ mod checkpoint_budget_tests { seq_id: seq, token_count: tokens.len() as u64, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); @@ -400,6 +542,7 @@ mod checkpoint_budget_tests { &mut radix, &mut sequences, 30, + 0, &mut evicted, |seq| { dropped.push(seq.value.seq_id); @@ -429,6 +572,7 @@ mod checkpoint_budget_tests { seq_id: seq, token_count: 2, recompute_cost: 1, + retention_priority: 0, }, ) .unwrap(); @@ -448,6 +592,7 @@ mod checkpoint_budget_tests { &mut radix, &mut sequences, 30, + 0, &mut (0, 0), |_| panic!("pinned checkpoint must not be dropped") ) diff --git a/crates/skippy-serving/src/kv_integration/scheduling.rs b/crates/skippy-serving/src/kv_integration/scheduling.rs index 86888a37..b219087e 100644 --- a/crates/skippy-serving/src/kv_integration/scheduling.rs +++ b/crates/skippy-serving/src/kv_integration/scheduling.rs @@ -73,6 +73,7 @@ mod tests { max_entries: 8, max_bytes: 0, l2_max_bytes: 1024, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: Default::default(), shared_prefix_stride_tokens: 1, @@ -82,7 +83,7 @@ mod tests { }), ..StageConfig::default() }; - KvStageIntegration::from_test_model_with_l3_manager( + KvStageIntegration::from_loaded_model_with_l3_manager( &config, Some(ModelStateKind::Dense), Some(MemoryCacheCapabilities { diff --git a/crates/skippy-serving/src/kv_integration/snapshot_validation.rs b/crates/skippy-serving/src/kv_integration/snapshot_validation.rs index 202d9169..93f4427e 100644 --- a/crates/skippy-serving/src/kv_integration/snapshot_validation.rs +++ b/crates/skippy-serving/src/kv_integration/snapshot_validation.rs @@ -63,6 +63,7 @@ mod tests { max_entries: 4, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, exact_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, diff --git a/crates/skippy-serving/src/kv_integration/tier_metrics.rs b/crates/skippy-serving/src/kv_integration/tier_metrics.rs index 3251ab02..89a16891 100644 --- a/crates/skippy-serving/src/kv_integration/tier_metrics.rs +++ b/crates/skippy-serving/src/kv_integration/tier_metrics.rs @@ -264,6 +264,7 @@ mod tests { seq_id: 0, token_count: 3, recompute_cost: 1, + retention_priority: 0, }, ) .expect("resident checkpoint"); diff --git a/crates/skippy-serving/src/lib.rs b/crates/skippy-serving/src/lib.rs index 4caaac2a..b4dde931 100644 --- a/crates/skippy-serving/src/lib.rs +++ b/crates/skippy-serving/src/lib.rs @@ -41,6 +41,7 @@ mod legacy_scheduler_absence_tests { pub mod serving_hooks; pub mod settings; pub mod split_dflash; +mod stage_request_class; pub mod telemetry; pub mod thinking_probe; pub mod tokenizer; diff --git a/crates/skippy-serving/src/runtime_state.rs b/crates/skippy-serving/src/runtime_state.rs index d4244e1e..6ff12a79 100644 --- a/crates/skippy-serving/src/runtime_state.rs +++ b/crates/skippy-serving/src/runtime_state.rs @@ -18,18 +18,20 @@ use skippy_runtime::{ }; mod context_capacity; +pub(crate) mod draft_batch; 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; pub mod panic_recovery; mod resident_prefix; mod restore_transaction; mod session_end_exports; mod state_transfer; +mod verification_batch; +pub(crate) use verification_batch::RuntimeVerificationRequest; #[cfg(test)] use context_capacity::lane_count_for_workload; @@ -51,7 +53,6 @@ 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, @@ -97,6 +98,8 @@ pub struct RuntimeState { /// Set while parked sessions' exports run, so their own runtime calls do /// not start completing the rest. completing_parked_session_ends: bool, + prefix_capture: Option, + next_prefix_capture: Option, #[cfg(test)] modelless_for_test: bool, /// Lets modelless tests exercise a split DFlash final stage. @@ -281,7 +284,6 @@ impl RuntimeState { 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, @@ -298,6 +300,8 @@ impl RuntimeState { session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + prefix_capture: None, + next_prefix_capture: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer: None, compute_meter: Arc::default(), @@ -405,44 +409,24 @@ pub fn load_runtime_with_overrides( .iter() .map(std::path::PathBuf::from) .collect::>(); - 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); + 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(runtime_from_verified_model( + Ok(Some(runtime_from_loaded_model( config, model, session_lifecycle_observer, - content, )?)) } -fn runtime_from_verified_model( - config: &StageConfig, - model: StageModel, - observer: 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) -} - /// Apply workload admission and retain the host's session-lifecycle observer. fn runtime_from_loaded_model( config: &StageConfig, @@ -459,7 +443,6 @@ fn runtime_from_loaded_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, @@ -476,6 +459,8 @@ fn runtime_from_loaded_model( session_end_kv_exports: BTreeMap::new(), parked_session_ends: Vec::new(), completing_parked_session_ends: false, + prefix_capture: None, + next_prefix_capture: None, session_resident_prefixes: BTreeMap::new(), session_lifecycle_observer, compute_meter: Arc::default(), @@ -501,30 +486,23 @@ pub fn load_runtime_with_overrides_and_open_events( .iter() .map(std::path::PathBuf::from) .collect::>(); - 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); + 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(runtime_from_verified_model( + Ok(Some(runtime_from_loaded_model( config, model, session_lifecycle_observer, - content, )?)) } diff --git a/crates/skippy-serving/src/runtime_state/context_capacity.rs b/crates/skippy-serving/src/runtime_state/context_capacity.rs index d050cfab..aa38e856 100644 --- a/crates/skippy-serving/src/runtime_state/context_capacity.rs +++ b/crates/skippy-serving/src/runtime_state/context_capacity.rs @@ -124,6 +124,7 @@ mod tests { max_entries: 64, max_bytes: 0, l2_max_bytes: 0, + l1_checkpoint_max_bytes: None, codec: skippy_protocol::StageKvCacheCodec::Native, min_tokens: 1, shared_prefix_stride_tokens: 1, diff --git a/crates/skippy-serving/src/runtime_state/draft_batch.rs b/crates/skippy-serving/src/runtime_state/draft_batch.rs new file mode 100644 index 00000000..bfb032d1 --- /dev/null +++ b/crates/skippy-serving/src/runtime_state/draft_batch.rs @@ -0,0 +1,74 @@ +//! Independent lanes sharing one advisory draft-model forward. +use super::*; +use skippy_runtime::dflash::proposal_batch::DFlashBatchRequest; + +pub(crate) struct RuntimeDraftRequest { + pub(crate) session_id: String, + pub(crate) anchor: i32, + pub(crate) max_tokens: usize, + pub(crate) base_position: u64, +} + +pub(crate) struct RuntimeDraftBatch { + pub(crate) proposals: Vec>, + pub(crate) shared_lanes: usize, +} + +impl RuntimeState { + pub(crate) fn dflash_propose_batch( + &mut self, + requests: &[&RuntimeDraftRequest], + ) -> Result { + self.complete_parked_session_ends(); + let indexes: BTreeMap<_, _> = requests + .iter() + .enumerate() + .map(|(index, request)| (request.session_id.as_str(), index)) + .collect(); + anyhow::ensure!(indexes.len() == requests.len(), "duplicate draft session"); + let mut order = Vec::new(); + let mut before = Vec::new(); + let mut native: Vec<_> = self + .sessions + .iter_mut() + .filter_map(|(id, lane)| { + let &index = indexes.get(id.as_str())?; + let request = requests[index]; + order.push(index); + before.push( + lane.session + .dflash_draft_stats() + .map_or(0, |stats| stats.shared_proposals), + ); + Some(DFlashBatchRequest { + session: &mut lane.session, + anchor: request.anchor, + max_tokens: request.max_tokens, + }) + }) + .collect(); + anyhow::ensure!( + native.len() == requests.len(), + "draft session is not active" + ); + let outputs = StageSession::dflash_propose_batch(&mut native)?; + let shared_lanes = native + .iter() + .zip(before) + .filter(|(request, before)| { + request + .session + .dflash_draft_stats() + .is_some_and(|stats| stats.shared_proposals > *before) + }) + .count(); + let mut proposals = vec![None; requests.len()]; + for (index, output) in order.into_iter().zip(outputs) { + proposals[index] = output; + } + Ok(RuntimeDraftBatch { + proposals, + shared_lanes, + }) + } +} diff --git a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs b/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs index 9685f9a6..29ce4358 100644 --- a/crates/skippy-serving/src/runtime_state/lane_lifecycle.rs +++ b/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, @@ -456,6 +645,31 @@ impl RuntimeState { self.abandon_session_end_kv_exports(session_id); let session = self.session(session_id)?; session.import_kv_page(desc, bytes)?; + self.record_imported_kv_page(session_id, desc) + } + + pub fn try_import_kv_page_chunks<'a>( + &mut self, + session_id: &str, + desc: &RuntimeKvPageDesc, + chunks: impl ExactSizeIterator, + ) -> Result { + self.abandon_session_end_kv_exports(session_id); + if !self + .session(session_id)? + .try_import_kv_page_chunks(desc, chunks)? + { + return Ok(false); + } + self.record_imported_kv_page(session_id, desc)?; + Ok(true) + } + + fn record_imported_kv_page( + &mut self, + session_id: &str, + desc: &RuntimeKvPageDesc, + ) -> Result<()> { let token_end = desc .token_start .checked_add(desc.token_count) diff --git a/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs b/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs index e7d68d49..7c956283 100644 --- a/crates/skippy-serving/src/runtime_state/lane_lifecycle/tests/generation_warmup.rs +++ b/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/crates/skippy-serving/src/runtime_state/model_content.rs b/crates/skippy-serving/src/runtime_state/model_content.rs deleted file mode 100644 index 4917ed3a..00000000 --- a/crates/skippy-serving/src/runtime_state/model_content.rs +++ /dev/null @@ -1,625 +0,0 @@ -//! 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}, - sync::atomic::{AtomicBool, Ordering}, - time::{Instant, SystemTime}, -}; - -type ObservedFiles = Vec<(String, PathBuf, FileStamp)>; - -#[derive(Clone)] -pub(crate) struct VerifiedModelContent { - digest: String, - files: ObservedFiles, -} - -#[derive(Clone, PartialEq, Eq)] -struct FileStamp { - bytes: u64, - modified: Option, - created: Option, - #[cfg(unix)] - identity: (u64, u64, i64, i64), - /// Volume serial number, 128-bit file ID and `ChangeTime`, absent on a - /// filesystem that keeps no change time (FAT, exFAT). - #[cfg(windows)] - identity: Option<(u64, u128, i64)>, -} - -impl FileStamp { - /// Reads the stamp of an open file. Windows only exposes a file's identity - /// and change time through a handle, hence the file and not just its - /// metadata. - fn read(file: &File, metadata: &Metadata) -> std::io::Result { - #[cfg(unix)] - use std::os::unix::fs::MetadataExt; - #[cfg(not(windows))] - let _ = file; - Ok(Self { - bytes: metadata.len(), - modified: metadata.modified().ok(), - created: metadata.created().ok(), - #[cfg(unix)] - identity: ( - metadata.dev(), - metadata.ino(), - metadata.ctime(), - metadata.ctime_nsec(), - ), - #[cfg(windows)] - identity: crate::file_identity::windows_strong_identity(file), - }) - } - - fn of_path(path: &Path) -> std::io::Result { - let file = open_regular(path)?; - let metadata = file.metadata()?; - Self::read(&file, &metadata) - } - - /// Whether the stamp alone proves the bytes are the ones hashed. Size and - /// last-write times do not: a same-size rewrite can restore them. - fn is_strong(&self) -> bool { - #[cfg(unix)] - { - true - } - #[cfg(windows)] - { - self.identity.is_some() - } - #[cfg(not(any(unix, windows)))] - { - false - } - } -} - -/// Opens a regular file for the proof. On Unix the open does not block, so a -/// path replaced by a FIFO after any earlier check cannot hang it, and the -/// type is checked on the open handle. -fn open_regular(path: &Path) -> std::io::Result { - let mut options = std::fs::OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.custom_flags(libc::O_NONBLOCK); - } - let file = options.open(path)?; - if !file.metadata()?.is_file() { - return Err(std::io::Error::other( - "model content proof requires regular files", - )); - } - Ok(file) -} - -impl VerifiedModelContent { - /// Unix and Windows capture strong file stamps before native open, then - /// hash 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(any(unix, windows))] - let (model, content) = match Self::observe_files(config).ok().flatten() { - Some(files) => { - verify_alongside_load(load, |cancelled| Self::from_observed(files, cancelled))? - } - None => (load()?, None), - }; - #[cfg(not(any(unix, windows)))] - let (model, content) = { - let content = Self::observe(config).ok().flatten(); - (load()?, content) - }; - Ok((model, content.filter(|proof| proof.still_matches(config)))) - } - - #[cfg(any(not(any(unix, windows)), test))] - pub(crate) fn observe(config: &StageConfig) -> Result> { - Self::observe_files(config)? - .map(|files| Self::from_observed(files, &AtomicBool::new(false))) - .transpose() - } - - fn observe_files(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); - } - capture_files(files).map(Some) - } - - 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 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, stamp) in files { - ensure!( - !cancelled.load(Ordering::Acquire), - "model content verification cancelled" - ); - let file = open_regular(&path) - .with_context(|| format!("open model content {}", path.display()))?; - let before = file.metadata()?; - ensure!( - FileStamp::read(&file, &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()); - let mut reader = BufReader::new(file); - verified_bytes = verified_bytes.saturating_add(hash_content( - &mut reader, - &mut digest, - &mut buffer, - cancelled, - )?); - let after = reader.get_ref().metadata()?; - ensure!( - FileStamp::read(reader.get_ref(), &after)? == stamp, - "model content changed during verification" - ); - observed.push((name, path, stamp)); - } - let digest = digest - .finalize() - .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, - }) - } - - /// 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 - && FileStamp::of_path(path).is_ok_and(|current| current == *stamp) - }, - ); - if !unchanged { - return false; - } - // Without a strong stamp (platforms other than Unix and Windows, or a - // Windows filesystem with no change time), recheck the actual content - // after model open and at backend construction rather than trust - // preserved timestamps. - self.files.iter().all(|(_, _, stamp)| stamp.is_strong()) - || 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()) - } -} - -/// 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() - .map(|(name, path)| { - let stamp = FileStamp::of_path(&path)?; - Ok((name, path, stamp)) - }) - .collect() -} - -#[cfg(any(unix, windows))] -fn verify_alongside_load( - load: impl FnOnce() -> Result, - 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(&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); - model.map(|model| (model, content)) - }) -} - -fn source_files(config: &StageConfig) -> Result> { - let mut files: Vec<_> = if config.model_part_paths.is_empty() { - let Some(path) = config.model_path.as_deref().map(Path::new) else { - return Ok(Vec::new()); - }; - 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() - }; - if let Some(path) = config.projector_path.as_deref() { - files.push(("projector".into(), PathBuf::from(path))); - } - files - .into_iter() - .map(|(role, path)| Ok((role, path.canonicalize()?))) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// These tests rewrite a file in place with same-length bytes, so on Unix - /// only ctime, and on Windows only `ChangeTime`, can reveal the change. - /// Filesystems stamp both from a coarse clock; wait until that clock has - /// moved past `path`'s stamp so the rewrite cannot land in the same tick as - /// the observed one. - fn wait_for_ctime_to_advance_past(path: &Path) { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - let ctime = |metadata: Metadata| (metadata.ctime(), metadata.ctime_nsec()); - let observed = ctime(std::fs::metadata(path).unwrap()); - let probe = path.with_extension("ctime-probe"); - let deadline = Instant::now() + std::time::Duration::from_secs(60); - loop { - std::fs::write(&probe, b"").unwrap(); - if ctime(std::fs::metadata(&probe).unwrap()) > observed { - break; - } - assert!( - Instant::now() < deadline, - "filesystem ctime did not advance" - ); - std::thread::yield_now(); - } - std::fs::remove_file(probe).unwrap(); - } - #[cfg(windows)] - { - let change_time = |path: &Path| FileStamp::of_path(path).unwrap().identity.unwrap().2; - let observed = change_time(path); - let probe = path.with_extension("ctime-probe"); - let deadline = Instant::now() + std::time::Duration::from_secs(60); - loop { - std::fs::write(&probe, b"").unwrap(); - if change_time(&probe) > observed { - break; - } - assert!( - Instant::now() < deadline, - "filesystem ChangeTime did not advance" - ); - std::thread::yield_now(); - } - std::fs::remove_file(probe).unwrap(); - } - #[cfg(not(any(unix, windows)))] - let _ = path; - } - - /// The strong stamp is what lets Unix and Windows skip rehashing: a - /// same-size rewrite that puts the last-write time back must still be - /// caught (#3158). - #[cfg(any(unix, windows))] - #[test] - fn same_size_rewrite_with_restored_mtime_invalidates_the_proof() { - 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 proof = VerifiedModelContent::observe(&config).unwrap().unwrap(); - assert!(proof.still_matches(&config)); - - let modified = std::fs::metadata(&path).unwrap().modified().unwrap(); - wait_for_ctime_to_advance_past(&path); - std::fs::write(&path, b"new weights").unwrap(); - std::fs::File::options() - .write(true) - .open(&path) - .unwrap() - .set_modified(modified) - .unwrap(); - assert_eq!( - std::fs::metadata(&path).unwrap().modified().unwrap(), - modified - ); - - assert!(!proof.still_matches(&config)); - } - - /// A FIFO with no writer would block a plain open forever. - #[cfg(unix)] - #[test] - fn a_fifo_is_refused_without_blocking() { - use std::os::unix::ffi::OsStrExt; - let root = tempfile::tempdir().unwrap(); - let path = root.path().join("model.gguf"); - let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); - // SAFETY: `c_path` is a NUL-terminated path that outlives the call. - assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); - assert!(FileStamp::of_path(&path).is_err()); - } - - #[cfg(any(unix, windows))] - #[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(any(unix, windows))] - #[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(any(unix, windows))] - #[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 |cancelled| { - started.send(())?; - observed_open.recv_timeout(Duration::from_secs(5))?; - assert!(!cancelled.load(Ordering::Acquire)); - 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, || { - wait_for_ctime_to_advance_past(&path); - 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(); - 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(); - wait_for_ctime_to_advance_past(&model); - 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/crates/skippy-serving/src/runtime_state/panic_recovery.rs b/crates/skippy-serving/src/runtime_state/panic_recovery.rs index 296826a0..f56ee069 100644 --- a/crates/skippy-serving/src/runtime_state/panic_recovery.rs +++ b/crates/skippy-serving/src/runtime_state/panic_recovery.rs @@ -34,6 +34,8 @@ impl PanicRecovery for RuntimeState { // A panic leaves every lane suspect, so no owed export may read one. // A sink that panicked left the completion flag set. self.completing_parked_session_ends = false; + self.prefix_capture = None; + self.next_prefix_capture = None; self.abandon_all_session_end_kv_exports(); let mut session_ids: Vec = self.sessions.keys().cloned().collect(); session_ids.extend(self.session_token_counts.keys().cloned()); diff --git a/crates/skippy-serving/src/runtime_state/resident_prefix.rs b/crates/skippy-serving/src/runtime_state/resident_prefix.rs index c1baa6b3..67b55962 100644 --- a/crates/skippy-serving/src/runtime_state/resident_prefix.rs +++ b/crates/skippy-serving/src/runtime_state/resident_prefix.rs @@ -1,34 +1,130 @@ //! Cold exports read immutable cache owners, never a borrowed execution lane. use super::*; +use std::ops::ControlFlow; + +type CaptureStep = Box ControlFlow<()> + Send>; + +pub(super) struct PrefixCaptureJob { + session_id: String, + preferred: bool, + started: bool, + advance: CaptureStep, +} + +impl RuntimeState { + pub(crate) fn offer_prefix_capture( + &mut self, + session_id: &str, + preferred: bool, + advance: impl FnMut(&mut Self, &str) -> ControlFlow<()> + Send + 'static, + ) { + let job = PrefixCaptureJob { + session_id: session_id.to_owned(), + preferred, + started: false, + advance: Box::new(advance), + }; + match self.prefix_capture.as_ref() { + None => self.prefix_capture = Some(job), + Some(current) + if (!current.preferred && preferred) + || (!current.started + && current.preferred == preferred + && current.session_id == session_id) => + { + self.prefix_capture = Some(job); + } + Some(current) + if current.preferred && !preferred && current.session_id == session_id => {} + Some(_) => { + // Do not let an extension or unrelated request overwrite the + // seed in progress. Keep one later opportunity without + // pinning either entry against eviction. + if self.next_prefix_capture.as_ref().is_none_or(|next| { + !next.preferred || (preferred && next.session_id == session_id) + }) { + self.next_prefix_capture = Some(job); + } + } + } + } + + pub(crate) fn has_prefix_capture_work(&self) -> bool { + self.parked_session_ends.is_empty() + && self.prefix_capture.as_ref().is_some_and(|job| { + // A grid boundary is a fallback. Wait for its canonical + // prompt boundary while requests are still using the runtime. + job.preferred || self.sessions.is_empty() + }) + } + + /// Attempt one copy or admission step using an execution view on the + /// shared model. The saved sequence remains owned by the resident cache. + pub(crate) fn run_prefix_capture_step(&mut self) -> bool { + if !self.has_prefix_capture_work() { + return false; + } + let Some(mut job) = self.prefix_capture.take() else { + return false; + }; + const IDLE_SESSION: &str = "native-prefix-durable-capture"; + let active = self.sessions.keys().next().cloned(); + let session = match active.as_deref() { + Some(session) => session, + None => { + if let Err(error) = self.ensure_session_active(IDLE_SESSION) { + tracing::debug!(%error, "durable prefix capture could not acquire idle lane"); + self.prefix_capture = self.next_prefix_capture.take(); + return true; + } + IDLE_SESSION + } + }; + job.started = true; + let outcome = (job.advance)(self, session); + if active.is_none() + && let Err(error) = self.drop_session_timed(IDLE_SESSION) + { + tracing::debug!(%error, "durable prefix capture could not release idle lane"); + } + self.prefix_capture = match outcome { + ControlFlow::Continue(()) => Some(job), + ControlFlow::Break(()) => self.next_prefix_capture.take(), + }; + true + } +} + impl RuntimeState { pub(crate) fn resident_kv_page_desc( &mut self, session: &str, sequence: i32, - tokens: u64, + tokens: std::ops::Range, ) -> 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) + .resident_kv_range_desc(sequence, layers, tokens) } pub(crate) fn export_resident_kv_page( &mut self, session: &str, sequence: i32, - tokens: u64, + tokens: std::ops::Range, bytes: usize, + component: Option, ) -> 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) + .export_resident_attention_range(sequence, layers, tokens, bytes, component) } pub(crate) fn resident_recurrent_state_bytes( @@ -40,13 +136,80 @@ impl RuntimeState { .resident_recurrent_state_bytes(sequence) } - pub(crate) fn export_resident_recurrent_state( + pub(crate) fn copy_resident_recurrent_range( &mut self, session: &str, sequence: i32, - bytes: usize, - ) -> Result> { + offset: usize, + output: &mut [u8], + ) -> Result<()> { self.session(session)? - .export_resident_recurrent_state(sequence, bytes) + .copy_resident_recurrent_range(sequence, offset, output) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + fn runtime_with_active_lane() -> RuntimeState { + let mut runtime = RuntimeState::new_modelless_for_test(1); + runtime.sessions.insert( + "active".to_owned(), + RuntimeLaneSession { + index: 0, + session: skippy_runtime::StageSession::detached_dflash_for_test(), + resident_prefix: None, + }, + ); + runtime + } + + #[test] + fn later_requests_cannot_replace_the_reusable_seed() { + let mut runtime = runtime_with_active_lane(); + let steps = Arc::new(Mutex::new(Vec::new())); + let seed = steps.clone(); + let mut advanced = false; + runtime.offer_prefix_capture("seed", true, move |_, _| { + seed.lock().unwrap().push("seed"); + if std::mem::replace(&mut advanced, true) { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }); + let extension = steps.clone(); + runtime.offer_prefix_capture("extension", true, move |_, _| { + extension.lock().unwrap().push("extension"); + ControlFlow::Break(()) + }); + + assert!(runtime.run_prefix_capture_step()); + runtime.offer_prefix_capture("pressure", false, |_, _| { + panic!("unrelated pressure replaced a reusable capture") + }); + assert!(runtime.run_prefix_capture_step()); + assert!(runtime.run_prefix_capture_step()); + assert!(!runtime.run_prefix_capture_step()); + assert_eq!(*steps.lock().unwrap(), ["seed", "seed", "extension"]); + } + + #[test] + fn preferred_boundary_can_replace_an_unstarted_grid_capture_in_the_same_request() { + let mut runtime = runtime_with_active_lane(); + let advanced = Arc::new(Mutex::new(false)); + runtime.offer_prefix_capture("seed", false, |_, _| panic!("obsolete checkpoint")); + assert!(!runtime.run_prefix_capture_step()); + let completed = advanced.clone(); + runtime.offer_prefix_capture("seed", true, move |_, _| { + *completed.lock().unwrap() = true; + ControlFlow::Break(()) + }); + + assert!(runtime.run_prefix_capture_step()); + assert!(*advanced.lock().unwrap()); + assert!(!runtime.run_prefix_capture_step()); } } diff --git a/crates/skippy-serving/src/runtime_state/verification_batch.rs b/crates/skippy-serving/src/runtime_state/verification_batch.rs new file mode 100644 index 00000000..87e47bd9 --- /dev/null +++ b/crates/skippy-serving/src/runtime_state/verification_batch.rs @@ -0,0 +1,85 @@ +//! Shared target forwards for already-active speculative lanes. +use super::*; +use skippy_runtime::verification_batch::VerifyBatchRequest; + +pub(crate) struct RuntimeVerificationRequest { + pub(crate) session_id: String, + pub(crate) token_ids: Vec, + pub(crate) sampling: Option, + pub(crate) base_position: u64, +} + +impl RuntimeState { + pub(crate) fn supports_shared_verification(&self) -> bool { + self.model.supports_shared_verification() + } + + pub(crate) fn shared_verification_fits( + &self, + requests: &[&RuntimeVerificationRequest], + ) -> bool { + if !self.supports_shared_verification() { + return false; + } + let total = requests.iter().try_fold(0usize, |sum, request| { + sum.checked_add(request.token_ids.len()) + }); + total.is_some_and(|total| { + requests.iter().all(|request| { + self.sessions + .get(&request.session_id) + .and_then(|lane| lane.session.verification_batch_capacity()) + .is_some_and(|capacity| total <= capacity) + }) + }) + } + + pub(crate) fn verify_batch_sampled( + &mut self, + requests: &[&RuntimeVerificationRequest], + ) -> Result>> { + self.complete_parked_session_ends(); + anyhow::ensure!( + self.supports_shared_verification(), + "target cannot share verification" + ); + let indexes: BTreeMap<_, _> = requests + .iter() + .enumerate() + .map(|(index, request)| (request.session_id.as_str(), index)) + .collect(); + anyhow::ensure!( + indexes.len() == requests.len(), + "duplicate verification session" + ); + let mut order = Vec::new(); + let mut native: Vec<_> = self + .sessions + .iter_mut() + .filter_map(|(id, lane)| { + let &index = indexes.get(id.as_str())?; + let request = requests[index]; + order.push(index); + Some(VerifyBatchRequest { + session: &mut lane.session, + token_ids: &request.token_ids, + sampling: request.sampling.as_ref(), + }) + }) + .collect(); + anyhow::ensure!( + native.len() == requests.len(), + "verification session is not active" + ); + let outputs = StageSession::verify_batch_sampled(&mut native)?; + let mut predictions = vec![Vec::new(); requests.len()]; + for (index, output) in order.into_iter().zip(outputs) { + predictions[index] = output; + self.add_session_tokens( + &requests[index].session_id, + requests[index].token_ids.len() as u64, + ); + } + Ok(predictions) + } +} diff --git a/crates/skippy-serving/src/stage_request_class.rs b/crates/skippy-serving/src/stage_request_class.rs new file mode 100644 index 00000000..c7eeac76 --- /dev/null +++ b/crates/skippy-serving/src/stage_request_class.rs @@ -0,0 +1,161 @@ +//! A request's tier and cache partition on the binary stage wire. +//! +//! Stage 0 stamps the class of each request on the cache-bearing messages it +//! sends downstream. A downstream stage lowers that claim to the highest tier +//! its host assigned to the stage and evicts by the result. It partitions its +//! caches by both, so the claims it merges into one tier still never share a +//! prefix: every stage keeps the same isolation as stage 0. + +use skippy_inference_api::{InferenceRequestClass, InferenceRequestTier}; +use skippy_protocol::StageConfig; +use skippy_protocol::binary::StageStateHeader; + +/// Stamp `class` on an outgoing stage message header. +pub(crate) fn stamp_request_class(state: &mut StageStateHeader, class: InferenceRequestClass) { + state.set_request_tier_demotion(tier_demotion(class.tier())); + state.set_private_cache_partition(class.is_private()); +} + +/// The class a stage serves a message at: the stamped claim, lowered to the +/// stage's configured maximum tier. +pub(crate) fn stage_request_class( + config: &StageConfig, + state: StageStateHeader, +) -> InferenceRequestClass { + claimed_request_class(state).limited_to(max_request_tier(config)) +} + +/// The cache namespace a stage records and looks up a message's prefixes in: +/// the served class's partition, which sets eviction order, and within it the +/// claimed one when the stage's cap lowered it. +pub(crate) fn stage_cache_namespace( + config: &StageConfig, + state: StageStateHeader, +) -> Option { + let served = stage_request_class(config, state); + let claimed = claimed_request_class(state); + if served == claimed { + return served.cache_namespace(None); + } + let claimed_partition = claimed + .cache_partition() + .unwrap_or_else(|| InferenceRequestTier::Local.as_str().to_owned()); + served.cache_namespace(Some(format!("claimed-{claimed_partition}"))) +} + +fn claimed_request_class(state: StageStateHeader) -> InferenceRequestClass { + InferenceRequestClass::new( + tier_from_demotion(state.request_tier_demotion()), + state.private_cache_partition(), + ) +} + +/// The highest tier this stage serves. An unrecognized name is `mesh`, so a +/// malformed cap fails low. +fn max_request_tier(config: &StageConfig) -> InferenceRequestTier { + config + .max_request_tier + .as_deref() + .map_or(InferenceRequestTier::Local, |tier| { + InferenceRequestTier::parse(tier).unwrap_or(InferenceRequestTier::Mesh) + }) +} + +fn tier_demotion(tier: InferenceRequestTier) -> u8 { + InferenceRequestTier::Local.code() - tier.code() +} + +fn tier_from_demotion(demotion: u8) -> InferenceRequestTier { + InferenceRequestTier::Local + .code() + .checked_sub(demotion) + .and_then(InferenceRequestTier::from_code) + .unwrap_or(InferenceRequestTier::Mesh) +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_protocol::binary::WireMessageKind; + + fn header(class: InferenceRequestClass) -> StageStateHeader { + let mut state = StageStateHeader::new(WireMessageKind::PrefillEmbd); + stamp_request_class(&mut state, class); + state + } + + #[test] + fn unstamped_messages_are_local_and_unpartitioned() { + let state = StageStateHeader::new(WireMessageKind::PrefillEmbd); + let config = StageConfig::default(); + assert_eq!( + stage_request_class(&config, state), + InferenceRequestClass::default() + ); + assert_eq!(stage_cache_namespace(&config, state), None); + } + + #[test] + fn every_class_round_trips_through_the_header() { + let config = StageConfig::default(); + for tier in InferenceRequestTier::ALL { + for private in [false, true] { + let class = InferenceRequestClass::new(tier, private); + assert_eq!(stage_request_class(&config, header(class)), class); + } + } + } + + #[test] + fn the_stage_cap_lowers_but_never_raises_a_claim() { + let config = StageConfig { + max_request_tier: Some("trusted".into()), + ..StageConfig::default() + }; + let local = InferenceRequestClass::new(InferenceRequestTier::Local, true); + let mesh = InferenceRequestClass::new(InferenceRequestTier::Mesh, false); + assert_eq!( + stage_request_class(&config, header(local)), + InferenceRequestClass::new(InferenceRequestTier::Trusted, true) + ); + assert_eq!(stage_request_class(&config, header(mesh)), mesh); + let malformed = StageConfig { + max_request_tier: Some("owner".into()), + ..StageConfig::default() + }; + assert_eq!( + stage_request_class(&malformed, header(local)).tier(), + InferenceRequestTier::Mesh + ); + } + + #[test] + fn claims_a_cap_merges_keep_separate_partitions_and_evict_at_the_cap() { + let config = StageConfig { + max_request_tier: Some("mesh".into()), + ..StageConfig::default() + }; + let namespaces = [ + InferenceRequestClass::new(InferenceRequestTier::Local, false), + InferenceRequestClass::new(InferenceRequestTier::Trusted, false), + InferenceRequestClass::new(InferenceRequestTier::Mesh, false), + InferenceRequestClass::new(InferenceRequestTier::Local, true), + InferenceRequestClass::new(InferenceRequestTier::Mesh, true), + ] + .map(|class| stage_cache_namespace(&config, header(class))); + let distinct = namespaces + .iter() + .collect::>() + .len(); + assert_eq!(distinct, namespaces.len(), "{namespaces:?}"); + for namespace in &namespaces { + assert_eq!( + InferenceRequestClass::from_cache_namespace(namespace.as_deref()).tier(), + InferenceRequestTier::Mesh, + "{namespace:?}" + ); + } + // A claim the cap leaves alone keeps the plain partition. + assert_eq!(namespaces[2].as_deref(), Some("tier:mesh:")); + } +} diff --git a/crates/skippy-serving/tests/fixtures/skippy-kv-qualification-context.txt b/crates/skippy-serving/tests/fixtures/skippy-kv-qualification-context.txt new file mode 100644 index 00000000..7e3a50ec --- /dev/null +++ b/crates/skippy-serving/tests/fixtures/skippy-kv-qualification-context.txt @@ -0,0 +1 @@ +000. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 001. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 002. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 003. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 004. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 005. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 006. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 007. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 008. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 009. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 010. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. 011. We are validating exact prefix cache reuse in the staged serving path with a deterministic long prompt, stable wording, and enough repeated context to cross the restore threshold without depending on model creativity. diff --git a/docs-site/content/cli.mdx b/docs-site/content/cli.mdx index 47663375..67d6302f 100644 --- a/docs-site/content/cli.mdx +++ b/docs-site/content/cli.mdx @@ -89,6 +89,8 @@ run its full path, such as `skippy models download --help`. | `--n-gpu-layers N` | Set the number of local model layers to offload. Use `-1` to offload all supported layers. | | `--gpu-id ID` | Pin an offloaded local model to a stable GPU ID. Use `doctor --device-inventory` to inspect IDs and visibility. | | `--generation-concurrency N` | Set the maximum active generation requests. Automatic local planning defaults to four lanes sharing a KV pool. | +| `--prefix-cache-checkpoint-ram SIZE` | Set the native L1 recurrent-checkpoint budget. The default is 1 GiB. | +| `--prefix-cache-ram SIZE` | Set the separate L2 host-RAM budget for disk fills. Use `off` to disable L2. | | `--mmproj PATH` | Select a multimodal projector GGUF. By default, Skippy looks for a matching installed projector. | | `--on-demand` | Defer an unsplit model's native load until the first inference request. Eager loading is the default. | | `--idle-evict-secs N` | Release an unsplit model after 1–86,400 idle seconds. Omit to disable idle eviction. | diff --git a/docs-site/content/configuration/reference.mdx b/docs-site/content/configuration/reference.mdx index fb0e9643..c94bbbbe 100644 --- a/docs-site/content/configuration/reference.mdx +++ b/docs-site/content/configuration/reference.mdx @@ -91,7 +91,8 @@ The environment overrides are `SKIPPY_SERVE_ON_DEMAND`, | `prefix_cache` | Select `auto`, `on`, `off`, or `record` | | `prefix_cache_budget` | Set the resident retention target | | `prefix_cache_max_entries`, `prefix_cache_min_tokens` | Bound retained entries and minimum useful prefixes | -| `prefix_cache_ram` | Bound native recurrent-checkpoint RAM; serialized runtimes use an optional tier above disk | +| `prefix_cache_ram` | Set the L2 host-RAM budget for disk fills | +| `prefix_cache_checkpoint_ram` | Set the L1 recurrent-checkpoint RAM budget, which defaults to 1 GiB | | `prefix_cache_retention_tokens` | Bound attention cells retained after requests finish. Defaults to 16,384 tokens. Use `0` to release all finished-request cells or `unbounded` to retain as much as the shared pool allows. | | `prefill_admission` | Select `cooperative` (default) or `serialized` suffix prefill | | `kv_cache_disk`, `kv_cache_disk_dir` | Set the disk cache budget and location. The default is `off`. The `auto` budget is capped at 64 GiB. | diff --git a/docs-site/content/kv-caching/disk-tier.mdx b/docs-site/content/kv-caching/disk-tier.mdx index 5e6cdd09..c23bc3c1 100644 --- a/docs-site/content/kv-caching/disk-tier.mdx +++ b/docs-site/content/kv-caching/disk-tier.mdx @@ -41,10 +41,11 @@ honors the minimum free-space reserve. Use `off` to disable the tier. ## How the tiers interact Skippy compares compatible resident and committed disk prefixes and restores -the longest valid checkpoint. A resident prefix wins a tie. Resident native -state is exported when it is cold-evicted, rather than serializing every warm -record. Restored disk entries are verified before use. A refused or failed -cold offload can lose reuse and require cold prefill on a later request. +the longest valid checkpoint. A resident prefix wins a tie. Eviction releases +native KV cells immediately. While the runtime is idle, Skippy can export a +retained checkpoint and queue a bounded write. A prefix evicted before capture +may require cold prefill on a later request. Skippy verifies restored disk +entries before use. ## Failure policy @@ -53,13 +54,14 @@ operator's retention policy. Once a valid configuration is running, storage unavailability fails open for inference: Skippy logs the problem and serves with cold prefill rather than making the model unavailable. -Native resident runtimes use `prefix_cache_ram` for recurrent checkpoints, -independently of disk. Serialized runtimes use it for an optional host-RAM tier -above an active disk tier: +`prefix_cache_ram` sets the optional L2 host-RAM tier above an active disk +tier. `prefix_cache_checkpoint_ram` sets the separate L1 recurrent-checkpoint +budget: ```toml [cache] prefix_cache_ram = "4GiB" +prefix_cache_checkpoint_ram = "1GiB" kv_cache_disk = "32GiB" ``` @@ -78,7 +80,8 @@ kill switches. Unset them before explicitly enabling prefix caching. | `kv_cache_disk` | `off` (default), `auto`, or IEC size | Enable and bound durable storage | | `kv_cache_disk_dir` | Local directory | Choose the cache root. Defaults to `$SKIPPY_HOME/kv-cache` or `~/.skippy/kv-cache`. | | `kv_cache_min_free` | IEC size of at least `1GiB` | Reserve free space on the volume. Defaults to `16GiB`. | -| `prefix_cache_ram` | `off` or IEC size | Bound native checkpoint RAM; serialized runtimes can add a RAM tier above disk | +| `prefix_cache_ram` | `off` or IEC size | Set the L2 host-RAM budget for disk fills. | +| `prefix_cache_checkpoint_ram` | `auto` or positive IEC size | Set the L1 checkpoint budget. Defaults to 1 GiB. | Invalid startup configuration is fatal. Runtime storage failure is not: inference continues with cold prefill and Skippy reports the cache error. diff --git a/docs-site/content/kv-caching/index.mdx b/docs-site/content/kv-caching/index.mdx index 8621a924..98c503d7 100644 --- a/docs-site/content/kv-caching/index.mdx +++ b/docs-site/content/kv-caching/index.mdx @@ -78,9 +78,11 @@ explicit choice fails rather than silently changing precision. Native resident caching keeps attention cells in the shared KV pool. Hybrid and recurrent models also retain immutable checkpoints in a separate, bounded -host-RAM budget. This works with disk caching disabled. Set `prefix_cache_ram` -to an IEC size to bound those checkpoints; `off` or an unset value selects the -1 GiB default. Disable prefix caching itself to retain no checkpoints. +host-RAM budget. This works with disk caching disabled. Set +`prefix_cache_checkpoint_ram` to a positive IEC size or leave it at the +1 GiB default. Move any previous native checkpoint override from +`prefix_cache_ram` to this setting. Disable prefix caching itself to retain +no checkpoints. For serialized runtimes on unified-memory systems, set `prefix_cache_ram = "off"` to avoid a second copy in the same physical memory. @@ -118,7 +120,8 @@ status, matched prefix tokens, suffix prefill tokens, and restore source. | `prefix_cache_budget` | Set the resident retention target | | `prefix_cache_exact_budget` | Set the exact-state retention ceiling; one snapshot may exceed it | | `prefix_cache_max_entries` | Limit retained prefix entries | -| `prefix_cache_ram` | Bound native recurrent checkpoints; serialized runtimes use optional L2 | +| `prefix_cache_ram` | Set the L2 host-RAM budget for disk fills | +| `prefix_cache_checkpoint_ram` | Bound native L1 recurrent checkpoints | | `prefix_cache_retention_tokens` | Bound attention cells retained after requests finish | | `prefill_admission` | Cooperatively batch uncached suffixes, or serialize their prefill | | `prefix_cache_min_tokens` | Avoid recording prefixes below a token threshold | diff --git a/docs/CACHE_CORRECTNESS_GATE.md b/docs/CACHE_CORRECTNESS_GATE.md index d3286c76..f11f6fc8 100644 --- a/docs/CACHE_CORRECTNESS_GATE.md +++ b/docs/CACHE_CORRECTNESS_GATE.md @@ -1,6 +1,155 @@ # Cache correctness gate -Prepare local observations with the existing operator owner: +## GPU behavior and cross-tier reuse + +Run the explicit qualification case on arm64 macOS with the pinned +[Qwen3-4B Q4_K_M GGUF](https://huggingface.co/unsloth/Qwen3-4B-GGUF/blob/22c9fc8a8c7700b76a1789366280a6a5a1ad1120/Qwen3-4B-Q4_K_M.gguf). +The [fixture manifest](../crates/skippy-model-artifact/src/kv_fixtures/models.json) +pins the GGUF and embedded chat template for each KV architecture case. Set `SKIPPY_CACHE_QUAL_FAMILY` +to `dense-attention` (the default), `hybrid-dense`, `attention-moe`, or +`hybrid-moe`, and supply the matching GGUF and a Skippy native build from the +repository's pinned recipe. A matching GPU and all fixture inputs are required; +missing inputs never become passing skips. + +```sh +LLAMA_STAGE_BUILD_DIR=/absolute/skippy-metal-build \ +SKIPPY_CACHE_QUAL_MODEL=/absolute/Qwen3-4B-Q4_K_M.gguf \ +SKIPPY_CACHE_QUAL_REPORT_DIR=/absolute/fresh-report-directory \ +just cache-correctness-metal +``` + +On ARM64 or x86_64 Linux with CUDA, point the same variables at the CUDA builds and use +`just cache-correctness-cuda`. + +The gate checks request identity, actual cache restoration, avoided prefill, +and known answers. Each base/replay request must return the JSON object +`{"code":1729}`. Conversation extensions change the requested code to 3141 +and then 2718; a changed tail requests 1618. The grammar constrains the shape +but does not supply or force the answer. Wrong values, malformed/truncated JSON, +and missing native generation evidence fail the gate. The harness validates +content from the production chat parser; a native-grammar-permitted Markdown +wrapper is parsed there rather than rejected as raw JSON. Equivalent JSON whitespace +or tokenization is allowed; free-form wording is not a correctness oracle. + +Report schema **11**, contract `behavior_and_reuse_v1`, separates this gate from +the previous numerical contract. Raw decoder text is retained in `raw_content` +alongside parsed `content`; the optional diagnostic field is additive to schema 11. +Raw generated tokens and top-five scores remain +in the report for diagnosis. Exact alternative-token rankings and numerical +score differences do not determine qualification. Old reports cannot qualify +under the new contract. + +An optional `SKIPPY_CACHE_QUAL_LLAMA_SERVER` captures pinned upstream observations +on the same backend as diagnostics. It is not built or required by ordinary KV +qualification or package CI. If supplied, its version and executable digest are +retained; startup/computation failures are recorded in `reference_error` and do +not establish or invalidate Skippy KV behavior. Native operator/parity regressions +belong in the existing native contract tests. + +The cache-disabled Skippy result qualifies the cold baseline. An attention +model must hit its native resident prefix in L1. A hybrid model must restore +both KV and recurrent state at the rendered chat checkpoint and prefill the +suffix. Every replay checks the reported token accounting against the +selected prefix. + +The L1 test also replays two successive conversation extensions and a changed +tail after a common prefix. Each request runs cold and warm through Skippy. +The validator derives retained-prefix bounds from the actual prompt plus +delivered generated tokens, including a stop token the scheduler may have +consumed before observing Stop. Receipts exclude queued, undelivered samples; +the harness must not subtract another token from them. Valid extra reuse is accepted; claims beyond retained history +or inconsistent suffix accounting fail. A recurrent checkpoint is reusable only +when the full checkpoint remains a prefix of the rendered prompt. Each conversation case +reports its own outcome and token accounting. + +The suite also exercises schema-constrained JSON, a forced named tool call, +and retrieval from the beginning of a prompt of at least 4,096 tokens. Skippy +uses an 8,192-token context. The structured cases compare completed +objects or tool names and arguments against a known answer. Each case uses +its own trusted Skippy scope and reports cold, seed, and warm cache usage. + +The cross-tier case forces eviction of native and serialized L1 entries. Two +L3 restores promote the checkpoint into host RAM. The next replay must hit L2 +without reading a disk payload. The publisher exits cleanly, and a new process +reopens the disk cache with empty in-memory tiers and must hit L3. While that +process owns the store, a contender must be denied access, generate the cold +result using in-memory caching, and leave the committed pack intact. The test +kills the owner and requires a fresh process to discard an interrupted write +and restore the committed checkpoint. Every restore must produce the +known answer and account for the remaining suffix prefill. A request from a +different trusted execution scope must miss, and truncating the disk object +must produce a detected corruption and a successful cold recompute. + +Skippy must show layer offload on the selected GPU backend. The fresh +directory retains `result.json` with the outcome, fixture and executable +identities, and token evidence alongside the native logs. The report records +each wrong answer, identity mismatch and invalid cache observation independently. +Missing prerequisites or telemetry fail qualification. Ordinary Rust tests run the +evidence validator offline. + +Each GPU cell also primes L1, L2, and L3 with an explicit chat +template, then adds a Jinja comment that renders identical prompt bytes. +The revised template must cold-prefill every token, preserve the output +and leave the disk-payload read counter unchanged. The cell JSON retains +the observed state for offline verification. + +Recheck a retained report without loading a model, starting a server, or +requiring a GPU. The verifier checks the fixture, behavioral contract, +qualification settings, and recorded test binary hash. Optional reference +provenance is checked when present. It recomputes the result +from the captured outputs and cache observations. + +```sh +just cache-correctness-verify metal /absolute/report-directory/result.json +``` + +### Run all four KV architecture cases + +```sh +SKIPPY_CACHE_QUAL_FIXTURE_DIR=/absolute/read-only-model-directory \ +LLAMA_STAGE_BUILD_DIR=/absolute/skippy-metal-build \ +just cache-correctness-matrix metal /absolute/fresh-report-directory +``` + +Use `cuda-arm64` for DGX Spark and `cuda` for x86-64 Linux CUDA. The matrix uses each exact +GGUF filename from the manifest and writes a `batch-result.json` with four +independent outcomes and SHA-256 digests of the retained cell reports. Missing +inputs produce explicit failures. A model failure leaves its diagnostics in +place and the other models still run. +Use `--build` to build the omitted native runtime with Just. It does not build +an upstream reference. Build a reference explicitly with +`just cache-correctness-reference SOURCE BUILD PIN` when investigating numerical +or native execution differences. + +To verify a retained matrix, pass the source SHA selected for admission: + +```sh +just cache-correctness-verify-matrix metal "$source_sha" /absolute/metal-report-directory +just cache-correctness-verify-matrix cuda "$source_sha" /absolute/cuda-report-directory +``` + +Each verification requires a matrix recorded from a clean checkout of that +source. It verifies the fixture manifest, then checks each report digest and +recomputes its decision. Dirty worktree results can still be used for +diagnostics. + +For KV-affecting PRs and pushes to `main`, CI runs one dense fixture inside +the Metal and Linux ARM64 CUDA 13 package jobs after device smoke. It compares +cold, warm L1, and L3 restart outputs and checks that the selected cache tier +actually restored the expected tokens. Full CI, including nightly, release and +llama upgrade validation, runs all four cases on Metal and Linux ARM64 CUDA 13 +on Spark. Each backend runs its models in sequence with separate cache roots +and reports. Qualification does not build an upstream reference. + +The Rust test harness loads the verified runtime from the same source-bound +package used for device smoke. It uses `hf download` at each pinned revision +with the runner's Hugging Face cache on the NAS. CI retains the runtime +manifest digest, fixture reports, and logs. A failed model, missing fixture, +absent GPU, or incomplete required job fails CI. + +## Historical state handoff batch + +Earlier checkouts that include the state-handoff operator prepare local observations with: ```sh cargo xtool automation cache-family-run prepare-full --input /absolute/operator.json --output /absolute/fresh-preparation diff --git a/docs/CAUSAL_DECISIONS.md b/docs/CAUSAL_DECISIONS.md index 2da05c99..f9b574a8 100644 --- a/docs/CAUSAL_DECISIONS.md +++ b/docs/CAUSAL_DECISIONS.md @@ -111,9 +111,9 @@ fallback. In split execution, the terminal worker computes scores and returns only a bounded selected-token vector. Full vocabulary logits remain inside the native -runtime. All workers must support stage protocol generation 18, wire header -version 17 and Skippy ABI 0.1.88. Upgrade the whole chain together; older stage -peers fail negotiation. Additive `system_one` discovery does not grant this +runtime. All workers must support stage protocol generation 19, wire header +version 18 and Skippy ABI 0.1.95. Upgrade the whole chain together so +they can negotiate. Additive `system_one` discovery does not grant this ability to an older runtime. No persisted-data migration is required. ## Model-backed validation diff --git a/docs/DATA_FLOW.md b/docs/DATA_FLOW.md index 204d7dc0..8bd69ffa 100644 --- a/docs/DATA_FLOW.md +++ b/docs/DATA_FLOW.md @@ -45,7 +45,7 @@ chain alone makes the hot path six hops, or about 60 ms before compute. Generation 7 introduced direct prediction return, and generation 9 added canonical stage-admission descriptors. Generation 18 is the current compatibility-breaking cutover: a peer is stage compatible only when it -advertises both `skippy-stage/2` and the complete `stage-generation-18` bundle. +advertises both `skippy-stage/2` and the complete `stage-generation-19` bundle. Every load carries a canonical admission descriptor. The ready response echoes that descriptor exactly before topology publication. Prediction-bearing messages return directly from the final/readout stage to the diff --git a/docs/PROMPT_CACHE.md b/docs/PROMPT_CACHE.md index f444b2a7..a0a45798 100644 --- a/docs/PROMPT_CACHE.md +++ b/docs/PROMPT_CACHE.md @@ -51,19 +51,19 @@ 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, 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, 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. +Persistent reuse uses the model identity supplied by model resolution and artifact +admission: the source-model digest and, for packaged inputs, the manifest digest +and package reference. The cache does not reopen or rehash model files, inspect +filesystem timestamps, or create a second model identity. Changing admitted +weights changes the existing cache keys. Configurations without a source-model +or manifest digest keep their native in-memory cache but disable L3 and its +host-RAM tier. + +Runtime compatibility remains part of the state key: native ABI, backend/device +placement, layer range, KV layout, context shape, payload and storage codec must +match before state can be reused. Run and topology instance labels do not change +model identity. Cache entries written with the former loaded-content wrapper +have different keys and are not reused; normal pruning can reclaim them. A saved native prefix remains usable after the originating session is freed. Eviction drops the cache's native attention references and recurrent checkpoint. @@ -85,10 +85,11 @@ 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` supplies this -budget. A zero/unset value selects the bounded 1 GiB native-cache default; -disable prefix caching itself to retain no entries. +budget merely because it is the last entry. Set +`--prefix-cache-checkpoint-ram SIZE` to override the 1 GiB default. +`--prefix-cache-ram` controls the separate L2 host-RAM tier. Move an +existing native checkpoint override to the new flag to preserve its size. +Disable prefix caching itself to retain no entries. ## Admission @@ -113,11 +114,11 @@ prompt chunks with decode rows is visible per native batch on the ## 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. +The resident path reclaims cells immediately when it evicts a prefix. +With L3 enabled, the scheduler can capture one retained prefix while the +runtime is idle and hand its owned payload to the disk writer. A prefix can +be evicted before capture or skipped when the export or writer queue exceeds +its byte limit. L3 verifies payload integrity on restore. 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. @@ -126,7 +127,8 @@ 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 +Durable identity includes the native ABI, runtime device order and placement, +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. @@ -169,3 +171,53 @@ 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. + +## Inspect and maintain the disk cache + +Standalone Skippy defaults to an automatic L3 budget. It uses at most 64 GiB +and preserves a 16 GiB filesystem reserve by default. Use `--kv-cache-disk off` +to disable L3. When Skippy prepares a local model with prefix reuse enabled, +it allows up to 256 MiB of L2 host RAM by default for serialized disk fills. Use `--prefix-cache-ram off` +to disable that tier. Prepared stage configurations carry their own L2 +limits. + +Pass the settings file used to start Skippy, or use the same disk cache flags +and environment variables. The commands use the serving settings precedence +of CLI flags, environment, TOML, and defaults. + +```sh +skippy kv-cache --settings serve.toml status +skippy --output json kv-cache --settings serve.toml status +skippy kv-cache --settings serve.toml prune --target 8GiB +skippy kv-cache --settings serve.toml clear --model-identity "$model_identity" --yes +``` + +`status` reports the active disk limits, filesystem free space, usage and +object counts, activity since the cache opened, startup reconciliation, and +inventory grouped by model identity. Inventory reports logical state bytes +per model. The whole-store usage accounts for physical space shared by cached +entries. JSON emits one result object with `schema_version: 1`. JSONL wraps +that object in the standard Skippy `result` event. + +`prune` trims least-recently-used inactive entries toward a whole-store byte +target. Omit `--target` to use the active cache budget's low-water mark. +`--model-identity` restricts which entries can be removed. Copy the complete +identity printed by `status`. The result reports how much space was freed and +whether the target was reached. `clear` removes all eligible entries for the +selected scope. Pinned entries remain available to in-flight requests. +Mutations prompt for consent in a human terminal. Use `--yes` in scripts. + +Each disk cache directory has one live Skippy owner. A replacement can +reopen the directory after shutdown or process failure. When the directory +is already owned, a second server logs the conflict and continues serving +with L3 unavailable. Use separate cache directories for concurrent servers +that each need L3. + +For a running server, maintenance goes through its private, authenticated +loopback listener. An offline command can open and reconcile the store once +it holds the exclusive cache root lock. If status reports that the root is +already owned, use the serving process's cache settings and OS account. If +the owner is unreachable, stop it before issuing offline maintenance. +`read_only_low_space` means the store can still serve reads and has stopped +admitting writes to preserve the filesystem reserve. Free space on that +filesystem or prune inactive entries, then check status again. diff --git a/docs/SERVING_SETTINGS.md b/docs/SERVING_SETTINGS.md index 2e79cc57..3d35dd69 100644 --- a/docs/SERVING_SETTINGS.md +++ b/docs/SERVING_SETTINGS.md @@ -376,7 +376,8 @@ known size. Use them without `--prompt` or `--stage-transport`. | `--prefix-cache` | `prefix_cache` | Prompt reuse: auto, on, off, record | | `--prefix-cache-codec` | `prefix_cache_codec` | Durable representation: native or experimental cachegen | | `--prefix-cache-budget` | `prefix_cache_budget` | Retention target: auto, unbounded, or IEC size; exact snapshots may exceed it | -| `--prefix-cache-ram` | `prefix_cache_ram` | Native recurrent-checkpoint RAM budget, independent of disk; off/unset selects the bounded default. Serialized runtimes use an optional host-RAM tier requiring disk caching | +| `--prefix-cache-ram` | `prefix_cache_ram` | L2 host-RAM tier for disk fills. Use off or a fixed IEC size. | +| `--prefix-cache-checkpoint-ram` | `prefix_cache_checkpoint_ram` | L1 recurrent-checkpoint RAM. Use auto for 1 GiB or a positive IEC size. | | `--prefix-cache-max-entries` | `prefix_cache_max_entries` | Maximum retained prefix entries | | `--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 | @@ -384,7 +385,7 @@ known size. Use them without `--prompt` or `--stage-transport`. | `--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` | `off` (default), `auto` (up to 64 GiB), or a fixed IEC size. | +| `--kv-cache-disk` | `kv_cache_disk` | Disk cache budget. Defaults to `auto` with a 64 GiB cap. Use `off` or an IEC size to override. | | `--kv-cache-disk-dir` | `kv_cache_disk_dir` | See `skippy serve --help` for values and defaults. | | `--kv-cache-min-free` | `kv_cache_min_free` | See `skippy serve --help` for values and defaults. | diff --git a/docs/design/METAL_DECODE_BENCHMARKS.md b/docs/design/METAL_DECODE_BENCHMARKS.md new file mode 100644 index 00000000..c8861042 --- /dev/null +++ b/docs/design/METAL_DECODE_BENCHMARKS.md @@ -0,0 +1,303 @@ +# Native decode benchmark evidence + +Status: draft, 2026-11-17. Three standalone campaigns per mode are complete and locally re-audited; +the matched vanilla comparison is complete as a fixed-budget observation, with output drift documented below. + +## Matched comparison + +The tables below are historical comparisons of the explicitly pinned snapshots, not measurements of the current PR against its immediate base. The separate three-way table includes vanilla llama.cpp. +Vanilla uses the same llama.cpp upstream pin, not the Skippy native patch queue. +An empty hardware/model cell is unmeasured, never an inferred number. + +Hardware: one 256 GB Apple M3 Ultra, macOS 26.7.1. Skippy main is +`fbc3349cd406786e43f6579590c9a12b0cd49c05`. The measured candidate snapshot is +`c2055c4a3bb20f601f0074e6fe06a7c85efef01d`. The current PR has subsequent +engine and scheduler changes; these rates must not be attributed to its current head. Both use llama.cpp +`8954f194837d2ec4d5f67f20c81b84abe63883ba`. The candidate includes the earlier +Mesh-hosted/Jared native work and subsequent engine changes, ported into the +standalone repository. These numbers do not isolate each contributor's changes. + +Jared's placement/batching port was already merged into Mesh's `gi` branch as +[Mesh PR #33](https://github.com/general-inference/mesh-llm/pull/33). The measured +standalone extraction baseline is a different source line: its core native +patch queue ends at 0016, while PR #33 contains patches 0017 through 0035 as +well. This comparison includes bringing that work into standalone Skippy; the +headline is not an incremental gain over PR #33. + +| Serving mode | Skippy main TPS | Skippy PR #9 TPS | Candidate vs main | +|---|---:|---:|---:| +| Plain, concurrency 1 | 35.90 | 98.98 | +175.70% | +| Plain, concurrency 2, aggregate | 62.71 | 162.17 | +158.62% | +| DFlash, concurrency 1 | 163.64 | 164.82 | +0.72% | +| DFlash, concurrency 2, aggregate | 155.27 | 206.15 | +32.77% | + +These are serving throughput measurements: fixed output tokens divided by +pooled HTTP batch elapsed time, including prefill. Each concurrency is pooled +independently. They pool three fresh-process campaigns with three measured cycles each. +Single-request DFlash is effectively unchanged. These are not a cross-hardware +claim or a comparison with BaseRT/Splash. + +The target is `unsloth/Qwen3.6-35B-A3B-GGUF`, revision +`a483e9e6cbd595906af30beda3187c2663a1118c`, file +`Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf` (22,360,456,160 bytes), SHA-256 +`707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450`. +DFlash additionally uses `ethanwtodd/Qwen3.6-35B-A3B-DFlash2-Q8_0-GGUF`, +revision `65aaab9513e9c6608ada7c7d16e6532c198a2296`, file +`Qwen3.6-35B-A3B-DFlash2-Q8_0.gguf` (570,468,544 bytes), SHA-256 +`986b8f24ac3469ed122946fb5be5b1fbe186467f2573f84e48bdbf7db278b327`. +There is no model tuning or quantization change between arms. + +## Method and custody + +- Eight fixed completion prompts, temperature zero, top-k one, 128 output + tokens per request, concurrency one and two, three warmup and three measured + cycles, and within-prompt old/new/new/old measured order. +- Context 8192, batch 2048, microbatch 512, four CPU threads and four batch + threads, f16 K/V, generation concurrency two, native MTP and prompt/disk + caches disabled; DFlash proposal cap seven when enabled. +- Both arms use packaged release CLIs and native libraries from their pinned + source trees. All 21 loaded ggml/llama library paths were checked against + each arm's own bundle. Model/draft and package hashes were verified. +- Whole ABBA blocks with competing load or non-nominal thermals are discarded + and retried; 100 ms observations cover requests. Across the three campaigns, plain discarded 146 blocks and + DFlash 52. Each mode accepted 864 requests including warmup. +- All accepted response text hashes match across arms and cycles; every + response has 128 output tokens and zero prompt-cache hits. Independent + pooling and artifact audits passed remotely and again on downloaded raw + evidence locally. +- No build/test work runs on the benchmark host during timed windows. + +Jianyang build job: `job_dae3gdjd1gvr22d`, run `run_bjf8g9z1gvr6fzy`. +Measurement job: `job_n64z1nezwe0wp85`, run `run_06cmr5v5yx35a14`. +The measurement job was intentionally cancelled after both retained-v-main +comparisons and audits completed, to publish those artifacts separately from +its unfinished cache experiment. Cancellation does not supply a successful +whole-job or cache-performance result. + +The run retains `retained-{plain,dflash}-0-{summary,independent-audit,provenance}.json` +and `retained-{plain,dflash}-0-evidence.tar.gz`, including requests, raw +responses, accepted/rejected batches, thermal/process observations, commands, +and loaded-library paths. Local copies are under the ignored +`target/m3-decode-campaign/measure-artifacts-1/` directory. + +## Remaining work + +The two further fresh-process campaigns per mode completed in +`job_a3z1zb6g1w0p9vx`, run `run_8mb0n0bdpd81mgb`. All four additional raw +archives passed a second local independent audit. + +### Three-way fixed-budget observation + +All three arms used the same M3, upstream pin, Apple Clang build 21000334, +model/draft bytes, input token counts, sampling settings, and 128-output-token +budget. Each mode has one fresh-process campaign with three warm and three +measured cycles, measured order vanilla/main/PR/PR/main/vanilla, and the same +whole-block load/thermal exclusions. Vanilla uses `cache_prompt:false` on every +request; Skippy prefix/disk caches are disabled. + +| Serving mode | Vanilla llama.cpp TPS | Skippy main TPS | Skippy PR #9 TPS | +|---|---:|---:|---:| +| Plain, concurrency 1 | 96.55 | 36.15 | 98.93 | +| Plain, concurrency 2, aggregate | 148.79 | 62.93 | 161.64 | +| DFlash, concurrency 1 | 169.20 | 164.08 | 165.55 | +| DFlash, concurrency 2, aggregate | 196.99 | 154.82 | 205.24 | + +**Vanilla cross-engine exact-text parity failed.** Skippy main and PR text is +exact throughout. Vanilla differs on prompt 2 in both modes, and prompt 5 at +plain C2; plain prompt 2 also varies within vanilla C2 repeats. These are +fixed-budget throughput observations, not a byte-identical vanilla speedup +claim or proof of equivalent model quality. No prompts were removed. The +three-way result does not replace the confirmed three-process Skippy table. + +The initial plain job `job_4b086x0mh18p2qg` (run `run_caphfdqssssaw4j`) +failed its strict cross-engine parity gate after collecting the whole plain +workload. Its timing integrity and Skippy parity were independently re-audited +post hoc; the failed gate remains recorded. The subsequent DFlash job +`job_9mrpbw1jg7nt0mx` (run `run_2f0fe28qzdyx2qb`) predeclared fixed-budget +comparison with strict Skippy parity and explicit vanilla drift reporting; +it completed, and its raw archive passed a second local audit. Each mode +accepted 432 requests including warmup; plain rejected 44 blocks and DFlash 21. + +An untimed probability diagnostic (`job_3s9va64cxdk99p6`, run +`run_3yt8y8aa1v6hqd5`) found plain prompt 2 C1 first diverges at output token +66: vanilla selects “ Components” over “ Concepts” with log-probability margin +0.0903, while PR reverses that ranking with margin 0.0318. Both prompts matched +at C2 in all three diagnostic repeats. The cause remains unproven; do not +attribute this to a one-ULP difference. The upstream server documentation also +warns that batch sizes can change output, but that does not itself establish +quality equivalence here. + +### Attribution + +A separately authorized M1 Ultra ablation compared the same retained runtime +with `SKIPPY_RS_SEQ=2` versus `0` (`job_r1a6e5jzn1kvhd9`, run +`run_153re0gjqtjqykr`). Disabling snapshots improved plain C1 from 66.04 to +68.89 TPS (+4.30%) and C2 aggregate from 97.52 to 102.41 TPS (+5.02%), with +exact text. That different-hardware result is not pooled into the M3 table. + +A second same-CLI M1 ablation changes only backend sampler row capacity from +legacy zero to one, with rollback depth zero in both arms (`job_k53yk8s75d55f2f`, +run `run_s70jtw5rzwq4bbw`). C1 measured 68.72 → 68.90 TPS (+0.27%); C2 measured +102.02 → 102.33 TPS (+0.31%). All 288 accepted responses match exactly; +37 whole blocks were rejected, and downloaded raw evidence passed a second +local audit. This single campaign does not demonstrate a material gain from +sampler row capacity. Neither ablation explains the full main-to-PR improvement; +further attribution remains necessary. + +A same-CLI M1 convolution-launch ablation changes only channels per threadgroup +from one to 32, retaining the same shader math and all other native settings +(`job_ekbcxzxfy3bz7e6`, run `run_79ex575fm5mqtd6`). C1 measured 68.21 → 68.79 +TPS (+0.86%); C2 aggregate measured 101.28 → 101.95 TPS (+0.67%). The latter's +three cycle changes were +1.27%, +1.06%, and -0.32%. All 288 accepted requests +have exact text, 35 blocks were rejected, and the raw archive passed a second +local audit. This is another small isolated contribution, not an explanation +of the full main-to-PR gain. + +Two API tests remain unqualified because the bundled split-certification roster +was recorded against ABI 0.1.80 and its original recipe. The measured candidate +used ABI 0.1.85. The integration against current Skippy main uses ABI 0.1.88. +Split and family certification require qualification of the exact recipe. + +Cached Metal dispatch prototypes, including serialized/deduplicated signatures +and in-place snapshots, remain outside this PR. Their correctness/profile +results do not contribute to any TPS number above. + +## Unpromoted cached-encoding pilot + +A separately built V3 cache runtime (`8b0e6bc6a60ae587e9beb75123b84c4f08bd9d2a`, +native tree `03ebbc56f70519b50ec66db1234a96f4a38791c9`) uses the same CLI and +runtime in both arms, changing only the cache switch. One M3 plain campaign +measured C1 99.27 → 101.95 TPS (+2.70%; cycles +2.33%, +2.88%, +2.89%) and +C2 aggregate 162.33 → 163.39 TPS (+0.65%; cycles +0.64%, +0.70%, +0.61%). +All 288 accepted responses match exactly; 10 blocks were rejected, and the +downloaded raw archive passed the independent audit again locally. + +These are preliminary, single-campaign observations, excluded from this PR's +product code and confirmed headline. Job `job_n8hpce6fspce5my`, run +`run_p3kv0ya7ys4enht`, later failed its DFlash exact-text gate. That DFlash arm +also inherited a zero-rollback override from the plain-only ablation harness, +forcing host checkpoints instead of production speculative rollback. Both +cache-off and cache-on C2 produced the same two variants of prompt 2, with the +same counts. Those data do not qualify production DFlash behavior. A new +DFlash campaign restored the production defaults; no gate was waived. + +That corrected production DFlash pilot (`job_t2yjbkrj1fthjzs`, run +`run_174vdj1s14bh7cn`) passed exact text for all 288 accepted requests, rejected +six blocks, and passed the downloaded raw-data audit. C1 measured 165.20 → +165.33 TPS (+0.07%); C2 aggregate measured 206.65 → 206.17 TPS (-0.23%). +These results are effectively flat. The rollback override was unset in both +arms. Fresh-process V4 confirmation remains outstanding. + +The packaged cache runtime additionally passed actual Metal unit/invalidation +checks on a Dan-lab M4 Mac mini (`job_9trvfmjfdj54tf9`, run +`run_vv2132wyp91m1d9`): 54,016 exact values including retired-source cases, +with all loaded ggml paths from its own bundle and a local artifact re-audit. +This is hardware correctness evidence, not M4 serving throughput. + +## Rejected paired-projection experiment + +A private Q8_0 candidate combines two independent projections sharing one input +into one Metal dispatch. It retains their separate weight/output buffers and +the existing per-row dot-product body. Local M5 Max screens using original +weight bytes reduced GPU time by 28–31% for a small shared-expert pair and +4–5% for the tested query/key pair across three ABBA cycles. Outputs were byte +exact. Batch, distinct-input and overlapping-output cases declined fusion. +Four full-model state exports also matched exactly with flash attention auto, +context 8192, and the candidate pipeline observed. These local diagnostics do +not establish packaged serving performance. + +The subsequent source-pinned M5 Pro 48 GB pilot (`job_66qwv9eg4ebffmn`, run +`run_whb7ey3jx2r11ws`) used one loaded engine and switched the fusion flag +between matched requests. The same compiled runtime served both arms. The +direct native iteration API included session creation, prefill, 128 sampled +tokens and cleanup; HTTP and frontend scheduling were absent. Three warm and +three measured cycles covered all eight fixed prompts in within-prompt ABBA. + +Native C1 throughput measured **66.40 → 65.94 TPS (-0.70%)**, with measured +cycle changes -0.25%, -0.91% and -0.94%. All tokens matched, 192 full-length +requests were accepted including warmup, and two whole blocks were rejected. +The downloaded requests, block selection, load/thermal windows, library paths +and recomputed rates passed an independent local audit. This is one process +campaign on a separate hardware/compiler cohort, not a serving-table update. +The candidate remains excluded from this PR: the kernel win did not produce a +native decode gain. Pins and audit hashes are in +[`metal-decode-q8-pair-rejected.json`](evidence/metal-decode-q8-pair-rejected.json). + +## Review follow-up: scheduler and rollback movement + +The follow-up to Jared's review starts from PR head `1ebce5e`. It removes +empty verification waits, interrupts direct gathering for ready speculative work, +uses the configured batch policy's decode wait capped at 300 microseconds for +shared gathering, and types draft operations independently of diagnostic labels. +Native rollback relocation now skips identity rows and uses backend-to-backend +copies for non-overlapping groups. Aliased groups still gather before scattering; +`native.recurrent_rollback_copy` records their `host_staging_bytes` and duration. +Synthetic CPU/Metal copy checks and peer rollback tests establish correctness, +not serving TPS. No replacement headline is established by these changes alone. + +### Metal qualification boundaries + +The retained defaults are deliberately distinct from capability eligibility. +`GGML_METAL_ROUTED_U32=1` / `GGML_METAL_ROUTED_U32_R4=1` can now exercise safe, +bounded geometry on M3 Ultra; the normal defaults are unchanged. Host greedy +can be tested on any shared-buffer device with `GGML_METAL_HOST_GREEDY=1`; +private buffers remain ineligible. `GGML_METAL_ROUTED_ROWS=1` tests the narrow +Q4_1 rule on Apple families 7–9 and the general rule on Apple10 and newer; +`0` disables the diagnostic row tuning. Normal row defaults stay unchanged. + +The retained evidence does not establish that M4 u32 or M5 Max R4 are slower; +those defaults remain unpromoted pending qualification. This report contains no +retained cross-chip host-greedy comparison beyond the M5 Max qualification, nor +an attributable broad Q4_K row-rule comparison on M1 Ultra/M4. The M3 Ultra +historical tables did not exercise the old chip-gated host-greedy/routed paths. +Do not infer those patches' gains from the combined tables. Broader defaults +require new per-device numerical and matched serving results. + +## Matched review-fix pilot against current main + +The source-bound [measurement job](https://pilot.jianyang.cloud/jobs/job_gf030kdnqjk30wq) +compares candidate `ab0dd87` with main `5008074` and separately with pre-fix +PR #9 `1ebce5e`. All three use the same upstream pin `8954f194`, target/draft +bytes and serving settings. The later follow-ups add test wiring and backport +main's deterministic telemetry test; these rates remain attributed to `ab0dd87`. + +| Serving mode | Main `5008074` TPS | Candidate `ab0dd87` TPS | Change | +| --- | ---: | ---: | ---: | +| Plain, concurrency 1 | 94.84 | 99.56 | +4.97% | +| Plain, concurrency 2, aggregate | 150.46 | 161.93 | +7.62% | +| DFlash, concurrency 1 | 162.63 | 164.79 | +1.33% | +| DFlash, concurrency 2, aggregate | 157.72 | 207.70 | +31.69% | + +The separate before/after review-fix pilot measured concurrent DFlash at +205.70 → 208.07 TPS (+1.15%); other modes changed by +0.38% to +0.53%. +Do not pool the two comparisons: their requests and process lifetimes are separate. +The large main comparison reflects all PR #9 work; it is not a gain attributable +to these review fixes alone or evidence of a hundreds-of-milliseconds copy penalty. + +Each mode/comparison has one fresh-process campaign, three warm cycles and three +measured cycles at concurrency one and two. All 288 accepted requests per +comparison obeyed the 128-token budget, had zero prompt-cache hits and matched +response hashes. Complete ABBA blocks with interference were rejected. Rates +include HTTP/prefill time. Four independent audits were rerun locally against +downloaded raw evidence and match the remote audits. This is a provisional pilot: +`promotion_allowed` remains false until further fresh-process confirmation. + +The [raw-evidence job](https://pilot.jianyang.cloud/jobs/job_0ec18ww6y3e96qe) +retains four flat archives named `{main,previous}-vs-candidate-{plain,dflash}.tar.gz` +and `evidence-manifest.json`. Each archive contains responses, batch timings, +commands, provenance, loaded-library paths and load/thermal observations. Archive +SHA-256 hashes, exact source/CLI identities and independent rates are recorded in +[evidence/pr9-review-fixes-m3.json](evidence/pr9-review-fixes-m3.json). + +The source-pinned [M3 Ultra native diagnostic job](https://pilot.jianyang.cloud/jobs/job_947w4gdfrhnad3x) +also passed CPU/Metal copy contracts, 40 routed native cases (80 paired outputs, +160 FP64 oracle checks, both R8 and R4 pipeline execution), and GPU peer rollback +modes 0/1/2/7. It tests the opt-in row diagnostic and bounded u32 eligibility; +it does not promote broader performance defaults. Log hashes are in the same +evidence manifest. + +Local validation of the follow-up passed 1,374 serving tests (32 opt-in tests +ignored), documentation tests and warning-denying all-target Clippy. The combined +native replay/resume recorded 335 distinct passes; `skippy_graph_contract_glm4-expansion` +timed out and `skippy_resident_checkpoint_gpu_long` remained an opt-in skip. This +is not a clean unrestricted full-replay pass. diff --git a/docs/design/METAL_DECODE_OPTIMIZATION.md b/docs/design/METAL_DECODE_OPTIMIZATION.md new file mode 100644 index 00000000..aff04248 --- /dev/null +++ b/docs/design/METAL_DECODE_OPTIMIZATION.md @@ -0,0 +1,178 @@ +# Metal decode optimization work + +The November 17, 2026 M3 Ultra measurements cover the original port across three process campaigns. The vanilla comparison uses a fixed token budget and records cross-engine text differences. See [the benchmark evidence](METAL_DECODE_BENCHMARKS.md). + +## Baseline migration + +The standalone extraction starts at `fbc3349cd406786e43f6579590c9a12b0cd49c05` +and pins llama.cpp `8954f194837d2ec4d5f67f20c81b84abe63883ba`. +It predates the shared draft/verification scheduler and native decode work +qualified in the Mesh-hosted Skippy tree. This branch ports those changes while +preserving the extraction's newer upstream changes and standalone ownership. + +The earlier placement/batching work was already merged into Mesh's `gi` branch +in PR #33. It was absent from the measured standalone extraction baseline, +whose core native patch queue ends at 0016 rather than PR #33's 0035. Therefore +the standalone headline includes this catch-up as well as subsequent changes; +it does not measure our incremental contribution over Jared's work. + +The port includes shared speculative forwards, concurrent sampling, resident +prefix handling, KV allocation and row attention improvements, gated activation +fusion, routed vector reuse, decode convolution changes, and tracing. The affine +conversion preserves integer codes and rounds affine coefficients to f16; that +conversion utility is not used in these unchanged-GGUF serving measurements. +Model tuning is outside scope. + +Compatibility resolutions retain upstream per-layer KV strides, the standalone +context-capacity implementation, prompt shape statistics, and current sampling +state. Native API bindings are regenerated from the prepared source at ABI +0.1.85 rather than copied from the older upstream pin. + +Skippy PR #71 subsequently landed the placement, batching, and resident-cache +baseline on standalone main. PR #9 now adds the remaining shared verification +and draft execution paths and nine native decode patches to that baseline, with +native ABI 0.1.88. The measurements below refer to the historical snapshots. + +## Historical validation and remaining gates + +Local evidence is under `target/migration-audit/`; those artifacts are ignored +and are not a published benchmark report. + +- All 141 ordered native patches apply directly, with every intermediate tree + matching the qualified native history. Two imported patches were regenerated + against their actual parents after a fresh M3 checkout exposed hidden + three-way Git-object dependencies. The resulting native source is unchanged. +- Rust all-target warning-denying Clippy passed again after the final + documentation and test-assertion edits. +- Native routed policy and numerical checks passed, including the R4/R8 paths. +- The focused native CTest run passed all 51 fixture-backed tests, with no skips. +- The full-model control/candidate probe produced identical exported state in + four comparisons covering rollback and shared recurrent-lane repair. +- The wider native family graph-contract run passed all 198 tests with no + skips. The serial Rust + workspace run excluding `skippy-api` passed, including integration and + documentation tests. The API run passed 131 tests with its two unresolved + split-certification tests explicitly filtered out; that is not a full pass. +- The split roster remains bound to its prior native recipe. Do not relabel + those certificates as newly qualified to make tests pass. +- Regenerated API documentation and the binding freshness/mutation self-check + passed. The standalone release CLI builds and reads the packaged native + runtime successfully. +- The C++ facade CTest run completed: 248 passed and one skipped because this + standard library lacks `std::start_lifetime_as_array`. The skip is not native + hardware qualification. +- The separate Rust facade workspace passed formatting, all-target + warning-denying Clippy, unit/integration tests, and documentation tests. Its + optional real embedding/reranking fixtures are not decode qualification. +- Two unchanged process-supervision projection tests failed in the parallel + workspace run and passed both in the focused serial rerun and the serial + workspace run. Do not report an unconditional parallel workspace pass. +- A pristine standalone baseline checkout and its runtime/release CLI have been + built separately. The confirmed Skippy serving results and qualified vanilla + observations are recorded in the benchmark report. +- An untimed serving smoke loaded the original 35B GGUF, returned the expected + one-word response, and completed two concurrent 64-token requests with prompt + caching disabled. The owned server then shut down cleanly. Other validation + was running, so request elapsed times are not benchmark evidence. + +Historical Mesh-hosted engine-only results were +8.5% at concurrency one and ++45.3% aggregate throughput at concurrency two against Jared's PR baseline. +They are workload-specific historical results, not measurements of this +standalone port or a claim of parity with another engine. + +The separate M1 parallel-encoding experiment failed its predeclared performance +gate: plain decode improved, but DFlash concurrency-two pooled throughput was +-0.097%, with mixed cycles. That prototype is not retained in this port. + +## Subsequent experiments + +After qualifying this baseline, measure independently implemented cached Metal +encoding plans, fewer host round trips across draft/verify/accept/commit, packed +4-bit TensorOps using unchanged model values, and shared-plus-routed expert +fusion. Static analysis and public research identify candidate mechanisms; +neither establishes their isolated speedup. Keep each experiment independently +switchable and compare matched model bytes, hardware, prompt/context, output +length, concurrency, and acceptance behavior. + +### Cached encoding plan constraints + +The current Metal encoder selects pipelines, binds buffers and inline arguments, +sets threadgroup memory, inserts barriers, and dispatches each graph on the CPU. +A replay experiment should record that command stream and replay ordinary Metal +encoder calls; changing command-buffer ordering is a separate experiment. + +A tensor-shape-only key is insufficient. The key must cover operation parameters, +strides, source topology and aliasing, output flags, buffer usage and actual Metal +buffer identities/offsets, fusion configuration, and command-buffer boundaries. +Recorded buffers and pipeline objects need owned lifetimes with bounded eviction. +Debug capture and fusion statistics should use normal encoding. + +Row-list attention currently examines host-visible row-list values to choose the +gather-free pipeline. Matching allocation and tensor geometry does not guarantee +that choice remains valid. Either recompute and key the classification on replay, +or invalidate the plan when the relevant values change. Never cache a dense-row +decision across a general-row layout merely because the list has the same shape. + +Qualification must exercise buffer replacement, changed strides and operation +parameters, aliasing, row-layout transitions, graph reuse, and speculative +accept/reject/rollback. Keep plan creation and cache hits observable separately +from warmed pipeline compilation and GPU execution time. + +### Isolated dispatch-plan prototype + +The current default-off prototype remains outside this PR. Its native tree is +`03ebbc56f70519b50ec66db1234a96f4a38791c9`, packaged from standalone snapshot +`8b0e6bc6a60ae587e9beb75123b84c4f08bd9d2a`. It records ordinary Metal encoder +operations and compares live graph/tensor metadata against an in-place snapshot +before replay. It still resolves current Metal buffer identities, offsets and +usage and recomputes row-list density on every hit. A first pass validates node +and source identities before dereferencing saved source metadata, including +when old leaf metadata has been unmapped. Storage is bounded, resources remain +owned through command-buffer completion, and capture/debug paths encode normally. + +The M3 build passed 49,152 exact ordinary-op values under invalidation cases, +3,072 exact row-list values across dense/general transitions, and 1,792 exact +values with retired source metadata, changed buffer usage and ignored debug +names. The tests require actual hits and misses. These checks establish +correctness coverage, not a serving speedup. + +On the local M5 model-state probe, in-place snapshots reduce thread CPU time +spent validating the key by 84.43% versus the deduplicated serialized-key +prototype, across ABBA runs with 2,718 calls and four exact state exports per +process. This is time in one CPU component, not end-to-end TPS. The earlier +serialized-key deduplication reduced final signature storage by 45.7%; that is +also not a serving-throughput claim. + +The separately built M3 runtime uses the same compiler as the retained serving +producer. Its serving comparison uses the same CLI and native runtime +in both arms, with only the cache switch changed, original target/draft hashes, +plain and DFlash modes, C1/C2, fixed output budgets, within-prompt ABBA, exact +response hashes, whole-block load/thermal exclusions, and independent raw-data +audits. A measured benefit without correctness or concurrency regressions is +required before promotion into the core queue. + +The first M3 plain pilot measured +2.70% C1 and +0.65% C2 with exact text and +a local raw-data re-audit. The corrected production DFlash pilot passed with +exact text and was effectively flat (+0.07% C1, -0.23% C2). These single-process +observations do not promote the prototype. See the benchmark report for the +failed DFlash gate and corrected rollback setup. + +The subsequent V4 prototype additionally keys routed-policy overrides and +bypasses replay while an attention-tuning override is active. Its M1 build +passed 57,856 exact values, including an actual alternate attention pipeline +and configuration invalidations. Fresh-process serving confirmation remains +unfinished, and V4 remains outside this PR. + +### Paired dense projections + +An untimed, class-split M5 Pro GPU diagnostic placed roughly 80% of captured +device duration in matrix multiplies: 55% in dense-only groups, 18% in +routed-only groups and 7.5% in mixed groups. Splitting changes scheduling and +fusion, so these shares guide experiments rather than describe normal serving +wall time or explain the main-to-PR gain. + +A private paired-Q8 projection candidate preserved weight bytes and per-row +arithmetic. It passed local kernel/fallback and full-model state checks, but a +source-pinned native C1 pilot measured -0.70% throughput despite the isolated +kernel benefit. The code is excluded. See the benchmark report and rejected +experiment evidence; kernel latency alone is insufficient for promotion. diff --git a/docs/design/evidence/metal-decode-followup-pilots.json b/docs/design/evidence/metal-decode-followup-pilots.json new file mode 100644 index 00000000..ece42523 --- /dev/null +++ b/docs/design/evidence/metal-decode-followup-pilots.json @@ -0,0 +1,199 @@ +{ + "scope": "Unpromoted cache pilots and isolated convolution attribution; no combined headline or completed fresh-process cache confirmation", + "audits": { + "plain_cache": { + "sha256": "63ee8fb663cd677d027d027d2fd668ad45e6cc4b3b1148a8fc1c7ad2a7201be5", + "result": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 10, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 61.89362099976279, + "tok_s": 99.26709571610857 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 60.26691000000574, + "tok_s": 101.94649103462274 + } + ], + "percent": 2.699177707562739, + "cycle_percent": [ + 2.3255374312258548, + 2.8806697282916183, + 2.8931661371142114 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 37.847813999745995, + "tok_s": 162.33434248121262 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.6024070000276, + "tok_s": 163.39379550876865 + } + ], + "percent": 0.6526364115951866, + "cycle_percent": [ + 0.6399634619995709, + 0.7034544790244901, + 0.6144758382015558 + ], + "all_text_exact": true + } + ] + } + }, + "m4_cache": { + "sha256": "c59119ec36a03e44c810e8d6fd5f2fd2e2b434f3c47e038fd7442e1671fd2b7c", + "result": { + "status": "PASS_LOCAL_M4_ARTIFACT_AUDIT", + "node": "macmini-764jw9", + "run": "run_vv2132wyp91m1d9", + "exact_values": 54016, + "loaded_libraries": 5, + "log_sha256": "c64361aadf0b5ab9123f843579e529beba7e9b138871bddb6aca2e60f21e4dea", + "scope": "No serving or model-performance claim" + } + }, + "convolution": { + "sha256": "718169f7d4624626d5d0b0734e8ad96900e3988aa6237ac02bb9646459a68829", + "result": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 35, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 90.07924199919216, + "tok_s": 68.20661301807024 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 89.31418099999428, + "tok_s": 68.79086760030184 + } + ], + "percent": 0.8565952132483234, + "cycle_percent": [ + 0.2932773213457418, + 1.1687358834778339, + 1.1071130843452126 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 60.66625300026499, + "tok_s": 101.27541583906894 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 60.263106000144035, + "tok_s": 101.95292622297488 + } + ], + "percent": 0.6689781308649723, + "cycle_percent": [ + 1.2715795593551515, + 1.0635018380220407, + -0.319068961014779 + ], + "all_text_exact": true + } + ] + } + }, + "production_dflash_cache": { + "job": "job_t2yjbkrj1fthjzs", + "run": "run_174vdj1s14bh7cn", + "sha256": "958042733b29acf4cf0095bf7a686738e50c46cb148f2be797913d8fe4290c71", + "result": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 6, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 37.19015800044872, + "tok_s": 165.2049985893007 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.162603000877425, + "tok_s": 165.32749333664646 + } + ], + "percent": 0.07414711927107298, + "cycle_percent": [ + 0.20850642632082028, + 0.1968110758600261, + -0.183617813577297 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 29.731798999477178, + "tok_s": 206.6474349603951 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 29.800968999043107, + "tok_s": 206.1677927384603 + } + ], + "percent": -0.2321065451534543, + "cycle_percent": [ + -0.35791206749599125, + 0.1756335748524407, + -0.5144040563941688 + ], + "all_text_exact": true + } + ] + } + } + } +} diff --git a/docs/design/evidence/metal-decode-m3-confirmed.json b/docs/design/evidence/metal-decode-m3-confirmed.json new file mode 100644 index 00000000..ca269d91 --- /dev/null +++ b/docs/design/evidence/metal-decode-m3-confirmed.json @@ -0,0 +1,113 @@ +{ + "scope": "Matched original models on M3 Ultra; three fresh-process campaigns, each with three measured cycles and exact text, artifacts locally re-audited.", + "comparisons": { + "plain": [ + { + "concurrency": 1, + "process_campaigns": 3, + "arms": [ + { + "arm": "old", + "output_tokens": 18432, + "elapsed_s": 513.3963660004083, + "tok_s": 35.90208505680257 + }, + { + "arm": "new", + "output_tokens": 18432, + "elapsed_s": 186.2137089986354, + "tok_s": 98.98304533601804 + } + ], + "pooled_percent": 175.7027765362702, + "process_percent": [ + 177.08642602147387, + 175.97061472205073, + 174.0618314449079 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "process_campaigns": 3, + "arms": [ + { + "arm": "old", + "output_tokens": 18432, + "elapsed_s": 293.94392499886453, + "tok_s": 62.705837516700505 + }, + { + "arm": "new", + "output_tokens": 18432, + "elapsed_s": 113.65917499898933, + "tok_s": 162.16904618711072 + } + ], + "pooled_percent": 158.61873887565903, + "process_percent": [ + 159.1770134583843, + 157.7523987313445, + 158.9267281519163 + ], + "all_text_exact": true + } + ], + "dflash": [ + { + "concurrency": 1, + "process_campaigns": 3, + "arms": [ + { + "arm": "old", + "output_tokens": 18432, + "elapsed_s": 112.63505700184032, + "tok_s": 163.6435448307967 + }, + { + "arm": "new", + "output_tokens": 18432, + "elapsed_s": 111.82934999954887, + "tok_s": 164.82256223499786 + } + ], + "pooled_percent": 0.7204790176234654, + "process_percent": [ + 1.0956604869827302, + 0.5208770005601382, + 0.5472139729673975 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "process_campaigns": 3, + "arms": [ + { + "arm": "old", + "output_tokens": 18432, + "elapsed_s": 118.70968200080097, + "tok_s": 155.26955922496393 + }, + { + "arm": "new", + "output_tokens": 18432, + "elapsed_s": 89.41049499786459, + "tok_s": 206.150295895803 + } + ], + "pooled_percent": 32.769292915374336, + "process_percent": [ + 32.33871954776011, + 33.09692781606921, + 32.87261665997823 + ], + "all_text_exact": true + } + ] + }, + "vanilla_pending": true, + "cache_prototypes_excluded": true, + "source_main": "fbc3349cd406786e43f6579590c9a12b0cd49c05", + "source_pr_product": "ac040471f6104ea8fdfd6beafb345a6d3163ef92" +} diff --git a/docs/design/evidence/metal-decode-q8-pair-rejected.json b/docs/design/evidence/metal-decode-q8-pair-rejected.json new file mode 100644 index 00000000..9bb2e480 --- /dev/null +++ b/docs/design/evidence/metal-decode-q8-pair-rejected.json @@ -0,0 +1,219 @@ +{ + "status": "REJECTED_NO_NATIVE_DECODE_GAIN", + "shipping": false, + "native_tree": "1993e8e1acf36403a0793ccf6a59e194df3726bb", + "source_overlay": "e1a77a93d61fd7fca7ef388f38703843ca7499f4", + "model_sha256": "707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450", + "build": { + "job": "job_7ft4nqzs2qz0d8w", + "run": "run_a8ks7g29e7b0dap", + "compiler_apple_build": 21000101 + }, + "native_pilot": { + "job": "job_66qwv9eg4ebffmn", + "run": "run_whb7ey3jx2r11ws", + "hardware": "Apple M5 Pro, 48 GB", + "warm_cycles": 3, + "measured_cycles": 3, + "audit": { + "status": "PASS_INDEPENDENT_NATIVE_PILOT_AUDIT", + "scope": "Direct native iteration API including session creation, prefill, 128 sampled output tokens, and session cleanup; no HTTP scheduler. One loaded engine, fusion flag switched between requests. Not pooled with serving TPS.", + "single_process": true, + "promotion_allowed": false, + "arms": [ + { + "arm": 0, + "output_tokens": 6144, + "elapsed_s": 92.525442, + "tok_s": 66.40335746788435 + }, + { + "arm": 1, + "output_tokens": 6144, + "elapsed_s": 93.178344, + "tok_s": 65.93806818459878 + } + ], + "percent": -0.7007014419573632, + "cycle_percent": [ + -0.2527628123523362, + -0.9120764881837218, + -0.9387571417630136 + ], + "all_tokens_exact": true, + "accepted_requests": 192, + "rejected_blocks": 2, + "raw_sha256": { + "summary.json": "d4d1b9fc47ad6266a58595a315af25fe113c1effa170762872a4712e120d8ca0", + "requests.jsonl": "ca9b1ba4d581b1abacf1ca6c09850580537894cdb5093de6b379619a750a3de2", + "blocks.json": "ddc8b1cad27d1860f7dde38cdcc3d5fe00988edf23d5b3610118b9d749811a70", + "load-thermal.json": "9f97dfa8074f9e10157f0e98b508ace372f3c475d096e26dfe1571f07de7a43b", + "native-libraries.txt": "413f5b9cab4c6cca9be23ee1701bd280ac8bf306b0fb20b3ee05f84a8d321be1" + } + } + }, + "local_kernel_screen": { + "hardware": "Apple M5 Max", + "scope": "Local M5 Max original-weight two-projection GPU screen, not serving TPS", + "comparisons": [ + { + "case": "shared_expert", + "cycles": [ + { + "baseline_gpu_us": 32.0283975, + "pair_gpu_us": 22.238435000000003, + "latency_percent": -30.566507425168542 + }, + { + "baseline_gpu_us": 32.307494999999996, + "pair_gpu_us": 23.136589999999998, + "latency_percent": -28.386307883046946 + }, + { + "baseline_gpu_us": 32.16199, + "pair_gpu_us": 22.5855975, + "latency_percent": -29.77549741169624 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0, + 200 + ] + }, + { + "case": "query_key", + "cycles": [ + { + "baseline_gpu_us": 93.14155249999999, + "pair_gpu_us": 89.039865, + "latency_percent": -4.403713906314777 + }, + { + "baseline_gpu_us": 93.0754075, + "pair_gpu_us": 89.3183375, + "latency_percent": -4.036587215586462 + }, + { + "baseline_gpu_us": 93.0943025, + "pair_gpu_us": 89.1906425, + "latency_percent": -4.19323191126546 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0, + 200 + ] + }, + { + "case": "qkv_gate", + "cycles": [ + { + "baseline_gpu_us": 122.061365, + "pair_gpu_us": 121.03803500000001, + "latency_percent": -0.8383733870254373 + }, + { + "baseline_gpu_us": 122.20867, + "pair_gpu_us": 120.51271750000001, + "latency_percent": -1.387751376395796 + }, + { + "baseline_gpu_us": 121.97595749999999, + "pair_gpu_us": 120.4923325, + "latency_percent": -1.2163257664937643 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0, + 200 + ] + }, + { + "case": "batch_fallback", + "cycles": [ + { + "baseline_gpu_us": 38.2915675, + "pair_gpu_us": 37.977177499999996, + "latency_percent": -0.8210423874655981 + }, + { + "baseline_gpu_us": 38.024195, + "pair_gpu_us": 37.93999, + "latency_percent": -0.22145110501352594 + }, + { + "baseline_gpu_us": 38.211865, + "pair_gpu_us": 37.9622875, + "latency_percent": -0.6531413737591696 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0 + ] + }, + { + "case": "input_fallback", + "cycles": [ + { + "baseline_gpu_us": 32.0164475, + "pair_gpu_us": 31.9767675, + "latency_percent": -0.12393629867897271 + }, + { + "baseline_gpu_us": 32.453835, + "pair_gpu_us": 32.01875, + "latency_percent": -1.340627386563098 + }, + { + "baseline_gpu_us": 32.026585, + "pair_gpu_us": 32.047920000000005, + "latency_percent": 0.06661653123494204 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0 + ] + }, + { + "case": "output_alias", + "cycles": [ + { + "baseline_gpu_us": 31.747704999999996, + "pair_gpu_us": 31.3800125, + "latency_percent": -1.1581703307372848 + }, + { + "baseline_gpu_us": 31.49678, + "pair_gpu_us": 31.487277499999998, + "latency_percent": -0.030169750685637986 + }, + { + "baseline_gpu_us": 31.549575, + "pair_gpu_us": 31.4170675, + "latency_percent": -0.41999773372540794 + } + ], + "all_outputs_exact": true, + "fused_counts": [ + 0 + ] + } + ] + }, + "local_state_diagnostic": { + "status": "PASS_FULL_MODEL_FA_AUTO_PAIR_STATE_DIAGNOSTIC", + "scope": "Local M5 Max retained ABI .85 libllama plus private pair ggml libraries; flash attention auto, context8192, batch2048, microbatch512, threads4; numerical/state diagnostic, not packaged serving TPS", + "state_blocks_exact": 4, + "pair_pipeline_compiled": true, + "control_log_sha256": "a11a3c6ffd80309976dfb4ad56e4b3126674ff9fd6c17c21ac863476aeed1561", + "candidate_log_sha256": "a156267e003a3dd9d72a59edff725fe28e54774316c8b6dfb8391e7b5989acff", + "state_bytes": 264770512, + "state_sha256": "dc6ec0977fdeded86cdb0c6163ef4a71a4c723b82cd03eaaeeeaa669170f2f79" + }, + "disposition": "Do not promote. Byte-exact kernel and model-state results did not translate into a native C1 throughput benefit. This pilot is not HTTP serving TPS or attribution of the confirmed main-to-PR gain." +} diff --git a/docs/design/evidence/metal-decode-three-way.json b/docs/design/evidence/metal-decode-three-way.json new file mode 100644 index 00000000..b8a1e564 --- /dev/null +++ b/docs/design/evidence/metal-decode-three-way.json @@ -0,0 +1,291 @@ +{ + "scope": "Three-way fixed-budget observations; vanilla exact-text parity failed. Sampler row-cap single-campaign attribution.", + "audits": { + "dflash": { + "sha256": "75f7e498c6bb34b375934c0c4a0376081450a4c45d09865492cdd645b9ace032", + "result": { + "vanilla_text_drift": [ + { + "concurrency": 1, + "prompt": 2, + "hashes": { + "vanilla": [ + "a62ba2f06703af695e11e2198b293e3fc9f0211c80845461e25a43270a997e53" + ], + "main": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ], + "pr": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ] + } + }, + { + "concurrency": 2, + "prompt": 2, + "hashes": { + "vanilla": [ + "a62ba2f06703af695e11e2198b293e3fc9f0211c80845461e25a43270a997e53" + ], + "main": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ], + "pr": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ] + } + } + ], + "strict_skippy_main_pr_parity": true, + "status": "PASS_TIMING_INTEGRITY_OUTPUT_PARITY_FAILED", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 432, + "rejected_blocks": 21, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "vanilla", + "output_tokens": 6144, + "elapsed_s": 36.31189800007269, + "tok_s": 169.20073965805096 + }, + { + "arm": "main", + "output_tokens": 6144, + "elapsed_s": 37.44534500106238, + "tok_s": 164.079139872411 + }, + { + "arm": "pr", + "output_tokens": 6144, + "elapsed_s": 37.111954000080004, + "tok_s": 165.55312608942 + } + ], + "percent": 0.8983385810988453, + "cycle_percent": [ + 1.2835135516989338, + 0.34867149058255276, + 1.0687850104814434 + ], + "all_text_exact": false + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "vanilla", + "output_tokens": 6144, + "elapsed_s": 31.18896699976176, + "tok_s": 196.9927378501164 + }, + { + "arm": "main", + "output_tokens": 6144, + "elapsed_s": 39.68504100013524, + "tok_s": 154.8190412598808 + }, + { + "arm": "pr", + "output_tokens": 6144, + "elapsed_s": 29.93535799975507, + "tok_s": 205.2422423025731 + } + ], + "percent": 32.56912110575041, + "cycle_percent": [ + 32.83100374634511, + 32.84949192477335, + 32.02952945315805 + ], + "all_text_exact": false + } + ] + } + }, + "plain": { + "sha256": "2788752cc5ca67b9dcf8aa6afb370500b293cb5688d260a7820981b1a63f3ff9", + "result": { + "vanilla_text_drift": [ + { + "concurrency": 1, + "prompt": 2, + "hashes": { + "vanilla": [ + "a62ba2f06703af695e11e2198b293e3fc9f0211c80845461e25a43270a997e53" + ], + "main": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ], + "pr": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ] + } + }, + { + "concurrency": 2, + "prompt": 2, + "hashes": { + "vanilla": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121", + "a62ba2f06703af695e11e2198b293e3fc9f0211c80845461e25a43270a997e53" + ], + "main": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ], + "pr": [ + "477cfce69078e964083712f5bf676456e6d1ba3f43bb0bb7829db0011c9a2121" + ] + } + }, + { + "concurrency": 2, + "prompt": 5, + "hashes": { + "vanilla": [ + "1f163ae28dc65606a7013bca4ea87c3f53ef7d5e0fa0b0a008482ae47c3ceafd" + ], + "main": [ + "3d79f83311c8eda06f4733418e6543deac1a02e1001d51f7b43610a6f4c3ea15" + ], + "pr": [ + "3d79f83311c8eda06f4733418e6543deac1a02e1001d51f7b43610a6f4c3ea15" + ] + } + } + ], + "strict_skippy_main_pr_parity": true, + "status": "PASS_TIMING_INTEGRITY_OUTPUT_PARITY_FAILED", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 432, + "rejected_blocks": 44, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "vanilla", + "output_tokens": 6144, + "elapsed_s": 63.63849600101821, + "tok_s": 96.54533633072812 + }, + { + "arm": "main", + "output_tokens": 6144, + "elapsed_s": 169.9622259994503, + "tok_s": 36.14920882490602 + }, + { + "arm": "pr", + "output_tokens": 6144, + "elapsed_s": 62.10303400084376, + "tok_s": 98.93236455913771 + } + ], + "percent": 173.67781419043249, + "cycle_percent": [ + 172.34695622183133, + 174.9356642998235, + 173.75184859857575 + ], + "all_text_exact": false + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "vanilla", + "output_tokens": 6144, + "elapsed_s": 41.292364000109956, + "tok_s": 148.79264359830887 + }, + { + "arm": "main", + "output_tokens": 6144, + "elapsed_s": 97.63747799955308, + "tok_s": 62.92665609437518 + }, + { + "arm": "pr", + "output_tokens": 6144, + "elapsed_s": 38.010523000964895, + "tok_s": 161.63944915580444 + } + ], + "percent": 156.86959897151263, + "cycle_percent": [ + 158.6966276603636, + 155.47745826974148, + 156.43861592421095 + ], + "all_text_exact": false + } + ] + } + }, + "sampler": { + "sha256": "5bfbead61f8b46dc7ee76cf3186db83ebef453ed4858cc38d00be4ad7cb48e93", + "result": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 37, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 89.40440600016154, + "tok_s": 68.7214453389344 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 89.16692200000398, + "tok_s": 68.90447558568553 + } + ], + "percent": 0.26633643377032, + "cycle_percent": [ + 0.7357678117180244, + 0.5650808552969178, + -0.49657593682587153 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 60.225192999700084, + "tok_s": 102.01710769163657 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 60.04081799928099, + "tok_s": 102.33038464055531 + } + ], + "percent": 0.3070827589679137, + "cycle_percent": [ + -0.0530270129389554, + 0.6317861665107394, + 0.3436150826138018 + ], + "all_text_exact": true + } + ] + } + } + } +} diff --git a/docs/design/evidence/pr9-review-fixes-m3.json b/docs/design/evidence/pr9-review-fixes-m3.json new file mode 100644 index 00000000..8e1ebd9d --- /dev/null +++ b/docs/design/evidence/pr9-review-fixes-m3.json @@ -0,0 +1,368 @@ +{ + "schema_version": 1, + "scope": "Single matched M3 Ultra campaign per comparison and serving mode; three measured cycles, not a promoted headline", + "model": { + "repo": "unsloth/Qwen3.6-35B-A3B-GGUF", + "revision": "a483e9e6cbd595906af30beda3187c2663a1118c", + "file": "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", + "sha256": "707a55a8a4397ecde44de0c499d3e68c1ad1d240d1da65826b4949d1043f4450" + }, + "hardware": { + "chip": "Apple M3 Ultra", + "memory_gb": 256, + "node": "macstudio-4f19n3" + }, + "measurement": { + "job": "job_gf030kdnqjk30wq", + "run": "run_vx3h77yq2w6f6rf", + "url": "https://pilot.jianyang.cloud/jobs/job_gf030kdnqjk30wq" + }, + "raw_evidence": { + "job": "job_0ec18ww6y3e96qe", + "run": "run_j3gbezzqzb7ztn0", + "url": "https://pilot.jianyang.cloud/jobs/job_0ec18ww6y3e96qe", + "manifest": { + "source_run": "run_vx3h77yq2w6f6rf", + "archives": [ + { + "name": "main-vs-candidate-plain.tar.gz", + "sha256": "ef077e304c28a60c07fef311e48522ba2b4fdb01e7e95dc10d05932c3bf75ac9", + "size_bytes": 6168954 + }, + { + "name": "main-vs-candidate-dflash.tar.gz", + "sha256": "4f7f22a198d31c83c76b51782d59da20e9407a646acea4baa893bc46dce60b5e", + "size_bytes": 5940507 + }, + { + "name": "previous-vs-candidate-plain.tar.gz", + "sha256": "62151ea16ab1890a409c556188e9f00b9c9ae18515636105124aab3e323565db", + "size_bytes": 6397625 + }, + { + "name": "previous-vs-candidate-dflash.tar.gz", + "sha256": "8a8e916830037114d08abe67981348f96ccff7e8c7c070c15a6e0c3636500e15", + "size_bytes": 6200060 + } + ] + } + }, + "sources": { + "candidate": { + "source_sha": "ab0dd87644237851ce1b576b70eec8cf2c32a6d5", + "cli_sha256": "bbf8e5f65f775b2103068bee74eb8275aa587775d5f6ad919c7e73b138bacfc8", + "upstream": "8954f194837d2ec4d5f67f20c81b84abe63883ba" + }, + "main": { + "source_sha": "5008074f6e255929aa26589e03e736df3822a545", + "cli_sha256": "f7e4925abffffac38145099ca933678bacfee6741860e21ca11b8b3955d80184", + "upstream": "8954f194837d2ec4d5f67f20c81b84abe63883ba" + }, + "previous": { + "source_sha": "1ebce5ed2168c13f2a1865ae8ff2fe70cc43bfb5", + "cli_sha256": "7b3820f42fa55760bbb0dba4b6badc58f10bf070e7a03428cc6934fb712fcd01", + "upstream": "8954f194837d2ec4d5f67f20c81b84abe63883ba" + } + }, + "method": { + "order": "within-prompt ABBA", + "prompts": 8, + "output_tokens_per_request": 128, + "concurrency": [ + 1, + 2 + ], + "warmup_cycles": 3, + "measured_cycles": 3, + "sampling": "temperature zero, top-k one", + "cache": "prompt and disk disabled, zero cache hits verified", + "rate": "output tokens divided by pooled HTTP batch elapsed time, including prefill", + "guards": "reject complete blocks on competing load or non-nominal thermals", + "promotion_allowed": false + }, + "comparisons": { + "main-plain": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 21, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 64.78189199999906, + "tok_s": 94.84131769414961 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 61.71361899934709, + "tok_s": 99.55663109086183 + } + ], + "percent": 4.971792369986328, + "cycle_percent": [ + 4.693237770240333, + 5.037783035677412, + 5.184624623160161 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 40.835763999959454, + "tok_s": 150.4563499780756 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.942690999479964, + "tok_s": 161.92841989210012 + } + ], + "percent": 7.624849277346035, + "cycle_percent": [ + 7.86788963490106, + 7.941412609710019, + 7.0675151109427015 + ], + "all_text_exact": true + } + ] + }, + "main-dflash": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 18, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 37.77992199989967, + "tok_s": 162.62606365403073 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.28446499980055, + "tok_s": 164.78713051220842 + } + ], + "percent": 1.3288564019941607, + "cycle_percent": [ + 1.2718362417887707, + 1.3529851093694756, + 1.3619846946107739 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 38.956046000588685, + "tok_s": 157.7162117507294 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 29.581658999668434, + "tok_s": 207.6962620679545 + } + ], + "percent": 31.6898622927988, + "cycle_percent": [ + 30.59416238688599, + 32.63350598551329, + 31.85208701129605 + ], + "all_text_exact": true + } + ] + }, + "previous-plain": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 27, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 62.22441299865022, + "tok_s": 98.73938063719903 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 61.990102000534534, + "tok_s": 99.11259703923412 + } + ], + "percent": 0.3779813075862837, + "cycle_percent": [ + 0.2501577404599331, + 0.7548334014564562, + 0.12980263760229427 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 38.067643999587744, + "tok_s": 161.39690704437965 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.86665099998936, + "tok_s": 162.25358825637173 + } + ], + "percent": 0.5307915917846628, + "cycle_percent": [ + 0.6061706973918835, + 0.515295808723848, + 0.47129154148917163 + ], + "all_text_exact": true + } + ] + }, + "previous-dflash": { + "status": "PASS_ARTIFACT_AUDIT", + "single_campaign": true, + "promotion_allowed": false, + "accepted_requests": 288, + "rejected_blocks": 22, + "comparisons": [ + { + "concurrency": 1, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 37.420559999533, + "tok_s": 164.18781547033706 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 37.256177000235766, + "tok_s": 164.91225065741767 + } + ], + "percent": 0.4412234763008227, + "cycle_percent": [ + -0.017664873822431648, + 1.0072273194966064, + 0.33578426237002024 + ], + "all_text_exact": true + }, + { + "concurrency": 2, + "arms": [ + { + "arm": "old", + "output_tokens": 6144, + "elapsed_s": 29.86924699996598, + "tok_s": 205.69651454578008 + }, + { + "arm": "new", + "output_tokens": 6144, + "elapsed_s": 29.52857599989511, + "tok_s": 208.06963397157466 + } + ], + "percent": 1.1536993862219402, + "cycle_percent": [ + 0.8091444971112693, + 1.4958001339886673, + 1.1578186950807812 + ], + "all_text_exact": true + } + ] + } + }, + "native_validation": { + "job": "job_947w4gdfrhnad3x", + "run": "run_n8ckbq618kdhr4f", + "source_sha": "0caf2309ad48188d3337449bcccbf38f63f0b36f", + "status": "passed", + "backend": "Metal on Apple M3 Ultra", + "routed_native_cases": 40, + "paired_outputs": 80, + "fp64_oracle_checks": 160, + "r8_pipeline_compiles": 1, + "r4_pipeline_compiles": 1, + "row_diagnostics": "GGML_METAL_ROUTED_ROWS=1; production defaults unchanged", + "copy_contracts": "CPU and MTL0; identity, non-overlap, swaps, fan-out, zeroing, ascending snapshot planes", + "peer_rollback_modes": [ + 0, + 1, + 2, + 7 + ], + "url": "https://pilot.jianyang.cloud/jobs/job_947w4gdfrhnad3x", + "logs": { + "routed-native.log": { + "sha256": "3e3efa1113c84380e2e48e34e4f4fc21541915b9ee1e2dc162fe844af69b316b", + "size_bytes": 12107 + }, + "metal-copy.log": { + "sha256": "567c81c424137121d647002861fb4d33e511c7f1a14b55bd6de98ad8a4db3ddc", + "size_bytes": 4027 + }, + "metal-peer-rollback.log": { + "sha256": "015db8fb0d830834a596d6f79c053714184e849abd7600fcb1c56bce113fd66c", + "size_bytes": 740 + } + } + }, + "local_validation": { + "serving_tests": { + "passed": 1374, + "ignored_opt_in": 32, + "failed": 0, + "doc_tests": "passed" + }, + "native_replay": { + "unique_passed": 335, + "timeout": [ + "skippy_graph_contract_glm4-expansion" + ], + "skipped_opt_in": [ + "skippy_resident_checkpoint_gpu_long" + ], + "clean_full_replay_pass": false + }, + "clippy": "warning-denying all-target skippy-serving with dynamic-native-runtime", + "native_tree": "aafc58beb4f494798917276e28da54e62a10b06f" + } +} diff --git a/docs/native-api.md b/docs/native-api.md index d70f7cb4..d59dedb7 100644 --- a/docs/native-api.md +++ b/docs/native-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 **137 exported functions**. +Current generated surface: **21 headers** and **141 exported functions**. ## Quick navigation @@ -81,13 +81,14 @@ Current generated surface: **21 headers** and **137 exported functions**.
- execution.h16 functions + execution.h17 functions
- state.h21 functions + state.h24 functions
skippy_model_memory_cache_capabilities skippy_model_kv_pool_cells @@ -208,11 +209,14 @@ Current generated surface: **21 headers** and **137 exported functions**. skippy_session_verify_rollback_counts skippy_export_kv_page skippy_import_kv_page + skippy_import_kv_page_chunks skippy_import_cachegen_kv_page_v1 skippy_session_save_prefix skippy_session_restore_prefix skippy_session_export_resident_kv_page + skippy_session_export_resident_kv_component skippy_session_export_resident_recurrent_state + skippy_session_copy_resident_recurrent_range skippy_session_resident_prefix_bytes skippy_session_memory_used_cells skippy_session_drop_sequence @@ -764,6 +768,18 @@ LLAMA_API enum skippy_status skippy_decode_step_sampled_mtp( struct skippy_error ** out_error); ``` + +#### `skippy_verify_batch_sampled` + +Verify equal-length windows on independent lanes of one terminal model. Every window retains its own rollback checkpoint and sampler history. Sampling stops at the first rejected proposal in each lane. The caller must trim or retire every window before reusing that lane. The combined windows must fit one native microbatch. Activation-frontier stages are not supported here. + +```cpp +LLAMA_API enum skippy_status skippy_verify_batch_sampled( + const struct skippy_verify_request * requests, + size_t request_count, + struct skippy_error ** out_error); +``` + #### `skippy_iteration_batch_sampled` @@ -1910,6 +1926,20 @@ LLAMA_API enum skippy_status skippy_import_kv_page( struct skippy_error ** out_error); ``` + +#### `skippy_import_kv_page_chunks` + +Imports a single raw KV page from non-empty chunks in wire order. The ranges must remain readable until return and together cover exactly desc->payload_bytes. Unsupported layouts or backends leave the session untouched, so the caller can retry with a contiguous payload. + +```cpp +LLAMA_API enum skippy_status skippy_import_kv_page_chunks( + struct skippy_session * session, + const struct skippy_kv_page_desc * desc, + const struct skippy_kv_page_chunk * chunks, + size_t chunk_count, + struct skippy_error ** out_error); +``` + #### `skippy_import_cachegen_kv_page_v1` @@ -1971,6 +2001,27 @@ LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( struct skippy_error ** out_error); ``` + +#### `skippy_session_export_resident_kv_component` + +Exports an absolute token range from one resident sliding-window page component. The selected range must still be resident in that component. The returned descriptor is a single page, with no component offset. + +```cpp +LLAMA_API enum skippy_status skippy_session_export_resident_kv_component( + struct skippy_session * session, + int32_t cache_seq_id, + enum skippy_kv_page_component_role role, + 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` @@ -1986,6 +2037,21 @@ LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( struct skippy_error ** out_error); ``` + +#### `skippy_session_copy_resident_recurrent_range` + +Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint. + +```cpp +LLAMA_API enum skippy_status skippy_session_copy_resident_recurrent_range( + struct skippy_session * session, + int32_t cache_seq_id, + size_t offset, + void * output, + size_t bytes, + struct skippy_error ** out_error); +``` + #### `skippy_session_resident_prefix_bytes` @@ -2278,10 +2344,10 @@ 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 = 88`, `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)` +- `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 = 95`, `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` +- `execution.h`: `skippy_token_score_request`, `skippy_iteration_request`, `skippy_verify_request` - `laya.h`: `skippy_laya_model`, `skippy_laya_qtype`, `skippy_laya_info_v1`, `skippy_laya_memory_v1`, `skippy_laya_sequence`, `SKIPPY_LAYA_INFO_V1_ABI_VERSION = 1`, `SKIPPY_LAYA_QTYPE_COUNT = 3`, `SKIPPY_LAYA_MEMORY_V1_ABI_VERSION = 1`, `SKIPPY_LAYA_MAX_SEQUENCE_TOKENS = 4096` - `logprobs.h`: `skippy_logprob_entry`, `skippy_token_logprobs`, `SKIPPY_MAX_TOP_LOGPROBS = 20` - `model_package.h`: `skippy_tensor_role`, `skippy_model_info`, `skippy_tensor_info` @@ -2290,7 +2356,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `signals.h`: `skippy_token_signal`, `skippy_generation_signal_window` - `speculative_decoding.h`: `skippy_ngram_cache`, `skippy_native_mtp_draft`, `SKIPPY_NATIVE_MTP_MAX_DRAFT_TOKENS = 8` - `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` +- `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_kv_page_chunk`, `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` diff --git a/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch b/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch index 3a80fc56..83c115eb 100644 --- a/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch +++ b/llama_cpp/patches/0001-feat-skippy-define-graph-derived-native-ABI.patch @@ -1,4 +1,4 @@ -From e4ac96241415b7a42c0d39b83460f42024e2903b Mon Sep 17 00:00:00 2001 +From 0185b2ff6f1857859379999851ef6e983ab68d0a Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 Subject: [PATCH] feat(skippy): define graph-derived native ABI @@ -40,7 +40,7 @@ Subject: [PATCH] feat(skippy): define graph-derived native ABI diff --git a/include/skippy.h b/include/skippy.h new file mode 100644 -index 0000000000000000000000000000000000000000..dc8cbb431d31b21358507ce9136debd0fbe1fbbf +index 000000000..dc8cbb431 --- /dev/null +++ b/include/skippy.h @@ -0,0 +1,29 @@ @@ -75,7 +75,7 @@ index 0000000000000000000000000000000000000000..dc8cbb431d31b21358507ce9136debd0 +#endif // SKIPPY_H diff --git a/include/skippy/activation.h b/include/skippy/activation.h new file mode 100644 -index 0000000000000000000000000000000000000000..673c1d81cafffd797ac6a63b34e0f48e4ed8d927 +index 000000000..673c1d81c --- /dev/null +++ b/include/skippy/activation.h @@ -0,0 +1,66 @@ @@ -147,7 +147,7 @@ index 0000000000000000000000000000000000000000..673c1d81cafffd797ac6a63b34e0f48e +#endif // SKIPPY_ACTIVATION_H diff --git a/include/skippy/common.h b/include/skippy/common.h new file mode 100644 -index 0000000000000000000000000000000000000000..b9b5259afe44fe588e485a3abeccb8bc58bf0ed8 +index 000000000..b9b5259af --- /dev/null +++ b/include/skippy/common.h @@ -0,0 +1,146 @@ @@ -299,7 +299,7 @@ index 0000000000000000000000000000000000000000..b9b5259afe44fe588e485a3abeccb8bc +#endif // SKIPPY_COMMON_H diff --git a/include/skippy/devices.h b/include/skippy/devices.h new file mode 100644 -index 0000000000000000000000000000000000000000..36c6eb641b3f850ade443f6522a81b10eadfe635 +index 000000000..36c6eb641 --- /dev/null +++ b/include/skippy/devices.h @@ -0,0 +1,56 @@ @@ -361,7 +361,7 @@ index 0000000000000000000000000000000000000000..36c6eb641b3f850ade443f6522a81b10 +#endif diff --git a/include/skippy/events.h b/include/skippy/events.h new file mode 100644 -index 0000000000000000000000000000000000000000..2e0aa446f6df19d28dd6af958f71e983ed01f4ac +index 000000000..2e0aa446f --- /dev/null +++ b/include/skippy/events.h @@ -0,0 +1,229 @@ @@ -596,7 +596,7 @@ index 0000000000000000000000000000000000000000..2e0aa446f6df19d28dd6af958f71e983 +#endif // SKIPPY_EVENTS_H diff --git a/include/skippy/execution.h b/include/skippy/execution.h new file mode 100644 -index 0000000000000000000000000000000000000000..7098677d8bf27a333c7438dc4895d1859fc8eab4 +index 000000000..7098677d8 --- /dev/null +++ b/include/skippy/execution.h @@ -0,0 +1,264 @@ @@ -866,7 +866,7 @@ index 0000000000000000000000000000000000000000..7098677d8bf27a333c7438dc4895d185 +#endif // SKIPPY_EXECUTION_H diff --git a/include/skippy/model_package.h b/include/skippy/model_package.h new file mode 100644 -index 0000000000000000000000000000000000000000..944f57fdfc258b0608688272ed906f79152766e4 +index 000000000..944f57fdf --- /dev/null +++ b/include/skippy/model_package.h @@ -0,0 +1,93 @@ @@ -965,7 +965,7 @@ index 0000000000000000000000000000000000000000..944f57fdfc258b0608688272ed906f79 +#endif // SKIPPY_MODEL_PACKAGE_H diff --git a/include/skippy/model_source.h b/include/skippy/model_source.h new file mode 100644 -index 0000000000000000000000000000000000000000..5d77f4804b3a34f9ccb7057d82846060c587ef37 +index 000000000..5d77f4804 --- /dev/null +++ b/include/skippy/model_source.h @@ -0,0 +1,84 @@ @@ -1055,7 +1055,7 @@ index 0000000000000000000000000000000000000000..5d77f4804b3a34f9ccb7057d82846060 +#endif // SKIPPY_MODEL_SOURCE_H diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h new file mode 100644 -index 0000000000000000000000000000000000000000..799bdca2dadf1ef102ea5b207827ffda1ef8abf0 +index 000000000..799bdca2d --- /dev/null +++ b/include/skippy/runtime.h @@ -0,0 +1,277 @@ @@ -1338,7 +1338,7 @@ index 0000000000000000000000000000000000000000..799bdca2dadf1ef102ea5b207827ffda +#endif // SKIPPY_RUNTIME_H diff --git a/include/skippy/sampling.h b/include/skippy/sampling.h new file mode 100644 -index 0000000000000000000000000000000000000000..1b42f32c0c68b206273cdb4d992bad2419b6e6be +index 000000000..1b42f32c0 --- /dev/null +++ b/include/skippy/sampling.h @@ -0,0 +1,76 @@ @@ -1420,7 +1420,7 @@ index 0000000000000000000000000000000000000000..1b42f32c0c68b206273cdb4d992bad24 +#endif // SKIPPY_SAMPLING_H diff --git a/include/skippy/signals.h b/include/skippy/signals.h new file mode 100644 -index 0000000000000000000000000000000000000000..c4d3d24d92ab40ccb0f62d1479076bc5fd619183 +index 000000000..c4d3d24d9 --- /dev/null +++ b/include/skippy/signals.h @@ -0,0 +1,53 @@ @@ -1479,7 +1479,7 @@ index 0000000000000000000000000000000000000000..c4d3d24d92ab40ccb0f62d1479076bc5 +#endif // SKIPPY_SIGNALS_H diff --git a/include/skippy/speculative_decoding.h b/include/skippy/speculative_decoding.h new file mode 100644 -index 0000000000000000000000000000000000000000..0b5994482975cac5744acc595db38710d2224c37 +index 000000000..0b5994482 --- /dev/null +++ b/include/skippy/speculative_decoding.h @@ -0,0 +1,71 @@ @@ -1556,7 +1556,7 @@ index 0000000000000000000000000000000000000000..0b5994482975cac5744acc595db38710 +#endif // SKIPPY_SPECULATIVE_DECODING_H diff --git a/include/skippy/stage_plan.h b/include/skippy/stage_plan.h new file mode 100644 -index 0000000000000000000000000000000000000000..7ffe652772e8c3a4ca737b12b8b4877a9b1d01a9 +index 000000000..7ffe65277 --- /dev/null +++ b/include/skippy/stage_plan.h @@ -0,0 +1,256 @@ @@ -1818,7 +1818,7 @@ index 0000000000000000000000000000000000000000..7ffe652772e8c3a4ca737b12b8b4877a +#endif // SKIPPY_STAGE_PLAN_H diff --git a/include/skippy/state.h b/include/skippy/state.h new file mode 100644 -index 0000000000000000000000000000000000000000..1cfaaa5c69329eb0d21307c72cb7629267002be3 +index 000000000..1cfaaa5c6 --- /dev/null +++ b/include/skippy/state.h @@ -0,0 +1,236 @@ @@ -2060,7 +2060,7 @@ index 0000000000000000000000000000000000000000..1cfaaa5c69329eb0d21307c72cb76292 +#endif // SKIPPY_STATE_H diff --git a/include/skippy/tokenization.h b/include/skippy/tokenization.h new file mode 100644 -index 0000000000000000000000000000000000000000..c9697cf6c5c6da8147b849d79c85062edf8e56ba +index 000000000..c9697cf6c --- /dev/null +++ b/include/skippy/tokenization.h @@ -0,0 +1,85 @@ @@ -2151,7 +2151,7 @@ index 0000000000000000000000000000000000000000..c9697cf6c5c6da8147b849d79c85062e +#endif // SKIPPY_TOKENIZATION_H diff --git a/include/skippy/workloads.h b/include/skippy/workloads.h new file mode 100644 -index 0000000000000000000000000000000000000000..6aff324149748c35da2b7e62451e758b288d69f5 +index 000000000..6aff32414 --- /dev/null +++ b/include/skippy/workloads.h @@ -0,0 +1,93 @@ @@ -2248,3 +2248,6 @@ index 0000000000000000000000000000000000000000..6aff324149748c35da2b7e62451e758b +#endif + +#endif // SKIPPY_WORKLOADS_H +-- +2.56.0 + diff --git a/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch b/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch index 0d598e46..f778947b 100644 --- a/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch +++ b/llama_cpp/patches/0002-feat-skippy-realize-admitted-stages-from-live-graphs.patch @@ -1,8 +1,9 @@ -From 68e6dc5352663efd02a17830c3344b3c7d7c3f3d Mon Sep 17 00:00:00 2001 +From 15b4372009aa2a9729bfe96171982f339bff9356 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 +Co-authored-by: Melkor --- common/common.cpp | 109 --- common/common.h | 20 +- @@ -23,7 +24,7 @@ Subject: [PATCH] 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 ++ @@ -37,7 +38,7 @@ Subject: [PATCH] feat(skippy): realize admitted stages from live graphs src/skippy/events_internal.h | 35 + src/skippy/executable_graph.cpp | 335 +++++++ src/skippy/executable_graph.h | 37 + - src/skippy/execution-batch.cpp | 499 ++++++++++ + src/skippy/execution-batch.cpp | 515 ++++++++++ src/skippy/execution-single.cpp | 642 ++++++++++++ src/skippy/execution_internal.h | 20 + src/skippy/glm_dsa.cpp | 857 ++++++++++++++++ @@ -50,7 +51,7 @@ Subject: [PATCH] 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] 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] 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, 16518 insertions(+), 407 deletions(-) create mode 100644 common/log-terminal.cpp create mode 100644 common/regex-escape.cpp create mode 100644 common/sampling-config.cpp @@ -152,7 +153,7 @@ Subject: [PATCH] feat(skippy): realize admitted stages from live graphs create mode 100644 src/skippy/workloads_internal.h diff --git a/common/common.cpp b/common/common.cpp -index b009d460d697246bb5c5e74125f4f3507e60fdc9..2cf5cc7fc398b31c4a4c2af474e6040b840133bb 100644 +index b009d460d..2cf5cc7fc 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -67,14 +67,6 @@ @@ -293,7 +294,7 @@ index b009d460d697246bb5c5e74125f4f3507e60fdc9..2cf5cc7fc398b31c4a4c2af474e6040b const llama_model * model = llama_get_model(ctx); const llama_vocab * vocab = llama_model_get_vocab(model); diff --git a/common/common.h b/common/common.h -index 22724e81743642a35a35e7ff82ba46d7fac9cecc..4981afa922f87d9f344e44b17c2ece103472cbc4 100644 +index 22724e817..4981afa92 100644 --- a/common/common.h +++ b/common/common.h @@ -43,7 +43,7 @@ @@ -370,7 +371,7 @@ index 22724e81743642a35a35e7ff82ba46d7fac9cecc..4981afa922f87d9f344e44b17c2ece10 llama_token token, bool special = true); diff --git a/common/json.cpp b/common/json.cpp -index 37713cef29e78833fd09cfff607cc83b3eb871c6..694d85badbcfee2675cde403e929116da813c857 100644 +index 37713cef2..694d85bad 100644 --- a/common/json.cpp +++ b/common/json.cpp @@ -92,7 +92,7 @@ static std::shared_ptr set_json(const std::set & vals) { @@ -426,7 +427,7 @@ index 37713cef29e78833fd09cfff607cc83b3eb871c6..694d85badbcfee2675cde403e929116d COMMON_JSON_GET(bool) COMMON_JSON_GET(int) diff --git a/common/json.h b/common/json.h -index 95b6d6f212e533fc83072b0c8f40120b36c33eef..da3b599dcd412a2ce63dbe94f64f5b88f851b3dc 100644 +index 95b6d6f21..da3b599dc 100644 --- a/common/json.h +++ b/common/json.h @@ -1,5 +1,7 @@ @@ -497,7 +498,7 @@ index 95b6d6f212e533fc83072b0c8f40120b36c33eef..da3b599dcd412a2ce63dbe94f64f5b88 diff --git a/common/log-terminal.cpp b/common/log-terminal.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..a486de11c717de44e9ad9954a49493509304335f +index 000000000..a486de11c --- /dev/null +++ b/common/log-terminal.cpp @@ -0,0 +1,52 @@ @@ -554,7 +555,7 @@ index 0000000000000000000000000000000000000000..a486de11c717de44e9ad9954a4949350 +} + diff --git a/common/log.h b/common/log.h -index 93ea58e76158add30c7050032d641261317af800..6bc5c5914a3dcb4c3f02a2478b175a5eaf78adf5 100644 +index 93ea58e76..6bc5c5914 100644 --- a/common/log.h +++ b/common/log.h @@ -1,5 +1,6 @@ @@ -648,7 +649,7 @@ index 93ea58e76158add30c7050032d641261317af800..6bc5c5914a3dcb4c3f02a2478b175a5e #define LOG_JSON(type, data) \ diff --git a/common/regex-escape.cpp b/common/regex-escape.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..12c3888f6d0d0c37cf5d968dd6013d2d2e5b53fb +index 000000000..12c3888f6 --- /dev/null +++ b/common/regex-escape.cpp @@ -0,0 +1,8 @@ @@ -662,7 +663,7 @@ index 0000000000000000000000000000000000000000..12c3888f6d0d0c37cf5d968dd6013d2d + diff --git a/common/sampling-config.cpp b/common/sampling-config.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..bf3c4c8e672a9159e2e7cf80cd5962deb28c60f5 +index 000000000..bf3c4c8e6 --- /dev/null +++ b/common/sampling-config.cpp @@ -0,0 +1,169 @@ @@ -837,7 +838,7 @@ index 0000000000000000000000000000000000000000..bf3c4c8e672a9159e2e7cf80cd5962de +} diff --git a/common/sampling-report.cpp b/common/sampling-report.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d40a39f71d0de99da8634cbfb5ffa1a53f4e5175 +index 000000000..d40a39f71 --- /dev/null +++ b/common/sampling-report.cpp @@ -0,0 +1,51 @@ @@ -894,7 +895,7 @@ index 0000000000000000000000000000000000000000..d40a39f71d0de99da8634cbfb5ffa1a5 + diff --git a/common/sampling-timing.cpp b/common/sampling-timing.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..3936d82f6dca515c41f13f26d16f557bc5b2523f +index 000000000..3936d82f6 --- /dev/null +++ b/common/sampling-timing.cpp @@ -0,0 +1,10 @@ @@ -909,7 +910,7 @@ index 0000000000000000000000000000000000000000..3936d82f6dca515c41f13f26d16f557b +} + diff --git a/common/sampling.cpp b/common/sampling.cpp -index 078bfd984f424573199841633a7fb419ea5d5591..8ac63d67264137d2cf0eaf5c344cc123d49ae3ed 100644 +index 078bfd984..8ac63d672 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -1,7 +1,6 @@ @@ -1255,7 +1256,7 @@ index 078bfd984f424573199841633a7fb419ea5d5591..8ac63d67264137d2cf0eaf5c344cc123 - } -} diff --git a/common/sampling.h b/common/sampling.h -index f19bd27c40f8b41de21d409caaa9e343a1eb7d5b..97b4c278a2c7c7e4e79b157c92c3dc2004df92a5 100644 +index f19bd27c4..97b4c278a 100644 --- a/common/sampling.h +++ b/common/sampling.h @@ -37,23 +37,25 @@ struct common_sampler; @@ -1367,7 +1368,7 @@ index f19bd27c40f8b41de21d409caaa9e343a1eb7d5b..97b4c278a2c7c7e4e79b157c92c3dc20 struct common_sampler_deleter { diff --git a/common/tokenization.cpp b/common/tokenization.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..7f5064cb5bcf8af357769443f4b11e1b33ccc917 +index 000000000..7f5064cb5 --- /dev/null +++ b/common/tokenization.cpp @@ -0,0 +1,58 @@ @@ -1430,7 +1431,7 @@ index 0000000000000000000000000000000000000000..7f5064cb5bcf8af357769443f4b11e1b +} + diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp -index 3391cb49e858a98b42b2cf462e6ed85c81d18a1b..cf1dfe8c6f9efdd687e45c7db6c886601044bcd5 100644 +index 3391cb49e..cf1dfe8c6 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -28,7 +28,8 @@ llama_batch_allocr::llama_batch_allocr(uint32_t n_pos_per_embd, bool allow_mixed @@ -1501,7 +1502,7 @@ index 3391cb49e858a98b42b2cf462e6ed85c81d18a1b..cf1dfe8c6f9efdd687e45c7db6c88660 llama_batch_compat::~llama_batch_compat() { diff --git a/src/llama-batch.h b/src/llama-batch.h -index e6f4be6a28a02287f47367342a2457d67e11f5ed..9b4c5a7dc59d5b7ebb60c6f2978224cb5e867524 100644 +index e6f4be6a2..9b4c5a7dc 100644 --- a/src/llama-batch.h +++ b/src/llama-batch.h @@ -170,7 +170,8 @@ public: @@ -1528,7 +1529,7 @@ index e6f4be6a28a02287f47367342a2457d67e11f5ed..9b4c5a7dc59d5b7ebb60c6f2978224cb + static void init(llama_batch_ext & batch_ext, const llama_batch & batch_inp, size_t n_embd_row = 0, bool activation_positions = false); }; diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 35308bf3eb300660f35e40bbd1fc797c7417159e..545347cd7a5775ed6e81badc30e0c47a43279228 100644 +index 35308bf3e..545347cd7 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2214,7 +2214,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { @@ -1543,7 +1544,7 @@ index 35308bf3eb300660f35e40bbd1fc797c7417159e..545347cd7a5775ed6e81badc30e0c47a return -1; } diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp -index 3866d5980f37caf7cd07eeba6ff755e9a2b23580..a7f6f9d848bb43e04110777ab57ccb44a0449b1a 100644 +index 3866d5980..a7f6f9d84 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -195,6 +195,16 @@ bool llama_memory_hybrid_idx::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_po @@ -1564,7 +1565,7 @@ index 3866d5980f37caf7cd07eeba6ff755e9a2b23580..a7f6f9d848bb43e04110777ab57ccb44 // only whole sequences are copied: the recurrent state ignores the range, and a shared cell holds a single pool grouping GGML_ASSERT(p0 <= 0 && p1 < 0 && "partial seq_cp is not supported"); diff --git a/src/llama-memory-hybrid-idx.h b/src/llama-memory-hybrid-idx.h -index ebd082ab5685215db13b334aef318e03b921e9d2..d32ea0c7b1f32442d214396d7a16bf0eac08d956 100644 +index ebd082ab5..d32ea0c7b 100644 --- a/src/llama-memory-hybrid-idx.h +++ b/src/llama-memory-hybrid-idx.h @@ -66,6 +66,10 @@ public: @@ -1580,7 +1581,7 @@ index ebd082ab5685215db13b334aef318e03b921e9d2..d32ea0c7b1f32442d214396d7a16bf0e // state write/load diff --git a/src/skippy/abi.cpp b/src/skippy/abi.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..ceed6e5d36ca9521bbba0d32a176defb2a425b3b +index 000000000..ceed6e5d3 --- /dev/null +++ b/src/skippy/abi.cpp @@ -0,0 +1,59 @@ @@ -1645,7 +1646,7 @@ index 0000000000000000000000000000000000000000..ceed6e5d36ca9521bbba0d32a176defb +} diff --git a/src/skippy/activation.cpp b/src/skippy/activation.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d1c094548c7c3e0273366d2fb067c037d1878255 +index 000000000..d1c094548 --- /dev/null +++ b/src/skippy/activation.cpp @@ -0,0 +1,1028 @@ @@ -2679,7 +2680,7 @@ index 0000000000000000000000000000000000000000..d1c094548c7c3e0273366d2fb067c037 +} diff --git a/src/skippy/activation_internal.h b/src/skippy/activation_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..29674ebda7c23f0c136cc3b5b58a4ea1d5caf4f9 +index 000000000..29674ebda --- /dev/null +++ b/src/skippy/activation_internal.h @@ -0,0 +1,88 @@ @@ -2773,7 +2774,7 @@ index 0000000000000000000000000000000000000000..29674ebda7c23f0c136cc3b5b58a4ea1 + skippy_error ** out_error); diff --git a/src/skippy/activation_layout.cpp b/src/skippy/activation_layout.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..0cb2181dfe5dfc953355ea4e10e86217e5f9dabd +index 000000000..0cb2181df --- /dev/null +++ b/src/skippy/activation_layout.cpp @@ -0,0 +1,164 @@ @@ -2943,7 +2944,7 @@ index 0000000000000000000000000000000000000000..0cb2181dfe5dfc953355ea4e10e86217 +} // extern "C" diff --git a/src/skippy/block_boundaries.cpp b/src/skippy/block_boundaries.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..e72a49b0cd23a755a8967f25f47e1e077bc41313 +index 000000000..e72a49b0c --- /dev/null +++ b/src/skippy/block_boundaries.cpp @@ -0,0 +1,64 @@ @@ -3013,7 +3014,7 @@ index 0000000000000000000000000000000000000000..e72a49b0cd23a755a8967f25f47e1e07 +} diff --git a/src/skippy/block_boundaries.h b/src/skippy/block_boundaries.h new file mode 100644 -index 0000000000000000000000000000000000000000..7c9aae1144fdf8134efefaaf83d4073636a7185d +index 000000000..7c9aae114 --- /dev/null +++ b/src/skippy/block_boundaries.h @@ -0,0 +1,42 @@ @@ -3061,7 +3062,7 @@ index 0000000000000000000000000000000000000000..7c9aae1144fdf8134efefaaf83d40736 + std::string & error); diff --git a/src/skippy/chat_sampling.cpp b/src/skippy/chat_sampling.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..3c9fc758bdae343a7ae9581a32bb95b436d5de28 +index 000000000..3c9fc758b --- /dev/null +++ b/src/skippy/chat_sampling.cpp @@ -0,0 +1,75 @@ @@ -3142,7 +3143,7 @@ index 0000000000000000000000000000000000000000..3c9fc758bdae343a7ae9581a32bb95b4 +} diff --git a/src/skippy/chat_sampling.h b/src/skippy/chat_sampling.h new file mode 100644 -index 0000000000000000000000000000000000000000..1c01b2bd032dbc912c26450f13462f0e65bd98ec +index 000000000..1c01b2bd0 --- /dev/null +++ b/src/skippy/chat_sampling.h @@ -0,0 +1,7 @@ @@ -3155,7 +3156,7 @@ index 0000000000000000000000000000000000000000..1c01b2bd032dbc912c26450f13462f0e +llama_token skippy_chat_sample_token(skippy_session * session, int32_t logits_index); diff --git a/src/skippy/devices.cpp b/src/skippy/devices.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..2068a9b1cd2030203a8bac51f964b299652e35a0 +index 000000000..2068a9b1c --- /dev/null +++ b/src/skippy/devices.cpp @@ -0,0 +1,106 @@ @@ -3267,7 +3268,7 @@ index 0000000000000000000000000000000000000000..2068a9b1cd2030203a8bac51f964b299 + diff --git a/src/skippy/environment.h b/src/skippy/environment.h new file mode 100644 -index 0000000000000000000000000000000000000000..a9f574b2f271d21caf60e533fa5876ffd4832d60 +index 000000000..a9f574b2f --- /dev/null +++ b/src/skippy/environment.h @@ -0,0 +1,48 @@ @@ -3321,7 +3322,7 @@ index 0000000000000000000000000000000000000000..a9f574b2f271d21caf60e533fa5876ff +} diff --git a/src/skippy/errors.h b/src/skippy/errors.h new file mode 100644 -index 0000000000000000000000000000000000000000..08a147aae8f8aabc99115fd9397eff9652e8c7a7 +index 000000000..08a147aae --- /dev/null +++ b/src/skippy/errors.h @@ -0,0 +1,66 @@ @@ -3393,7 +3394,7 @@ index 0000000000000000000000000000000000000000..08a147aae8f8aabc99115fd9397eff96 + diff --git a/src/skippy/events.cpp b/src/skippy/events.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..a7bbe60281bbdfe33a952a760168a0be98706fec +index 000000000..a7bbe6028 --- /dev/null +++ b/src/skippy/events.cpp @@ -0,0 +1,243 @@ @@ -3642,7 +3643,7 @@ index 0000000000000000000000000000000000000000..a7bbe60281bbdfe33a952a760168a0be +} diff --git a/src/skippy/events_internal.h b/src/skippy/events_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..040f89e1e16abb1d9255e0391568f68132fc65a1 +index 000000000..040f89e1e --- /dev/null +++ b/src/skippy/events_internal.h @@ -0,0 +1,35 @@ @@ -3683,7 +3684,7 @@ index 0000000000000000000000000000000000000000..040f89e1e16abb1d9255e0391568f681 +#endif // SKIPPY_EVENTS_INTERNAL_H diff --git a/src/skippy/executable_graph.cpp b/src/skippy/executable_graph.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..fb993cbd92de310b9113acc79a103652ae32eb53 +index 000000000..fb993cbd9 --- /dev/null +++ b/src/skippy/executable_graph.cpp @@ -0,0 +1,335 @@ @@ -4024,7 +4025,7 @@ index 0000000000000000000000000000000000000000..fb993cbd92de310b9113acc79a103652 +} diff --git a/src/skippy/executable_graph.h b/src/skippy/executable_graph.h new file mode 100644 -index 0000000000000000000000000000000000000000..aa02187d17802923dcf4092e5a772a8de20f79b3 +index 000000000..aa02187d1 --- /dev/null +++ b/src/skippy/executable_graph.h @@ -0,0 +1,37 @@ @@ -4067,10 +4068,10 @@ index 0000000000000000000000000000000000000000..aa02187d17802923dcf4092e5a772a8d + std::string & error); diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..2b9593e0cfc957c583a5c4c9d2679f8ab4c70d9a +index 000000000..31a65905b --- /dev/null +++ b/src/skippy/execution-batch.cpp -@@ -0,0 +1,499 @@ +@@ -0,0 +1,515 @@ +#include "skippy.h" +#include "skippy/activation_internal.h" +#include "skippy/errors.h" @@ -4485,9 +4486,25 @@ index 0000000000000000000000000000000000000000..2b9593e0cfc957c583a5c4c9d2679f8a + return SKIPPY_STATUS_RUNTIME_ERROR; + } + skippy_mark_context_work_pending(first->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( @@ -4572,7 +4589,7 @@ index 0000000000000000000000000000000000000000..2b9593e0cfc957c583a5c4c9d2679f8a +} // extern "C" diff --git a/src/skippy/execution-single.cpp b/src/skippy/execution-single.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..4ce3d4ba92e3a572bc8bc229d41f84eef8c36b61 +index 000000000..4ce3d4ba9 --- /dev/null +++ b/src/skippy/execution-single.cpp @@ -0,0 +1,642 @@ @@ -5220,7 +5237,7 @@ index 0000000000000000000000000000000000000000..4ce3d4ba92e3a572bc8bc229d41f84ee +} // extern "C" diff --git a/src/skippy/execution_internal.h b/src/skippy/execution_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..1d59e00d3cef298ef44554ab9e59f29b75f278df +index 000000000..1d59e00d3 --- /dev/null +++ b/src/skippy/execution_internal.h @@ -0,0 +1,20 @@ @@ -5246,7 +5263,7 @@ index 0000000000000000000000000000000000000000..1d59e00d3cef298ef44554ab9e59f29b + const skippy_graph_build_inputs * graph_build_inputs = nullptr); diff --git a/src/skippy/glm_dsa.cpp b/src/skippy/glm_dsa.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..7ce838ee1df0f665bbe931f2de29976f7cd2fb7b +index 000000000..7ce838ee1 --- /dev/null +++ b/src/skippy/glm_dsa.cpp @@ -0,0 +1,857 @@ @@ -6109,7 +6126,7 @@ index 0000000000000000000000000000000000000000..7ce838ee1df0f665bbe931f2de29976f + diff --git a/src/skippy/glm_dsa.h b/src/skippy/glm_dsa.h new file mode 100644 -index 0000000000000000000000000000000000000000..7d7f5cc0dde837aacc03805fb9e3fb9402a032ff +index 000000000..7d7f5cc0d --- /dev/null +++ b/src/skippy/glm_dsa.h @@ -0,0 +1,14 @@ @@ -6129,7 +6146,7 @@ index 0000000000000000000000000000000000000000..7d7f5cc0dde837aacc03805fb9e3fb94 +void skippy_glm_dsa_op_timing_end(skippy_session * session); diff --git a/src/skippy/graph_build_inputs.h b/src/skippy/graph_build_inputs.h new file mode 100644 -index 0000000000000000000000000000000000000000..c08f2d510d27cd1ee0ec0bc022c1a34df305692c +index 000000000..c08f2d510 --- /dev/null +++ b/src/skippy/graph_build_inputs.h @@ -0,0 +1,109 @@ @@ -6244,7 +6261,7 @@ index 0000000000000000000000000000000000000000..c08f2d510d27cd1ee0ec0bc022c1a34d +} diff --git a/src/skippy/graph_dependencies.cpp b/src/skippy/graph_dependencies.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..c0e3cd7b97cad3ade858712fc1bc21c4aa36fe8f +index 000000000..c0e3cd7b9 --- /dev/null +++ b/src/skippy/graph_dependencies.cpp @@ -0,0 +1,57 @@ @@ -6307,7 +6324,7 @@ index 0000000000000000000000000000000000000000..c0e3cd7b97cad3ade858712fc1bc21c4 +} diff --git a/src/skippy/graph_dependencies.h b/src/skippy/graph_dependencies.h new file mode 100644 -index 0000000000000000000000000000000000000000..d34f53fe428318b7a6df4cdd05e4a6b19d59bc43 +index 000000000..d34f53fe4 --- /dev/null +++ b/src/skippy/graph_dependencies.h @@ -0,0 +1,11 @@ @@ -6324,7 +6341,7 @@ index 0000000000000000000000000000000000000000..d34f53fe428318b7a6df4cdd05e4a6b1 + const llama_model * model); diff --git a/src/skippy/graph_identity.cpp b/src/skippy/graph_identity.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..ab2dd50e950a41f34a6f95e2f357e7aa4b882011 +index 000000000..ab2dd50e9 --- /dev/null +++ b/src/skippy/graph_identity.cpp @@ -0,0 +1,1092 @@ @@ -7422,7 +7439,7 @@ index 0000000000000000000000000000000000000000..ab2dd50e950a41f34a6f95e2f357e7aa +} diff --git a/src/skippy/graph_identity.h b/src/skippy/graph_identity.h new file mode 100644 -index 0000000000000000000000000000000000000000..843c7ba7fddea5fdadaded990108c96a92b607e6 +index 000000000..843c7ba7f --- /dev/null +++ b/src/skippy/graph_identity.h @@ -0,0 +1,71 @@ @@ -7499,7 +7516,7 @@ index 0000000000000000000000000000000000000000..843c7ba7fddea5fdadaded990108c96a + std::string & error); diff --git a/src/skippy/model_lifecycle.cpp b/src/skippy/model_lifecycle.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..caa9fcd6de0d0dabfe636feba45bbdd1808bf87f +index 000000000..caa9fcd6d --- /dev/null +++ b/src/skippy/model_lifecycle.cpp @@ -0,0 +1,155 @@ @@ -7660,7 +7677,7 @@ index 0000000000000000000000000000000000000000..caa9fcd6de0d0dabfe636feba45bbdd1 +} // extern "C" diff --git a/src/skippy/model_load_config.cpp b/src/skippy/model_load_config.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..2e8d3c4ed6d312e4ce618d04eddf18dae7782c5b +index 000000000..2e8d3c4ed --- /dev/null +++ b/src/skippy/model_load_config.cpp @@ -0,0 +1,213 @@ @@ -7879,7 +7896,7 @@ index 0000000000000000000000000000000000000000..2e8d3c4ed6d312e4ce618d04eddf18da +} diff --git a/src/skippy/model_load_config_internal.h b/src/skippy/model_load_config_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..554d2bdd3be1a734c30fdd53ae7ef05658fb45e4 +index 000000000..554d2bdd3 --- /dev/null +++ b/src/skippy/model_load_config_internal.h @@ -0,0 +1,35 @@ @@ -7920,7 +7937,7 @@ index 0000000000000000000000000000000000000000..554d2bdd3be1a734c30fdd53ae7ef056 +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 0000000000000000000000000000000000000000..60a27669fb6a2ef80651e41bc79de1da494a43a8 +index 000000000..60a27669f --- /dev/null +++ b/src/skippy/model_loading.cpp @@ -0,0 +1,1189 @@ @@ -9115,7 +9132,7 @@ index 0000000000000000000000000000000000000000..60a27669fb6a2ef80651e41bc79de1da +} // extern "C" diff --git a/src/skippy/model_loading_internal.h b/src/skippy/model_loading_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..97e966e4e9e5282b3acc0bb25800ff0588dc97ed +index 000000000..97e966e4e --- /dev/null +++ b/src/skippy/model_loading_internal.h @@ -0,0 +1,38 @@ @@ -9159,7 +9176,7 @@ index 0000000000000000000000000000000000000000..97e966e4e9e5282b3acc0bb25800ff05 +} // extern "C" diff --git a/src/skippy/model_package.cpp b/src/skippy/model_package.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..75cf28fbd29f7bc1b5a2eccaf28b2bf3ac259f16 +index 000000000..75cf28fbd --- /dev/null +++ b/src/skippy/model_package.cpp @@ -0,0 +1,782 @@ @@ -9947,7 +9964,7 @@ index 0000000000000000000000000000000000000000..75cf28fbd29f7bc1b5a2eccaf28b2bf3 +} diff --git a/src/skippy/model_source.cpp b/src/skippy/model_source.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..02ad771ade0bac7dddfc4d31eff27247fbadd207 +index 000000000..02ad771ad --- /dev/null +++ b/src/skippy/model_source.cpp @@ -0,0 +1,463 @@ @@ -10416,7 +10433,7 @@ index 0000000000000000000000000000000000000000..02ad771ade0bac7dddfc4d31eff27247 +} diff --git a/src/skippy/package_tensor_binding.cpp b/src/skippy/package_tensor_binding.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..5fb51f89997a22d9448e2a948d7d12efed2447db +index 000000000..5fb51f899 --- /dev/null +++ b/src/skippy/package_tensor_binding.cpp @@ -0,0 +1,120 @@ @@ -10542,7 +10559,7 @@ index 0000000000000000000000000000000000000000..5fb51f89997a22d9448e2a948d7d12ef +} diff --git a/src/skippy/package_tensor_binding.h b/src/skippy/package_tensor_binding.h new file mode 100644 -index 0000000000000000000000000000000000000000..751048af8a7a747872fc7c8b8d92833f30966aa2 +index 000000000..751048af8 --- /dev/null +++ b/src/skippy/package_tensor_binding.h @@ -0,0 +1,27 @@ @@ -10575,7 +10592,7 @@ index 0000000000000000000000000000000000000000..751048af8a7a747872fc7c8b8d92833f + std::string & error); diff --git a/src/skippy/rerank_template.h b/src/skippy/rerank_template.h new file mode 100644 -index 0000000000000000000000000000000000000000..f0c3b2ea791b08f467d359e7e5cd674f7fba25c1 +index 000000000..f0c3b2ea7 --- /dev/null +++ b/src/skippy/rerank_template.h @@ -0,0 +1,36 @@ @@ -10617,7 +10634,7 @@ index 0000000000000000000000000000000000000000..f0c3b2ea791b08f467d359e7e5cd674f +} diff --git a/src/skippy/runtime_support.h b/src/skippy/runtime_support.h new file mode 100644 -index 0000000000000000000000000000000000000000..d7e99130754c2447fac040b6af979b687b59241b +index 000000000..d7e991307 --- /dev/null +++ b/src/skippy/runtime_support.h @@ -0,0 +1,47 @@ @@ -10670,7 +10687,7 @@ index 0000000000000000000000000000000000000000..d7e99130754c2447fac040b6af979b68 + skippy_error ** out_error); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h new file mode 100644 -index 0000000000000000000000000000000000000000..f19a25b76a54088ef1cf49c27ac75a22f88514cd +index 000000000..f19a25b76 --- /dev/null +++ b/src/skippy/runtime_types.h @@ -0,0 +1,183 @@ @@ -10859,7 +10876,7 @@ index 0000000000000000000000000000000000000000..f19a25b76a54088ef1cf49c27ac75a22 +}; diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..6fd1240e375eb08280bdc303ff6ce90a1e8ccf67 +index 000000000..6fd1240e3 --- /dev/null +++ b/src/skippy/sampling.cpp @@ -0,0 +1,602 @@ @@ -11467,7 +11484,7 @@ index 0000000000000000000000000000000000000000..6fd1240e375eb08280bdc303ff6ce90a +} diff --git a/src/skippy/sampling_config.cpp b/src/skippy/sampling_config.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..6be5559e23d9db28d07485eeefefd8d2af5891e4 +index 000000000..6be5559e2 --- /dev/null +++ b/src/skippy/sampling_config.cpp @@ -0,0 +1,178 @@ @@ -11651,7 +11668,7 @@ index 0000000000000000000000000000000000000000..6be5559e23d9db28d07485eeefefd8d2 +} diff --git a/src/skippy/sampling_internal.h b/src/skippy/sampling_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..7bbf160164aa3c25d33ab90dcad39d63f5250847 +index 000000000..7bbf16016 --- /dev/null +++ b/src/skippy/sampling_internal.h @@ -0,0 +1,67 @@ @@ -11724,7 +11741,7 @@ index 0000000000000000000000000000000000000000..7bbf160164aa3c25d33ab90dcad39d63 +llama_token skippy_sample_token(skippy_session * session, const skippy_sampling_config * sampling); diff --git a/src/skippy/sampling_vocab.cpp b/src/skippy/sampling_vocab.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..baf83db4466ee03c9d58cb4e966f4643f9584b6e +index 000000000..baf83db44 --- /dev/null +++ b/src/skippy/sampling_vocab.cpp @@ -0,0 +1,74 @@ @@ -11804,7 +11821,7 @@ index 0000000000000000000000000000000000000000..baf83db4466ee03c9d58cb4e966f4643 +} diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..f1de95cc5290334672181cdda2ce7c7796e772c5 +index 000000000..f1de95cc5 --- /dev/null +++ b/src/skippy/session.cpp @@ -0,0 +1,521 @@ @@ -12331,7 +12348,7 @@ index 0000000000000000000000000000000000000000..f1de95cc5290334672181cdda2ce7c77 +} // extern "C" diff --git a/src/skippy/speculative_decoding.cpp b/src/skippy/speculative_decoding.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..3d15111fb304c38341aade0a9e44e09962f55c87 +index 000000000..3d15111fb --- /dev/null +++ b/src/skippy/speculative_decoding.cpp @@ -0,0 +1,568 @@ @@ -12905,7 +12922,7 @@ index 0000000000000000000000000000000000000000..3d15111fb304c38341aade0a9e44e099 +} diff --git a/src/skippy/speculative_internal.h b/src/skippy/speculative_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..d8276944dea03fc64c202fa184213d47a73cfcf3 +index 000000000..d8276944d --- /dev/null +++ b/src/skippy/speculative_internal.h @@ -0,0 +1,32 @@ @@ -12943,7 +12960,7 @@ index 0000000000000000000000000000000000000000..d8276944dea03fc64c202fa184213d47 + skippy_error ** out_error); diff --git a/src/skippy/stage_execution_contract.cpp b/src/skippy/stage_execution_contract.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..719e044627deb9e605ffbc64a9b3724dfc15b145 +index 000000000..719e04462 --- /dev/null +++ b/src/skippy/stage_execution_contract.cpp @@ -0,0 +1,78 @@ @@ -13027,7 +13044,7 @@ index 0000000000000000000000000000000000000000..719e044627deb9e605ffbc64a9b3724d +} diff --git a/src/skippy/stage_execution_contract.h b/src/skippy/stage_execution_contract.h new file mode 100644 -index 0000000000000000000000000000000000000000..bcb56cdd764f0a37d566bb9fac792f1c296eab98 +index 000000000..bcb56cdd7 --- /dev/null +++ b/src/skippy/stage_execution_contract.h @@ -0,0 +1,15 @@ @@ -13048,7 +13065,7 @@ index 0000000000000000000000000000000000000000..bcb56cdd764f0a37d566bb9fac792f1c + bool embedding_input = false); diff --git a/src/skippy/stage_plan.cpp b/src/skippy/stage_plan.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..380e1eaad93d222fd8f9ab318a5c34c3ae26059e +index 000000000..380e1eaad --- /dev/null +++ b/src/skippy/stage_plan.cpp @@ -0,0 +1,709 @@ @@ -13763,7 +13780,7 @@ index 0000000000000000000000000000000000000000..380e1eaad93d222fd8f9ab318a5c34c3 +} diff --git a/src/skippy/stage_realization.cpp b/src/skippy/stage_realization.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..4a91e986b7383b52c10e198babb502074e65dcb5 +index 000000000..4a91e986b --- /dev/null +++ b/src/skippy/stage_realization.cpp @@ -0,0 +1,362 @@ @@ -14131,7 +14148,7 @@ index 0000000000000000000000000000000000000000..4a91e986b7383b52c10e198babb50207 +} diff --git a/src/skippy/stage_realization.h b/src/skippy/stage_realization.h new file mode 100644 -index 0000000000000000000000000000000000000000..6ef94f46dc46ea41ed76cf6166f51dda52683583 +index 000000000..6ef94f46d --- /dev/null +++ b/src/skippy/stage_realization.h @@ -0,0 +1,21 @@ @@ -14158,7 +14175,7 @@ index 0000000000000000000000000000000000000000..6ef94f46dc46ea41ed76cf6166f51dda + llm_graph_result & result); diff --git a/src/skippy/stage_slice_plan.cpp b/src/skippy/stage_slice_plan.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..7444a760e8b417519c03772e3f29483d5a253a3a +index 000000000..7444a760e --- /dev/null +++ b/src/skippy/stage_slice_plan.cpp @@ -0,0 +1,907 @@ @@ -15071,7 +15088,7 @@ index 0000000000000000000000000000000000000000..7444a760e8b417519c03772e3f29483d +} diff --git a/src/skippy/stage_slice_plan.h b/src/skippy/stage_slice_plan.h new file mode 100644 -index 0000000000000000000000000000000000000000..1cb24c7cb74226c999296f4d42ab761d8e2882eb +index 000000000..1cb24c7cb --- /dev/null +++ b/src/skippy/stage_slice_plan.h @@ -0,0 +1,136 @@ @@ -15213,10 +15230,10 @@ index 0000000000000000000000000000000000000000..1cb24c7cb74226c999296f4d42ab761d + std::string & error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..f035ea13fdcfd88fb0681918f3acf389199bc81b +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 +15839,9 @@ index 0000000000000000000000000000000000000000..f035ea13fdcfd88fb0681918f3acf389 + 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 +15905,9 @@ index 0000000000000000000000000000000000000000..f035ea13fdcfd88fb0681918f3acf389 + 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; @@ -16408,7 +16431,7 @@ index 0000000000000000000000000000000000000000..f035ea13fdcfd88fb0681918f3acf389 +} // extern "C" diff --git a/src/skippy/state_effects.cpp b/src/skippy/state_effects.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..b33ed2d5d881faa7aaff49767c907944c83069c8 +index 000000000..b33ed2d5d --- /dev/null +++ b/src/skippy/state_effects.cpp @@ -0,0 +1,450 @@ @@ -16864,7 +16887,7 @@ index 0000000000000000000000000000000000000000..b33ed2d5d881faa7aaff49767c907944 +} diff --git a/src/skippy/state_effects.h b/src/skippy/state_effects.h new file mode 100644 -index 0000000000000000000000000000000000000000..5bb6b779b6c03a49447ec9dc5d1bb52128edf1d8 +index 000000000..5bb6b779b --- /dev/null +++ b/src/skippy/state_effects.h @@ -0,0 +1,74 @@ @@ -16944,7 +16967,7 @@ index 0000000000000000000000000000000000000000..5bb6b779b6c03a49447ec9dc5d1bb521 + std::string & error); diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..e271852ff0286fde08f61bdc18565c19b063d5a2 +index 000000000..e271852ff --- /dev/null +++ b/src/skippy/state_memory.cpp @@ -0,0 +1,116 @@ @@ -17066,7 +17089,7 @@ index 0000000000000000000000000000000000000000..e271852ff0286fde08f61bdc18565c19 +} diff --git a/src/skippy/state_memory.h b/src/skippy/state_memory.h new file mode 100644 -index 0000000000000000000000000000000000000000..4875cf39855d72989869e0f492de01cdf5a320d3 +index 000000000..4875cf398 --- /dev/null +++ b/src/skippy/state_memory.h @@ -0,0 +1,16 @@ @@ -17088,7 +17111,7 @@ index 0000000000000000000000000000000000000000..4875cf39855d72989869e0f492de01cd +uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result); diff --git a/src/skippy/tokenization.cpp b/src/skippy/tokenization.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..54753a1610a8a75da19b69f3264af1db218b88b9 +index 000000000..54753a161 --- /dev/null +++ b/src/skippy/tokenization.cpp @@ -0,0 +1,179 @@ @@ -17273,7 +17296,7 @@ index 0000000000000000000000000000000000000000..54753a1610a8a75da19b69f3264af1db +} // extern "C" diff --git a/src/skippy/verification.cpp b/src/skippy/verification.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..0812485d71dfedc65a8760fe682ab8b89c3771a0 +index 000000000..0812485d7 --- /dev/null +++ b/src/skippy/verification.cpp @@ -0,0 +1,256 @@ @@ -17535,7 +17558,7 @@ index 0000000000000000000000000000000000000000..0812485d71dfedc65a8760fe682ab8b8 +} // extern "C" diff --git a/src/skippy/workloads.cpp b/src/skippy/workloads.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d3de66cbe98390974482208af891fa3567967f51 +index 000000000..d3de66cbe --- /dev/null +++ b/src/skippy/workloads.cpp @@ -0,0 +1,373 @@ @@ -17914,7 +17937,7 @@ index 0000000000000000000000000000000000000000..d3de66cbe98390974482208af891fa35 +} // extern "C" diff --git a/src/skippy/workloads_internal.h b/src/skippy/workloads_internal.h new file mode 100644 -index 0000000000000000000000000000000000000000..cc9279e7ed491543959603a3f69f69cf1401b2f2 +index 000000000..cc9279e7e --- /dev/null +++ b/src/skippy/workloads_internal.h @@ -0,0 +1,8 @@ @@ -17927,7 +17950,7 @@ index 0000000000000000000000000000000000000000..cc9279e7ed491543959603a3f69f69cf +// attached from an earlier chat request. +void skippy_prepare_non_chat_workload(skippy_session * session); diff --git a/tests/test-batch-alloc.cpp b/tests/test-batch-alloc.cpp -index 49e2b075521a3655be94f386189d178ca2e1abe4..93f8e4ef5ee64bec5fe9aff304cff8a9a56896bc 100644 +index 49e2b0755..93f8e4ef5 100644 --- a/tests/test-batch-alloc.cpp +++ b/tests/test-batch-alloc.cpp @@ -926,6 +926,27 @@ static void test_mrope(testing & t) { @@ -17958,3 +17981,6 @@ index 49e2b075521a3655be94f386189d178ca2e1abe4..93f8e4ef5ee64bec5fe9aff304cff8a9 t.test("token_batch_explicit_fields", [&](testing & t) { llama_token token[3] = { 5, 6, 7 }; llama_pos pos[3] = { 3, 4, 5 }; +-- +2.56.0 + diff --git a/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch b/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch index 6e0f85e2..ee63c86c 100644 --- a/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch +++ b/llama_cpp/patches/0003-feat-llama-integrate-live-stage-planning-and-executi.patch @@ -1,4 +1,4 @@ -From 1a6f24ab802a6bc15236a6013f94c5b30809cab9 Mon Sep 17 00:00:00 2001 +From 4625421677286f58807caeb201b5339c1890763f 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 @@ -45,11 +45,11 @@ 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, 3080 insertions(+), 329 deletions(-) + 25 files changed, 3084 insertions(+), 325 deletions(-) create mode 100644 src/skippy-verify-checkpoint.h diff --git a/include/llama.h b/include/llama.h -index 9cc17a82b529098c8849f3f023f22818bf3d64eb..7a2b918b40eae4a476da4714617eee37a9c2b337 100644 +index 9cc17a82b..7a2b918b4 100644 --- a/include/llama.h +++ b/include/llama.h @@ -555,6 +555,13 @@ extern "C" { @@ -67,7 +67,7 @@ index 9cc17a82b529098c8849f3f023f22818bf3d64eb..7a2b918b40eae4a476da4714617eee37 const struct llama_model * model, const char * path_model); diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp -index fe0b808b3a4dda69cd943df0d190c9b81e355134..d3b46066600fe1df2f4d003ec2ba1d5814692616 100644 +index fe0b808b3..d3b460666 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -345,6 +345,8 @@ static const std::map LLM_KV_NAMES = { @@ -124,7 +124,7 @@ index fe0b808b3a4dda69cd943df0d190c9b81e355134..d3b46066600fe1df2f4d003ec2ba1d58 {LLM_TENSOR_VISEXP_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_VISEXP_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, diff --git a/src/llama-arch.h b/src/llama-arch.h -index 305aae22aa5554c08b926f2327d64f2dd1e5421d..b36f0fb7f402c117213a18912bc50e1ce18aa45f 100644 +index 305aae22a..b36f0fb7f 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -349,6 +349,8 @@ enum llm_kv { @@ -137,7 +137,7 @@ index 305aae22aa5554c08b926f2327d64f2dd1e5421d..b36f0fb7f402c117213a18912bc50e1c LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, LLM_KV_ATTENTION_INDEXER_TYPES, diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c9959909c5b 100644 +index 545347cd7..bad10f27a 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -13,10 +13,16 @@ @@ -548,20 +548,22 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 // 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()) { -@@ -1941,11 +2054,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -1941,12 +2054,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; -@@ -1972,7 +2081,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { + const uint32_t n_outputs_all = balloc->get_n_outputs(); +@@ -1972,7 +2084,7 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { cparams.causal_attn = false; ggml_status status; @@ -570,7 +572,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 cparams.causal_attn = causal_attn_org; -@@ -2092,6 +2201,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { +@@ -2092,6 +2204,24 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return 0; } @@ -595,7 +597,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 template static void copy_tensor_async_rows( const std::vector & tensors, -@@ -2145,9 +2272,15 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); @@ -647,18 +649,21 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 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 @@ -667,7 +672,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 llama_memory_context_ptr mctx; -@@ -2282,7 +2415,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2282,7 +2423,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { if (!did_optimize) { did_optimize = true; @@ -676,7 +681,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens()); continue; -@@ -2310,11 +2443,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2310,11 +2451,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -2; }; @@ -688,7 +693,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2373,7 +2501,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2373,7 +2509,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { ggml_status status; @@ -702,7 +707,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 if (!res) { // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module -@@ -2511,9 +2644,22 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2511,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; @@ -726,7 +731,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 extract_all_idxs = extract_all_idxs || !masked; } } -@@ -2525,7 +2671,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2525,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()); } @@ -737,7 +742,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 const auto stride = n_vocab; // async copy the sampling data from the backend to the host -@@ -2537,6 +2685,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2537,6 +2693,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { n_outputs_prev += n_outputs; n_tokens_prev += ubatch.n_tokens; @@ -748,7 +753,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 } while (mctx->next()); if (layer_inp_dev && ev_layer_inp_written) { -@@ -2822,9 +2974,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -2822,9 +2982,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -761,7 +766,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 for (size_t s = 0; s < output_swaps.size(); ++s) { const uint64_t i0 = output_swaps[s].i0; -@@ -2837,6 +2989,7 @@ void llama_context::output_reorder() { +@@ -2837,6 +2997,7 @@ void llama_context::output_reorder() { } if (embd.size > 0) { @@ -769,7 +774,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 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]); } -@@ -2918,6 +3071,11 @@ uint32_t llama_context::graph_max_nodes() const { +@@ -2918,6 +3079,11 @@ uint32_t llama_context::graph_max_nodes() const { res += 32u*model.hparams.n_layer_all; } @@ -781,7 +786,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling for (const auto & [seq_id, sampler] : sampling.samplers) { res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq; -@@ -2955,7 +3113,6 @@ static void ubatch_prepare_reserve( +@@ -2955,7 +3121,6 @@ static void ubatch_prepare_reserve( } } @@ -789,7 +794,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 std::vector sampler_seqs; std::vector has_sampler(n_seqs, false); for (const auto & entry : samplers) { -@@ -2963,40 +3120,83 @@ static void ubatch_prepare_reserve( +@@ -2963,40 +3128,83 @@ static void ubatch_prepare_reserve( if (seq_id < 0 || (uint32_t) seq_id >= n_seqs) { continue; } @@ -880,7 +885,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 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); -@@ -3021,16 +3221,40 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3021,16 +3229,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); @@ -922,7 +927,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 // 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())) { -@@ -3039,6 +3263,130 @@ ggml_cgraph * llama_context::graph_reserve( +@@ -3039,6 +3271,130 @@ ggml_cgraph * llama_context::graph_reserve( } this->n_input_tensors = llama_graph_n_input_tensors(gf); @@ -1053,7 +1058,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 this->n_outputs = save_n_outputs; // initialize scheduler with the specified graph -@@ -3061,7 +3409,18 @@ llm_graph_params llama_context::graph_params( +@@ -3061,7 +3417,18 @@ llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, const llama_memory_context_i * mctx, @@ -1073,7 +1078,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 return { /*.model =*/ &model, /*.cparams =*/ cparams, -@@ -3080,6 +3439,9 @@ llm_graph_params llama_context::graph_params( +@@ -3080,6 +3447,9 @@ llm_graph_params llama_context::graph_params( /*.h_nextn_src =*/ supports_state_row() ? cparams.ctx_state_src->get_h_nextn_dev() : nullptr, /*.w_scales =*/ &model.w_scales, /*.samplers =*/ sampling.samplers, @@ -1083,7 +1088,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 /*.n_outputs =*/ n_outputs, /*.cb =*/ graph_get_cb(), /*.res =*/ res, -@@ -4312,7 +4674,8 @@ void llama_context::opt_epoch_iter( +@@ -4312,7 +4682,8 @@ void llama_context::opt_epoch_iter( auto * res = get_gf_res_prev(); @@ -1093,7 +1098,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 // the optimizer graph is allocated outside sched, so the next decode must rebuild gf_res_prev_active = nullptr; -@@ -4416,7 +4779,7 @@ llama_context_params llama_context_default_params() { +@@ -4416,7 +4787,7 @@ llama_context_params llama_context_default_params() { /*.n_seq_max =*/ 1, /*.n_rs_seq =*/ 0, /*.n_outputs_max =*/ 0, @@ -1102,7 +1107,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS, /*.ctx_type =*/ LLAMA_CONTEXT_TYPE_DEFAULT, -@@ -4453,9 +4816,10 @@ llama_context_params llama_context_default_params() { +@@ -4453,9 +4824,10 @@ llama_context_params llama_context_default_params() { return result; } @@ -1116,7 +1121,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 if (!model) { LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__); return nullptr; -@@ -4475,6 +4839,10 @@ llama_context * llama_init_from_model( +@@ -4475,6 +4847,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; } @@ -1127,7 +1132,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 if (model->split_mode() == LLAMA_SPLIT_MODE_TENSOR) { if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) { -@@ -4574,15 +4942,14 @@ llama_context * llama_init_from_model( +@@ -4574,15 +4950,14 @@ llama_context * llama_init_from_model( model->hparams.pooling_type, params.pooling_type); } @@ -1145,7 +1150,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 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) { -@@ -4599,6 +4966,12 @@ llama_context * llama_init_from_model( +@@ -4599,6 +4974,12 @@ llama_context * llama_init_from_model( return nullptr; } @@ -1158,7 +1163,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 void llama_free(llama_context * ctx) { delete ctx; } -@@ -4834,7 +5207,8 @@ struct ggml_cgraph * llama_graph_reserve( +@@ -4834,7 +5215,8 @@ struct ggml_cgraph * llama_graph_reserve( if (memory) { mctx = memory->init_full(); } @@ -1168,7 +1173,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 } // llama adapter API -@@ -5061,13 +5435,25 @@ size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, lla +@@ -5061,13 +5443,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) { @@ -1198,7 +1203,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 } /// -@@ -5086,7 +5472,11 @@ int32_t llama_encode( +@@ -5086,7 +5480,11 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { @@ -1212,7 +1217,7 @@ index 545347cd7a5775ed6e81badc30e0c47a43279228..bc3311d98e6c48cfb0af72fd55397c99 LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret); } diff --git a/src/llama-context.h b/src/llama-context.h -index 3e3921c7df283783b44b82d81ce06cc4d0f8282b..668065b39d7fc434d5fbc08fad9c9d4f2fbc61b0 100644 +index 3e3921c7d..668065b39 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -14,15 +14,38 @@ @@ -1428,7 +1433,7 @@ index 3e3921c7df283783b44b82d81ce06cc4d0f8282b..668065b39d7fc434d5fbc08fad9c9d4f ggml_backend_buffer_ptr buf_output; diff --git a/src/llama-ext.h b/src/llama-ext.h -index a77b2f40948a287b9d839f8c1cdc6dd0ed950561..e5f2e6c919019ad07667c8cd6b54b993a5ea2d54 100644 +index a77b2f409..e5f2e6c91 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -75,6 +75,12 @@ LLAMA_API bool llama_quant_tensor_allows_quantization( @@ -1445,7 +1450,7 @@ index a77b2f40948a287b9d839f8c1cdc6dd0ed950561..e5f2e6c919019ad07667c8cd6b54b993 // 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 4a1d497b7dbd8e02640253e9f72facffd0678f3d..c7488ff29cd14c4cf7df3cebcd42ca0086d8ed9c 100644 +index 4a1d497b7..c7488ff29 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -116,6 +116,10 @@ public: @@ -1476,7 +1481,7 @@ index 4a1d497b7dbd8e02640253e9f72facffd0678f3d..c7488ff29cd14c4cf7df3cebcd42ca00 void set_input(const llama_ubatch * ubatch) override; diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp -index 807f7987f2643d7b7938bf930d4b56650e7af54e..ec7a529c91861d6196f018f4002db2dbc9af6cf5 100644 +index 807f7987f..ec7a529c9 100644 --- a/src/llama-hparams.cpp +++ b/src/llama-hparams.cpp @@ -205,7 +205,22 @@ uint32_t llama_hparams::n_embd_v_gqa_max() const { @@ -1503,7 +1508,7 @@ index 807f7987f2643d7b7938bf930d4b56650e7af54e..ec7a529c91861d6196f018f4002db2db // for RWKV models return token_shift_count * n_embd; diff --git a/src/llama-hparams.h b/src/llama-hparams.h -index 3e846be030fd9253b250b9b0cfa5b88bbb19613d..0e74e3e33cc058e9cfc9f616ebc7e97736abd348 100644 +index 3e846be03..0e74e3e33 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -74,9 +74,7 @@ struct llama_hparams { @@ -1555,7 +1560,7 @@ index 3e846be030fd9253b250b9b0cfa5b88bbb19613d..0e74e3e33cc058e9cfc9f616ebc7e977 // corresponds to Mamba's conv_states size or RWKV's token_shift states size uint32_t n_embd_r() const; diff --git a/src/llama-kv-cache-dsv4.cpp b/src/llama-kv-cache-dsv4.cpp -index 9c0a9b22dffc99568778da1c205b8cb50f6d050f..9d73acd39ac3eaed217c6e4ceca092b7a9599fd6 100644 +index 9c0a9b22d..9d73acd39 100644 --- a/src/llama-kv-cache-dsv4.cpp +++ b/src/llama-kv-cache-dsv4.cpp @@ -1177,14 +1177,16 @@ ggml_tensor * llama_dsv4_comp_state::get_kv_all(ggml_context * ctx, int32_t il) @@ -1578,7 +1583,7 @@ index 9c0a9b22dffc99568778da1c205b8cb50f6d050f..9d73acd39ac3eaed217c6e4ceca092b7 ggml_tensor * llama_dsv4_comp_state::get_kv(ggml_context * ctx, int32_t il) const { diff --git a/src/llama-kv-cache-msa.cpp b/src/llama-kv-cache-msa.cpp -index 2d6bac0cb23cf8f07458b83df398f4bfa487d636..8ef36beb33b79627962b449a6e41a2c4c2df5372 100644 +index 2d6bac0cb..8ef36beb3 100644 --- a/src/llama-kv-cache-msa.cpp +++ b/src/llama-kv-cache-msa.cpp @@ -38,7 +38,9 @@ llama_kv_cache_msa::llama_kv_cache_msa( @@ -1602,7 +1607,7 @@ index 2d6bac0cb23cf8f07458b83df398f4bfa487d636..8ef36beb33b79627962b449a6e41a2c4 void llama_kv_cache_msa::clear(bool data) { diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index c0166d30b4ad8fc9f2397c4ab773cbddba52c7eb..9c49fc71690ce9bbc51fa577dd7c8229e5884611 100644 +index c0166d30b..9c49fc716 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -4,6 +4,7 @@ @@ -3584,7 +3589,7 @@ index c0166d30b4ad8fc9f2397c4ab773cbddba52c7eb..9c49fc71690ce9bbc51fa577dd7c8229 kv->get_prev_tokens(ubatch, n, res); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index acff46e19c5931eeb47120b44ea2cefb01b12282..bc29bfd608e724630ebbf5edc44a439a1cd3968e 100644 +index acff46e19..bc29bfd60 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -6,12 +6,15 @@ @@ -3807,7 +3812,7 @@ index acff46e19c5931eeb47120b44ea2cefb01b12282..bc29bfd608e724630ebbf5edc44a439a // // update context diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h -index 1187cc736441afffeb78538d6af1c3664f231ecc..4fcb33d167cce985bd5d1a487578b8fc27f204ec 100644 +index 1187cc736..4fcb33d16 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -92,6 +92,7 @@ public: @@ -3919,7 +3924,7 @@ index 1187cc736441afffeb78538d6af1c3664f231ecc..4fcb33d167cce985bd5d1a487578b8fc // remove cell i diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp -index 0af05571cc1a2b646612e9eea3019e385dc74816..5c0e32e03749fade7af0bb042bd656e061b9d517 100644 +index 0af05571c..5c0e32e03 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -28,7 +28,8 @@ llama_memory_recurrent::llama_memory_recurrent( @@ -4051,7 +4056,7 @@ index 0af05571cc1a2b646612e9eea3019e385dc74816..5c0e32e03749fade7af0bb042bd656e0 bool llama_memory_recurrent_context::get_rs_replay() const { diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h -index f444b9b8ea1590cdbe3e642a39fdd56c8e085b29..956abcd060670f701a00c855b85ef97d9754fb51 100644 +index f444b9b8e..956abcd06 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -131,6 +131,16 @@ public: @@ -4081,7 +4086,7 @@ index f444b9b8ea1590cdbe3e642a39fdd56c8e085b29..956abcd060670f701a00c855b85ef97d size_t size_r_bytes() const; diff --git a/src/llama-mmap.cpp b/src/llama-mmap.cpp -index 02e4ede7c4d69c5792fc945b96c33e499b49c7ea..0c2c97bc2e0928ce27b5fee1ecfcbd510870d154 100644 +index 02e4ede7c..0c2c97bc2 100644 --- a/src/llama-mmap.cpp +++ b/src/llama-mmap.cpp @@ -646,6 +646,31 @@ llama_file::llama_file(FILE * file) : pimpl(std::make_unique(file)) {} @@ -4138,7 +4143,7 @@ index 02e4ede7c4d69c5792fc945b96c33e499b49c7ea..0c2c97bc2e0928ce27b5fee1ecfcbd51 uint32_t llama_file::read_u32() { return pimpl->read_u32(); } diff --git a/src/llama-mmap.h b/src/llama-mmap.h -index 39715bfc38b5bec7cb188f7faf2d5f4e0b5d1a0a..c777a59a92ffc46e8d8a98d03f6545fcc803237f 100644 +index 39715bfc3..c777a59a9 100644 --- a/src/llama-mmap.h +++ b/src/llama-mmap.h @@ -13,6 +13,16 @@ struct llama_file; @@ -4159,7 +4164,7 @@ index 39715bfc38b5bec7cb188f7faf2d5f4e0b5d1a0a..c777a59a92ffc46e8d8a98d03f6545fc using llama_mmaps = std::vector>; using llama_mlocks = std::vector>; diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp -index 83c8c042ba484b26f8295f1c19457ab210e896b3..783705c0e3533c7284d60c806ddd0f942be37e2d 100644 +index 83c8c042b..783705c0e 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -9,6 +9,7 @@ @@ -4667,7 +4672,7 @@ index 83c8c042ba484b26f8295f1c19457ab210e896b3..783705c0e3533c7284d60c806ddd0f94 if (use_mmap) { for (uint32_t idx = 0; idx < mappings.size(); idx++) { diff --git a/src/llama-model-loader.h b/src/llama-model-loader.h -index e2db7395bcf7db282b8b34d744a65b9ed9e1292d..72d9fc0b2922d20d1b0777c5fb69d3b8d4e3b54d 100644 +index e2db7395b..72d9fc0b2 100644 --- a/src/llama-model-loader.h +++ b/src/llama-model-loader.h @@ -14,11 +14,37 @@ @@ -4782,7 +4787,7 @@ index e2db7395bcf7db282b8b34d744a65b9ed9e1292d..72d9fc0b2922d20d1b0777c5fb69d3b8 template typename std::enable_if::value, bool>::type diff --git a/src/llama-model.cpp b/src/llama-model.cpp -index f06ea2ec03ce5e69cff1383667192bcee94ba724..6fb12e12793b8d63e700a15fa48f0c1e9ddd3676 100644 +index f06ea2ec0..6fb12e127 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -7,6 +7,7 @@ @@ -5085,7 +5090,7 @@ index f06ea2ec03ce5e69cff1383667192bcee94ba724..6fb12e12793b8d63e700a15fa48f0c1e if (out == nullptr) { return (uint32_t) nelements; diff --git a/src/llama-model.h b/src/llama-model.h -index c3334469d239a59c948635bd9f2e5855d47dced1..b7480fd9d012afe77b764ef1e1c1e75e833d4352 100644 +index c3334469d..b7480fd9d 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -1025,6 +1025,18 @@ struct llama_model { @@ -5126,7 +5131,7 @@ index c3334469d239a59c948635bd9f2e5855d47dced1..b7480fd9d012afe77b764ef1e1c1e75e // apply Hadamard transform to the lightning indexer keys virtual bool lid_k_hdmd() const { return false; } diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp -index 38eb0d588ba80fdacb5b3bfa86a4ae388bed0f2c..7dc9cf36a28af65765cf6af1d95804132c2181e6 100644 +index 38eb0d588..7dc9cf36a 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -469,6 +469,7 @@ static ggml_type fallback_type_for(const ggml_type target_type) { @@ -5170,7 +5175,7 @@ index 38eb0d588ba80fdacb5b3bfa86a4ae388bed0f2c..7dc9cf36a28af65765cf6af1d9580413 // build metadata from tensor names diff --git a/src/llama.cpp b/src/llama.cpp -index cee6a7dc4428efc1146b075d1cb118de22ef1b58..10beaeed437b806f70d4cf4382ef41a5b09334ee 100644 +index cee6a7dc4..10beaeed4 100644 --- a/src/llama.cpp +++ b/src/llama.cpp @@ -314,10 +314,12 @@ static bool llama_prepare_model_devices(const llama_model_params & params, llama @@ -5320,7 +5325,7 @@ index cee6a7dc4428efc1146b075d1cb118de22ef1b58..10beaeed437b806f70d4cf4382ef41a5 - diff --git a/src/skippy-verify-checkpoint.h b/src/skippy-verify-checkpoint.h new file mode 100644 -index 0000000000000000000000000000000000000000..8793000c101ace2fa78b5ae4356c4bed9393fcb9 +index 000000000..8793000c1 --- /dev/null +++ b/src/skippy-verify-checkpoint.h @@ -0,0 +1,24 @@ @@ -5348,3 +5353,6 @@ index 0000000000000000000000000000000000000000..8793000c101ace2fa78b5ae4356c4bed + checkpoints.erase(it); + return true; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0004-feat-models-expose-stage-independent-graph-semantics.patch b/llama_cpp/patches/0004-feat-models-expose-stage-independent-graph-semantics.patch index 87f84292..23a03041 100644 --- a/llama_cpp/patches/0004-feat-models-expose-stage-independent-graph-semantics.patch +++ b/llama_cpp/patches/0004-feat-models-expose-stage-independent-graph-semantics.patch @@ -1,4 +1,4 @@ -From a99e3c7b699b8e9a86098786252ef4480712f78e Mon Sep 17 00:00:00 2001 +From be749ad21ab28f30e950e7ae9767459a79988921 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 Subject: [PATCH] feat(models): expose stage-independent graph semantics @@ -47,7 +47,7 @@ Subject: [PATCH] feat(models): expose stage-independent graph semantics 40 files changed, 2053 insertions(+), 343 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d23423fdf0 100644 +index bad10f27a..7ec63d58b 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -724,7 +724,7 @@ void llama_context::resolve_fused_ops( @@ -59,7 +59,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 if (!gf) { throw std::runtime_error(std::string("failed to reserve graph for ") + probe.name + " check"); } -@@ -3196,7 +3196,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3204,7 +3204,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t bool split_only, size_t * sizes, const skippy_graph_build_inputs & graph_build_inputs, @@ -69,7 +69,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 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); -@@ -3343,7 +3344,7 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3351,7 +3352,7 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t } } }; @@ -78,7 +78,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 observe_frontier(res->get_skippy_activation_imports(), input_activation_frontier_observed, input_activation_frontier_stable, input_activation_frontier); const ggml_tensor * boundary = res->get_skippy_activation_input(); -@@ -3365,7 +3366,7 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3373,7 +3374,7 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t } } @@ -87,7 +87,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 observe_frontier(res->get_skippy_activation_exports(), activation_frontier_observed, activation_frontier_stable, activation_frontier); const ggml_tensor * boundary = res->get_skippy_activation_output(); -@@ -3411,6 +3412,15 @@ llm_graph_params llama_context::graph_params( +@@ -3419,6 +3420,15 @@ llm_graph_params llama_context::graph_params( const llama_memory_context_i * mctx, llm_graph_type gtype, const skippy_graph_build_inputs & graph_build_inputs) const { @@ -103,7 +103,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 std::vector export_token_axes; // Reservation observes the frontier with multiple tokens. Reuse those // axes during decode, where singleton checkpoint/token dimensions can be -@@ -3440,6 +3450,7 @@ llm_graph_params llama_context::graph_params( +@@ -3448,6 +3458,7 @@ llm_graph_params llama_context::graph_params( /*.w_scales =*/ &model.w_scales, /*.samplers =*/ sampling.samplers, /*.build_inputs=*/ graph_build_inputs, @@ -112,7 +112,7 @@ index bc3311d98e6c48cfb0af72fd55397c9959909c5b..52dfe91c75de4526f662d73b692346d2 /*.computation_generation=*/ computation_generation, /*.n_outputs =*/ n_outputs, diff --git a/src/llama-context.h b/src/llama-context.h -index 668065b39d7fc434d5fbc08fad9c9d4f2fbc61b0..c26fdd61584b9ae677f530871d7b0a401bf25da7 100644 +index 668065b39..c26fdd615 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -331,7 +331,8 @@ public: @@ -126,7 +126,7 @@ index 668065b39d7fc434d5fbc08fad9c9d4f2fbc61b0..c26fdd61584b9ae677f530871d7b0a40 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; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 31200d0d1267f7e91312bde9f8ef2c4245cd1cca..4b4f73e2f9c6962a98f3e52aa6a5556a468efb03 100644 +index 31200d0d1..4b4f73e2f 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -17,6 +17,7 @@ @@ -2187,7 +2187,7 @@ index 31200d0d1267f7e91312bde9f8ef2c4245cd1cca..4b4f73e2f9c6962a98f3e52aa6a5556a inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); ggml_set_input(inp->self_rel_pos); diff --git a/src/llama-graph.h b/src/llama-graph.h -index c7488ff29cd14c4cf7df3cebcd42ca0086d8ed9c..60ae9769df9cedf980d5f759045e631ac08d522f 100644 +index c7488ff29..60ae9769d 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -5,11 +5,17 @@ @@ -2650,7 +2650,7 @@ index c7488ff29cd14c4cf7df3cebcd42ca0086d8ed9c..60ae9769df9cedf980d5f759045e631a ggml_tensor * build_rwkv_token_shift_load( llm_graph_input_rs * inp, diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index 9c49fc71690ce9bbc51fa577dd7c8229e5884611..8d1e65c6d13dda36a1ca3312400b556face77afc 100644 +index 9c49fc716..8d1e65c6d 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -3449,24 +3449,6 @@ void llama_kv_cache::set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatc @@ -2679,7 +2679,7 @@ index 9c49fc71690ce9bbc51fa577dd7c8229e5884611..8d1e65c6d13dda36a1ca3312400b556f // M-RoPE needs the 2D position, the PLE / Engram n-gram hashes need the token id return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index bc29bfd608e724630ebbf5edc44a439a1cd3968e..0d683ec3e0630c7e3f353837686216752ab7ee71 100644 +index bc29bfd60..0d683ec3e 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -310,6 +310,10 @@ public: @@ -2702,7 +2702,7 @@ index bc29bfd608e724630ebbf5edc44a439a1cd3968e..0d683ec3e0630c7e3f35383768621675 // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp -index 112ad927617b82b9c157a1e19f785129fc44e286..06295e71b6fad4e07c6599e1205a3dedbcc4004a 100644 +index 112ad9276..06295e71b 100644 --- a/src/models/bailingmoe3.cpp +++ b/src/models/bailingmoe3.cpp @@ -184,7 +184,7 @@ ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d( @@ -2753,7 +2753,7 @@ index 112ad927617b82b9c157a1e19f785129fc44e286..06295e71b6fad4e07c6599e1205a3ded ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); diff --git a/src/models/bitnet.cpp b/src/models/bitnet.cpp -index 5c2145a4fb3fb8d2fdad9940789b77cc15a36b59..981c2ee474ea4db65d4bc3ac721bc2d9c4a21615 100644 +index 5c2145a4f..981c2ee47 100644 --- a/src/models/bitnet.cpp +++ b/src/models/bitnet.cpp @@ -16,6 +16,7 @@ void llama_model_bitnet::load_arch_tensors(llama_model_loader &) { @@ -2775,7 +2775,7 @@ index 5c2145a4fb3fb8d2fdad9940789b77cc15a36b59..981c2ee474ea4db65d4bc3ac721bc2d9 cb(cur, "result_output", -1); res->t_logits = cur; diff --git a/src/models/chameleon.cpp b/src/models/chameleon.cpp -index 599890705969f595cad8027710f56bd228149fa2..9dc6644d24c063ec8a36f497813bfc5794374315 100644 +index 599890705..9dc6644d2 100644 --- a/src/models/chameleon.cpp +++ b/src/models/chameleon.cpp @@ -176,17 +176,20 @@ llama_model_chameleon::graph::graph(const llm_graph_params & params) : llm_graph @@ -2811,7 +2811,7 @@ index 599890705969f595cad8027710f56bd228149fa2..9dc6644d24c063ec8a36f497813bfc57 cb(cur, "result_output", -1); res->t_logits = cur; diff --git a/src/models/deepseek32.cpp b/src/models/deepseek32.cpp -index 0f22161ec5863fae55bdac321c7db28dd512366a..522dd68e56544f583b7bdbb200fe08bc434d0ebb 100644 +index 0f22161ec..522dd68e5 100644 --- a/src/models/deepseek32.cpp +++ b/src/models/deepseek32.cpp @@ -200,6 +200,8 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) : @@ -2855,7 +2855,7 @@ index 0f22161ec5863fae55bdac321c7db28dd512366a..522dd68e56544f583b7bdbb200fe08bc ggml_tensor * q = build_lora_mm(model.layers[il].wq_b, qr); diff --git a/src/models/deepseek4.cpp b/src/models/deepseek4.cpp -index fb7fb304813704221d9bfa3ad99d5a0178206f6e..7fc139050734338fa4073f7af9d442fec681b268 100644 +index fb7fb3048..7fc139050 100644 --- a/src/models/deepseek4.cpp +++ b/src/models/deepseek4.cpp @@ -12,7 +12,8 @@ void llama_model_deepseek4::load_arch_hparams(llama_model_loader & ml) { @@ -2950,7 +2950,7 @@ index fb7fb304813704221d9bfa3ad99d5a0178206f6e..7fc139050734338fa4073f7af9d442fe cur = build_hc_head(inpL, model.hc_head_fn, model.hc_head_scale, model.hc_head_base); cb(cur, "mtp_hc_head", -1); diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp -index 4ea6fb757d90f1e78882fd4a2d170dab35d84a8a..692a320ee144df1e1a5551552970a5e104654034 100644 +index 4ea6fb757..692a320ee 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -63,7 +63,7 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( @@ -3006,7 +3006,7 @@ index 4ea6fb757d90f1e78882fd4a2d170dab35d84a8a..692a320ee144df1e1a5551552970a5e1 return output; } diff --git a/src/models/gemma4.cpp b/src/models/gemma4.cpp -index 2af261dd052e01afdc44c27b6aad0dde51b72e05..3f0e604cd71631c17f9b23cf126f2c02d5bf0afd 100644 +index 2af261dd0..3f0e604cd 100644 --- a/src/models/gemma4.cpp +++ b/src/models/gemma4.cpp @@ -114,8 +114,9 @@ void llama_model_gemma4::load_arch_tensors(llama_model_loader &) { @@ -3037,7 +3037,7 @@ index 2af261dd052e01afdc44c27b6aad0dde51b72e05..3f0e604cd71631c17f9b23cf126f2c02 inp_per_layer = ggml_get_rows(ctx0, model.per_layer_tok_embd, inp->token0); diff --git a/src/models/glm-dsa.cpp b/src/models/glm-dsa.cpp -index 5881933b2ced55eca1a91c42073467ac11a77c3c..998a8f98f870c2e9806d52c8647b2f355d0e492d 100644 +index 5881933b2..998a8f98f 100644 --- a/src/models/glm-dsa.cpp +++ b/src/models/glm-dsa.cpp @@ -56,14 +56,77 @@ void llama_model_glm_dsa::load_arch_hparams(llama_model_loader & ml) { @@ -3131,7 +3131,7 @@ index 5881933b2ced55eca1a91c42073467ac11a77c3c..998a8f98f870c2e9806d52c8647b2f35 const uint32_t kv_lora_rank = hparams.n_lora_kv; diff --git a/src/models/glm4-moe.cpp b/src/models/glm4-moe.cpp -index 73de9cbea9bffc2e9bd460aa8d4732ed7d46cdad..e6b73f2ca4b6457466deeeabd7766384fcd87d96 100644 +index 73de9cbea..e6b73f2ca 100644 --- a/src/models/glm4-moe.cpp +++ b/src/models/glm4-moe.cpp @@ -285,13 +285,8 @@ llama_model_glm4_moe::graph::graph(const llm_graph_params & params) : llm_graph_ @@ -3151,7 +3151,7 @@ index 73de9cbea9bffc2e9bd460aa8d4732ed7d46cdad..e6b73f2ca4b6457466deeeabd7766384 // inp_pos - contains the positions ggml_tensor * inp_pos = build_inp_pos(); diff --git a/src/models/glm4.cpp b/src/models/glm4.cpp -index f2f9c2f57009befd6ee3c1840a463d575f2780b9..bf6f34af0044938a5c2eda0015cbb138173998be 100644 +index f2f9c2f57..bf6f34af0 100644 --- a/src/models/glm4.cpp +++ b/src/models/glm4.cpp @@ -77,13 +77,8 @@ llama_model_glm4::graph::graph(const llm_graph_params & params) : llm_graph_cont @@ -3171,7 +3171,7 @@ index f2f9c2f57009befd6ee3c1840a463d575f2780b9..bf6f34af0044938a5c2eda0015cbb138 // inp_pos - contains the positions ggml_tensor * inp_pos = build_inp_pos(); diff --git a/src/models/granite-swa.cpp b/src/models/granite-swa.cpp -index 021de4537613011f98b64b59a935792c7725fc87..0246e11365d7ee2adfb64768651b823c259fca73 100644 +index 021de4537..0246e1136 100644 --- a/src/models/granite-swa.cpp +++ b/src/models/granite-swa.cpp @@ -53,7 +53,7 @@ void llama_model_granite_swa::load_arch_hparams(llama_model_loader & ml) { @@ -3233,7 +3233,7 @@ index 021de4537613011f98b64b59a935792c7725fc87..0246e11365d7ee2adfb64768651b823c cur = ggml_add(ctx0, moe_out, ffn_shexp); diff --git a/src/models/granite-switch.cpp b/src/models/granite-switch.cpp -index f6f1906c651c2438e6a5af263413d42636ab55c0..cb9a2eaacbfe98fa612a51ef1f62631c7f6a01a0 100644 +index f6f1906c6..cb9a2eaac 100644 --- a/src/models/granite-switch.cpp +++ b/src/models/granite-switch.cpp @@ -22,8 +22,14 @@ void llama_model_granite_switch::load_arch_hparams(llama_model_loader & ml) { @@ -3332,7 +3332,7 @@ index f6f1906c651c2438e6a5af263413d42636ab55c0..cb9a2eaacbfe98fa612a51ef1f62631c // embed the substituted ids directly; build_inp_embd would embed the raw tokens diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp -index 882c45811d92f48ba8cbf9a8187f853677adc229..be64d662a776293d9e55e4690e21fc983a28ac65 100644 +index 882c45811..be64d662a 100644 --- a/src/models/kimi-k3.cpp +++ b/src/models/kimi-k3.cpp @@ -351,6 +351,35 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) : @@ -3401,7 +3401,7 @@ index 882c45811d92f48ba8cbf9a8187f853677adc229..be64d662a776293d9e55e4690e21fc98 const float eps_norm = hparams.f_norm_rms_eps; diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp -index 62719ba15f3f1268a449cd198e0a925c401911fe..5cda968252d133b3e1c12e7afaa836c1d717b748 100644 +index 62719ba15..5cda96825 100644 --- a/src/models/kimi-k31.cpp +++ b/src/models/kimi-k31.cpp @@ -412,7 +412,7 @@ ggml_tensor * llama_model_kimi_k31::graph::build_kda_conv1d( @@ -3432,7 +3432,7 @@ index 62719ba15f3f1268a449cd198e0a925c401911fe..5cda968252d133b3e1c12e7afaa836c1 const float eps_norm = hparams.f_norm_rms_eps; diff --git a/src/models/kimi-linear.cpp b/src/models/kimi-linear.cpp -index 81b147152c7e2d59f8557e7ff424d03eafd48256..778b39143ee7a963d498f9f6893d86b06ea0e2ac 100644 +index 81b147152..778b39143 100644 --- a/src/models/kimi-linear.cpp +++ b/src/models/kimi-linear.cpp @@ -203,13 +203,13 @@ static ggml_tensor * causal_conv1d(ggml_cgraph * gf, ggml_context * ctx0, ggml_t @@ -3503,7 +3503,7 @@ index 81b147152c7e2d59f8557e7ff424d03eafd48256..778b39143ee7a963d498f9f6893d86b0 // Output gating g2 = g_b(g_a(x)) ggml_tensor * cur_2d = ggml_reshape_2d(ctx0, cur, cur->ne[0], n_seq_tokens * n_seqs); diff --git a/src/models/lfm-base.cpp b/src/models/lfm-base.cpp -index 03bf1c063ede1f0795e06d087fada6e204024077..599e24bbf3f4edc3bcb9be1e4d1b4f568e92b4e9 100644 +index 03bf1c063..599e24bbf 100644 --- a/src/models/lfm-base.cpp +++ b/src/models/lfm-base.cpp @@ -37,7 +37,7 @@ ggml_tensor * llm_build_lfm_base::build_lfm_shortconv(const llama_memory_recurre @@ -3525,7 +3525,7 @@ index 03bf1c063ede1f0795e06d087fada6e204024077..599e24bbf3f4edc3bcb9be1e4d1b4f56 auto * conv_kernel = model.layers[il].shortconv.conv; auto * conv_out = ggml_ssm_conv(ctx0, bx, conv_kernel); diff --git a/src/models/mamba-base.cpp b/src/models/mamba-base.cpp -index 11ec79c76a0df5bcf588f08770b88dae1b2b3d7c..49b3eda7157830b966bd5ea0acf3bb3c7bf9e38f 100644 +index 11ec79c76..49b3eda71 100644 --- a/src/models/mamba-base.cpp +++ b/src/models/mamba-base.cpp @@ -36,7 +36,8 @@ ggml_tensor * llm_build_mamba_base::build_mamba_layer(llm_graph_input_rs * inp, @@ -3656,7 +3656,7 @@ index 11ec79c76a0df5bcf588f08770b88dae1b2b3d7c..49b3eda7157830b966bd5ea0acf3bb3c // grouped RMS norm if (model.layers[il].ssm_norm) { diff --git a/src/models/mimo2.cpp b/src/models/mimo2.cpp -index 06f0adf00f7cf0f34b35a59b56ea30cac016fc79..5f1512eddfd7e520c90176cab5ef1a3c199c686c 100644 +index 06f0adf00..5f1512edd 100644 --- a/src/models/mimo2.cpp +++ b/src/models/mimo2.cpp @@ -9,6 +9,9 @@ void llama_model_mimo2::load_arch_hparams(llama_model_loader & ml) { @@ -3698,7 +3698,7 @@ index 06f0adf00f7cf0f34b35a59b56ea30cac016fc79..5f1512eddfd7e520c90176cab5ef1a3c ggml_tensor * head_norm_w = layer.nextn.shared_head_norm ? layer.nextn.shared_head_norm diff --git a/src/models/minicpm3.cpp b/src/models/minicpm3.cpp -index 5c182d91d3f0e3bb00ba94c41d72805601618104..6db9fcc00de5aeb7d46375cc5b3c3a85dc986ee1 100644 +index 5c182d91d..6db9fcc00 100644 --- a/src/models/minicpm3.cpp +++ b/src/models/minicpm3.cpp @@ -171,8 +171,8 @@ llama_model_minicpm3::graph::graph(const llm_graph_params & params) : llm_graph_ @@ -3713,7 +3713,7 @@ index 5c182d91d3f0e3bb00ba94c41d72805601618104..6db9fcc00de5aeb7d46375cc5b3c3a85 cur = build_attn(inp_attn, diff --git a/src/models/minimax-01.cpp b/src/models/minimax-01.cpp -index 14df1bfb4c676ffd78d0ec691bcf45522c14b0da..eed269ac59a73ae28a54b374069a17da3d4aaccb 100644 +index 14df1bfb4..eed269ac5 100644 --- a/src/models/minimax-01.cpp +++ b/src/models/minimax-01.cpp @@ -273,7 +273,7 @@ llama_model_minimax_01::graph::graph(const llm_graph_params & params) : llm_grap @@ -3751,7 +3751,7 @@ index 14df1bfb4c676ffd78d0ec691bcf45522c14b0da..eed269ac59a73ae28a54b374069a17da qkv = ggml_cont(ctx0, ggml_permute(ctx0, qkv, 0, 2, 1, 3)); cb(qkv, "qkv_permuted", il); diff --git a/src/models/minimax-m3.cpp b/src/models/minimax-m3.cpp -index 92c7ca757e0479752e6d7541597e16157d75b7d4..af245931e4462bb80fc8afc643c632bfc0f7a950 100644 +index 92c7ca757..af245931e 100644 --- a/src/models/minimax-m3.cpp +++ b/src/models/minimax-m3.cpp @@ -18,11 +18,13 @@ void llama_model_minimax_m3::load_arch_hparams(llama_model_loader & ml) { @@ -3854,7 +3854,7 @@ index 92c7ca757e0479752e6d7541597e16157d75b7d4..af245931e4462bb80fc8afc643c632bf msa_mf = ggml_cast(ctx0, msa_kqm, GGML_TYPE_F32); } diff --git a/src/models/models.h b/src/models/models.h -index 128722e69d2ced73080c2370c9652a83e3d43efe..322f2286ef5a047d9d6848b13d080ceb1c16ff16 100644 +index 128722e69..322f2286e 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -3310,6 +3310,11 @@ struct llama_model_kimi_k3 : public llama_model_base { @@ -3870,7 +3870,7 @@ index 128722e69d2ced73080c2370c9652a83e3d43efe..322f2286ef5a047d9d6848b13d080ceb llm_graph_input_attn_k * inp_attn_k, llm_graph_input_attn_kv * inp_attn_kv, diff --git a/src/models/nemotron-h-moe.cpp b/src/models/nemotron-h-moe.cpp -index 05a02322315f8f1a080a10215908e8aa99bfb887..90d07963c1d5ee19aeff6f22f60d3cf7f978d639 100644 +index 05a023223..90d07963c 100644 --- a/src/models/nemotron-h-moe.cpp +++ b/src/models/nemotron-h-moe.cpp @@ -22,8 +22,13 @@ llama_model_nemotron_h_moe::graph_mtp::graph_mtp(const llm_graph_params & params @@ -3950,7 +3950,7 @@ index 05a02322315f8f1a080a10215908e8aa99bfb887..90d07963c1d5ee19aeff6f22f60d3cf7 res->t_logits = cur; diff --git a/src/models/nemotron-h.cpp b/src/models/nemotron-h.cpp -index 3b8760343e3cf08ca777f3bb1cc2865d8c48287a..813c10954061222ba0961a495ae724810242118b 100644 +index 3b8760343..813c10954 100644 --- a/src/models/nemotron-h.cpp +++ b/src/models/nemotron-h.cpp @@ -64,14 +64,16 @@ void llama_model_nemotron_h::load_arch_tensors(llama_model_loader & ml) { @@ -3984,7 +3984,7 @@ index 3b8760343e3cf08ca777f3bb1cc2865d8c48287a..813c10954061222ba0961a495ae72481 layer.ffn_latent_up = create_tensor(tn(LLM_TENSOR_FFN_LATENT_UP, "weight", i), {moe_n_embd, n_embd}, mtp_flags | TENSOR_NOT_REQUIRED); layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, moe_n_embd, n_expert}, mtp_flags); diff --git a/src/models/qwen2moe.cpp b/src/models/qwen2moe.cpp -index abb2f5a8c510c5ad14a2a7e109b70684c10b8f32..56f137b97304abc9d1942cfaf25e6aa05a9b23c1 100644 +index abb2f5a8c..56f137b97 100644 --- a/src/models/qwen2moe.cpp +++ b/src/models/qwen2moe.cpp @@ -20,7 +20,10 @@ void llama_model_qwen2moe::load_arch_tensors(llama_model_loader &) { @@ -4000,7 +4000,7 @@ index abb2f5a8c510c5ad14a2a7e109b70684c10b8f32..56f137b97304abc9d1942cfaf25e6aa0 for (int i = 0; i < n_layer; ++i) { auto & layer = layers[i]; diff --git a/src/models/qwen35.cpp b/src/models/qwen35.cpp -index 542e150cbe086984aa884ae8a2eb5388ea652bb5..883e3c03460375dde17a86809591decc84f50557 100644 +index 542e150cb..883e3c034 100644 --- a/src/models/qwen35.cpp +++ b/src/models/qwen35.cpp @@ -418,7 +418,7 @@ ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear( @@ -4021,7 +4021,7 @@ index 542e150cbe086984aa884ae8a2eb5388ea652bb5..883e3c03460375dde17a86809591decc cb(k_conv, "k_conv", il); cb(v_conv, "v_conv", il); diff --git a/src/models/qwen35moe.cpp b/src/models/qwen35moe.cpp -index cf6dd9e747219ec86e11f791092eb65dc94ec8c2..1b926691a406fd1cf7fa80967bfe482be550a3f3 100644 +index cf6dd9e74..1b926691a 100644 --- a/src/models/qwen35moe.cpp +++ b/src/models/qwen35moe.cpp @@ -393,7 +393,7 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_attn_linear( @@ -4042,7 +4042,7 @@ index cf6dd9e747219ec86e11f791092eb65dc94ec8c2..1b926691a406fd1cf7fa80967bfe482b cb(k_conv, "k_conv", il); cb(v_conv, "v_conv", il); diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp -index 2c093cd09ff3c33e869924e166dea37bf521063f..8ddd339b383d2271a48d15b779a636bc2dfaebd8 100644 +index 2c093cd09..8ddd339b3 100644 --- a/src/models/qwen3next.cpp +++ b/src/models/qwen3next.cpp @@ -264,6 +264,7 @@ ggml_tensor * llama_model_qwen3next::graph::build_layer_attn( @@ -4079,7 +4079,7 @@ index 2c093cd09ff3c33e869924e166dea37bf521063f..8ddd339b383d2271a48d15b779a636bc cb(k_conv, "k_conv", il); cb(v_conv, "v_conv", il); diff --git a/src/models/qwen3vl.cpp b/src/models/qwen3vl.cpp -index 3873cb5ea36063d531ed3cb26fe226b74f92378d..2c31f2090668b45129279c2db8a7a64e577088f6 100644 +index 3873cb5ea..2c31f2090 100644 --- a/src/models/qwen3vl.cpp +++ b/src/models/qwen3vl.cpp @@ -169,7 +169,8 @@ llama_model_qwen3vl::graph::graph(const llm_graph_params & params) : llm_graph_c @@ -4093,7 +4093,7 @@ index 3873cb5ea36063d531ed3cb26fe226b74f92378d..2c31f2090668b45129279c2db8a7a64e if (n_vocab_in > n_vocab_out) { // case: output head smaller than vocab, see load_arch_tensors diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp -index 6f672e9e2049db9594307152568d84004e7099db..a3cd1cb97f4ad80806144c4a19924e752c72e22b 100644 +index 6f672e9e2..a3cd1cb97 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -805,6 +805,15 @@ llama_model_qwen4exp::llm_graph_input_kpool * llama_model_qwen4exp::graph::build @@ -4148,7 +4148,7 @@ index 6f672e9e2049db9594307152568d84004e7099db..a3cd1cb97f4ad80806144c4a19924e75 res->add_input(std::move(ple_inp)); diff --git a/src/models/rwkv6-base.cpp b/src/models/rwkv6-base.cpp -index 7eb917d1de7d04cb2f767670b546d963fee2a19e..8c88dd6dc02c9740e8964772dfb1e6814498b812 100644 +index 7eb917d1d..8c88dd6dc 100644 --- a/src/models/rwkv6-base.cpp +++ b/src/models/rwkv6-base.cpp @@ -129,7 +129,7 @@ ggml_tensor * llm_build_rwkv6_base::build_rwkv6_time_mix(llm_graph_input_rs * in @@ -4176,7 +4176,7 @@ index 7eb917d1de7d04cb2f767670b546d963fee2a19e..8c88dd6dc02c9740e8964772dfb1e681 if (!is_qrwkv) { // group norm with head_count groups diff --git a/src/models/rwkv6.cpp b/src/models/rwkv6.cpp -index 2a6ac3769f4440d7d711b327acd5e27814fc2f53..ea92a377df830755c3c50c414fa792089bbcae1e 100644 +index 2a6ac3769..ea92a377d 100644 --- a/src/models/rwkv6.cpp +++ b/src/models/rwkv6.cpp @@ -62,7 +62,7 @@ void llama_model_rwkv6::load_arch_tensors(llama_model_loader &) { @@ -4189,7 +4189,7 @@ index 2a6ac3769f4440d7d711b327acd5e27814fc2f53..ea92a377df830755c3c50c414fa79208 layer.time_mix_first = create_tensor(tn(LLM_TENSOR_TIME_MIX_FIRST, "weight", i), {head_size, n_embd / head_size}, 0); layer.time_mix_decay = create_tensor(tn(LLM_TENSOR_TIME_MIX_DECAY, "weight", i), {n_embd}, 0); diff --git a/src/models/rwkv7-base.cpp b/src/models/rwkv7-base.cpp -index fdcead7c063e93590bf5b6727f91be6e27b77d7e..94012ec5a9b7030adae33b99c2a5d33bf70b0cce 100644 +index fdcead7c0..94012ec5a 100644 --- a/src/models/rwkv7-base.cpp +++ b/src/models/rwkv7-base.cpp @@ -101,16 +101,17 @@ ggml_tensor * llm_build_rwkv7_base::build_rwkv7_time_mix(llm_graph_input_rs * in @@ -4215,7 +4215,7 @@ index fdcead7c063e93590bf5b6727f91be6e27b77d7e..94012ec5a9b7030adae33b99c2a5d33b if (layer.time_mix_ln && layer.time_mix_ln_b) { // group norm with head_count groups diff --git a/src/skippy/stage_realization.cpp b/src/skippy/stage_realization.cpp -index 4a91e986b7383b52c10e198babb502074e65dcb5..481528345e1e9f936ab159cd78e6c901f0b794ec 100644 +index 4a91e986b..481528345 100644 --- a/src/skippy/stage_realization.cpp +++ b/src/skippy/stage_realization.cpp @@ -277,14 +277,13 @@ void skippy_realize_stage_graph( @@ -4240,3 +4240,6 @@ index 4a91e986b7383b52c10e198babb502074e65dcb5..481528345e1e9f936ab159cd78e6c901 } std::unordered_map replacements; +-- +2.56.0 + diff --git a/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch b/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch index 74b86641..0c057ae9 100644 --- a/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch +++ b/llama_cpp/patches/0005-build-skippy-wire-native-runtime-and-backend-support.patch @@ -1,4 +1,4 @@ -From ece37662ff992bdbb02f6796399445ec875619db Mon Sep 17 00:00:00 2001 +From 72ec169df846d94fb143c9c26e6e6c0b07225e1c Mon Sep 17 00:00:00 2001 From: James Dumay Date: Tue, 13 Oct 2026 22:06:42 +1100 Subject: [PATCH] build(skippy): wire native runtime and backend support @@ -42,7 +42,7 @@ Subject: [PATCH] build(skippy): wire native runtime and backend support create mode 100644 ggml/src/ggml-metal/kernels/cachegen.metal diff --git a/CMakeLists.txt b/CMakeLists.txt -index 93543defd9fd8498ae2b660c8d1b6c7077b1a6b8..190e3f31f4873b55d968704904e7e0f9ed373e66 100644 +index 93543defd..190e3f31f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,18 @@ cmake_minimum_required(VERSION 3.14...3.28) # for add_link_options and implicit @@ -84,7 +84,7 @@ index 93543defd9fd8498ae2b660c8d1b6c7077b1a6b8..190e3f31f4873b55d968704904e7e0f9 if (LLAMA_BUILD_COMMON) install(TARGETS llama-common LIBRARY) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt -index c454f6bb3c60ea339b2f8f5ed2177056691eae2a..3c2b9b7ba752008c4c743369db74ff9d309f1f3d 100644 +index c454f6bb3..3c2b9b7ba 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -90,10 +90,7 @@ add_library(${TARGET} @@ -159,7 +159,7 @@ index c454f6bb3c60ea339b2f8f5ed2177056691eae2a..3c2b9b7ba752008c4c743369db74ff9d if (CMAKE_SYSTEM_NAME MATCHES "AIX") diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp -index d3e0a7f1102cbd806075a57f6d5f4f9bb977d2c8..65e4f9b3b82839b2c827d08d9cb9d0d42cd59aba 100644 +index d3e0a7f11..65e4f9b3b 100644 --- a/common/chat-auto-parser-generator.cpp +++ b/common/chat-auto-parser-generator.cpp @@ -13,6 +13,18 @@ @@ -247,7 +247,7 @@ index d3e0a7f1102cbd806075a57f6d5f4f9bb977d2c8..65e4f9b3b82839b2c827d08d9cb9d0d4 if (!arguments.start.empty()) { diff --git a/common/chat-diff-analyzer.cpp b/common/chat-diff-analyzer.cpp -index a7e370578fd9290f9516b87dc5f0515820748629..39ffa20f1237560369296c80297e5c1f1d5d4df5 100644 +index a7e370578..39ffa20f1 100644 --- a/common/chat-diff-analyzer.cpp +++ b/common/chat-diff-analyzer.cpp @@ -484,7 +484,8 @@ void analyze_reasoning::compare_reasoning_presence() { @@ -288,7 +288,7 @@ index a7e370578fd9290f9516b87dc5f0515820748629..39ffa20f1237560369296c80297e5c1f template_params params_content_only; diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp -index 51c64abec3cad2677373459fc6da43bf67b96adf..556688f1cf4e1784e082646fdf33ea2932205064 100644 +index 51c64abec..556688f1c 100644 --- a/common/chat-peg-parser.cpp +++ b/common/chat-peg-parser.cpp @@ -393,11 +393,12 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) { @@ -348,7 +348,7 @@ index 51c64abec3cad2677373459fc6da43bf67b96adf..556688f1cf4e1784e082646fdf33ea29 // Build ID parsers if keys are provided common_peg_parser id_parser = eps(); diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h -index 62ae5b8fe20e61d8c47f03842f3fc860d0d96506..a99c4e03781dfd6a935ef7bb9726adc859fff895 100644 +index 62ae5b8fe..a99c4e037 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -5,6 +5,7 @@ @@ -368,7 +368,7 @@ index 62ae5b8fe20e61d8c47f03842f3fc860d0d96506..a99c4e03781dfd6a935ef7bb9726adc8 common_peg_parser permute(const std::string & rule_prefix, const std::vector & parsers); diff --git a/common/chat.cpp b/common/chat.cpp -index 9e810d6d098b3990a21b8e9aa6e3a8122b65720c..c144697de6ee5b3485c7a60066bbbbec8bbd9e39 100644 +index 9e810d6d0..c144697de 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -204,6 +204,11 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const { @@ -450,7 +450,7 @@ index 9e810d6d098b3990a21b8e9aa6e3a8122b65720c..c144697de6ee5b3485c7a60066bbbbec if (!template_tool_use_src.empty()) { default_template_src = template_tool_use_src; diff --git a/common/chat.h b/common/chat.h -index f80ef4ed203b981e109c17473882a12dc1e836ef..c799a04ee0990f452c46923413b5933d89d69011 100644 +index f80ef4ed2..c799a04ee 100644 --- a/common/chat.h +++ b/common/chat.h @@ -98,6 +98,9 @@ struct common_chat_msg { @@ -474,7 +474,7 @@ index f80ef4ed203b981e109c17473882a12dc1e836ef..c799a04ee0990f452c46923413b5933d bool operator!=(const common_chat_msg & other) const { return !(*this == other); } diff --git a/common/ngram-cache.cpp b/common/ngram-cache.cpp -index 419a0ebc9833bde8e660dd582ae0c0273924066a..2c844ba2fd06817f315b7a527309813faad80102 100644 +index 419a0ebc9..2c844ba2f 100644 --- a/common/ngram-cache.cpp +++ b/common/ngram-cache.cpp @@ -1,14 +1,161 @@ @@ -681,7 +681,7 @@ index 419a0ebc9833bde8e660dd582ae0c0273924066a..2c844ba2fd06817f315b7a527309813f if (drafted_token == LLAMA_TOKEN_NULL) { drafted_token = try_draft(nc_static, ngram_static); diff --git a/common/peg-parser.cpp b/common/peg-parser.cpp -index 924289097752d23d05cd344f4b27673e82a71f19..8de366170c33d2fbac6c5a49e01526c3e8ba8bb4 100644 +index 924289097..8de366170 100644 --- a/common/peg-parser.cpp +++ b/common/peg-parser.cpp @@ -2255,6 +2255,401 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo @@ -1087,7 +1087,7 @@ index 924289097752d23d05cd344f4b27673e82a71f19..8de366170c33d2fbac6c5a49e01526c3 common_peg_parser_builder builder; builder.set_root(fn(builder)); diff --git a/common/peg-parser.h b/common/peg-parser.h -index b7e97083b386d9880b253e66125c961ac477f085..fbf4b6f7b91a0a30a9efc0cbe434b30b4c2e63d1 100644 +index b7e97083b..fbf4b6f7b 100644 --- a/common/peg-parser.h +++ b/common/peg-parser.h @@ -404,6 +404,14 @@ class common_peg_arena { @@ -1106,7 +1106,7 @@ index b7e97083b386d9880b253e66125c961ac477f085..fbf4b6f7b91a0a30a9efc0cbe434b30b private: diff --git a/common/reasoning-budget.cpp b/common/reasoning-budget.cpp -index ac2cd261db08b0726a8c57385986483b0f2cd83e..674bb914d5de942e18c0f0fb270d91c81f21406f 100644 +index ac2cd261d..674bb914d 100644 --- a/common/reasoning-budget.cpp +++ b/common/reasoning-budget.cpp @@ -1,9 +1,4 @@ @@ -1408,7 +1408,7 @@ index ac2cd261db08b0726a8c57385986483b0f2cd83e..674bb914d5de942e18c0f0fb270d91c8 return true; } diff --git a/common/reasoning-budget.h b/common/reasoning-budget.h -index 1b89a04c42e8056d6450d3266e4f0c1e2a561d2e..85d5c35dc42e95dbed1a489216f28708230fd54d 100644 +index 1b89a04c4..85d5c35dc 100644 --- a/common/reasoning-budget.h +++ b/common/reasoning-budget.h @@ -2,8 +2,6 @@ @@ -1450,7 +1450,7 @@ index 1b89a04c42e8056d6450d3266e4f0c1e2a561d2e..85d5c35dc42e95dbed1a489216f28708 +LLAMA_API bool common_reasoning_budget_force(struct llama_sampler * smpl); diff --git a/common/stage-chat.cpp b/common/stage-chat.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..c3362e2a7f9a1d233ae734dc0329bd79c560da6b +index 000000000..c3362e2a7 --- /dev/null +++ b/common/stage-chat.cpp @@ -0,0 +1,363 @@ @@ -1818,7 +1818,7 @@ index 0000000000000000000000000000000000000000..c3362e2a7f9a1d233ae734dc0329bd79 + return skippy_common_success(out_error); +} diff --git a/ggml/cmake/common.cmake b/ggml/cmake/common.cmake -index 39c1fbb489820bbd87256e3213a08c799d954973..bc4790fb876b8d391164fcadaac7f4783669ff60 100644 +index 39c1fbb48..bc4790fb8 100644 --- a/ggml/cmake/common.cmake +++ b/ggml/cmake/common.cmake @@ -99,8 +99,13 @@ function(ggml_cuda_fattn_instances DIR OUT_SRCS) @@ -1838,7 +1838,7 @@ index 39c1fbb489820bbd87256e3213a08c799d954973..bc4790fb876b8d391164fcadaac7f478 foreach (TYPE_K IN LISTS FA_TYPES) if ("${TYPE_K}-${TYPE_V}" IN_LIST FA_COMBINATIONS) diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h -index 58e771d42180ef92eaa79018d635a33add61ea44..60096c0df2d86f735355acb9744d3c1e4115c711 100644 +index 58e771d42..60096c0df 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -243,6 +243,33 @@ extern "C" { @@ -1876,7 +1876,7 @@ index 58e771d42180ef92eaa79018d635a33add61ea44..60096c0df2d86f735355acb9744d3c1e // Backend registry // diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp -index 9a12391bb6e36aa6e45939e4e7a82c6da8198f35..c8c05e442267e3b40d5afedefee364911fb82486 100644 +index 9a12391bb..c8c05e442 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -1500,14 +1500,30 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra @@ -1926,7 +1926,7 @@ index 9a12391bb6e36aa6e45939e4e7a82c6da8198f35..c8c05e442267e3b40d5afedefee36491 sched->splits = (ggml_backend_sched_split *) calloc(initial_splits_capacity, sizeof(sched->splits[0])); diff --git a/ggml/src/ggml-cuda/cachegen.cu b/ggml/src/ggml-cuda/cachegen.cu new file mode 100644 -index 0000000000000000000000000000000000000000..394c1d45ed6961466c41b40a8022a32c8b78d199 +index 000000000..394c1d45e --- /dev/null +++ b/ggml/src/ggml-cuda/cachegen.cu @@ -0,0 +1,223 @@ @@ -2155,7 +2155,7 @@ index 0000000000000000000000000000000000000000..394c1d45ed6961466c41b40a8022a32c +#endif // !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/cachegen.cuh b/ggml/src/ggml-cuda/cachegen.cuh new file mode 100644 -index 0000000000000000000000000000000000000000..7118c9aa9617988b26a0f14d57dda6855346e54b +index 000000000..7118c9aa9 --- /dev/null +++ b/ggml/src/ggml-cuda/cachegen.cuh @@ -0,0 +1,27 @@ @@ -2187,7 +2187,7 @@ index 0000000000000000000000000000000000000000..7118c9aa9617988b26a0f14d57dda685 + +#endif // !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu -index 8bae601333115f689e18b25bbae0c0f9fc8574d0..4700191f7754f1975494130141c7244ac2b2dda2 100644 +index 8bae60133..4700191f7 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -12,6 +12,7 @@ @@ -2577,7 +2577,7 @@ index 8bae601333115f689e18b25bbae0c0f9fc8574d0..4700191f7754f1975494130141c7244a } diff --git a/ggml/src/ggml-cuda/vendors/hip.h b/ggml/src/ggml-cuda/vendors/hip.h -index a97233c1e658609d1e5090caf7a01f8f1c4137e5..1ccfe1669da4ee6f9da72cb02a2cce20c34eb1b0 100644 +index a97233c1e..1ccfe1669 100644 --- a/ggml/src/ggml-cuda/vendors/hip.h +++ b/ggml/src/ggml-cuda/vendors/hip.h @@ -32,6 +32,12 @@ typedef uint64_t ggml_cuda_thread_mask_t; @@ -2594,7 +2594,7 @@ index a97233c1e658609d1e5090caf7a01f8f1c4137e5..1ccfe1669da4ee6f9da72cb02a2cce20 #define cublasCreate hipblasCreate #define cublasDestroy hipblasDestroy diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt -index 0ecc07c45fff692ea42cfb8acc7b24ca119cf0c3..14168ffec1516f46f2f0f4cfd2585643bc3fc159 100644 +index 0ecc07c45..14168ffec 100644 --- a/ggml/src/ggml-metal/CMakeLists.txt +++ b/ggml/src/ggml-metal/CMakeLists.txt @@ -37,6 +37,7 @@ set(METALLIB_KERNELS_FA_SHARED @@ -2606,7 +2606,7 @@ index 0ecc07c45fff692ea42cfb8acc7b24ca119cf0c3..14168ffec1516f46f2f0f4cfd2585643 kernels/fa_f16.metal kernels/fa_f32.metal diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h -index c370ce9a798cd8097ec0f79650ba22ba6b16f187..009b4ce2ef4dc9757a061d0e7784a2395c4a0a43 100644 +index c370ce9a7..009b4ce2e 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -1,6 +1,7 @@ @@ -2631,7 +2631,7 @@ index c370ce9a798cd8097ec0f79650ba22ba6b16f187..009b4ce2ef4dc9757a061d0e7784a239 } #endif diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index f7f05b6bbcbf3e621c411ed3f75e7a8563a69466..b03b925c650ca5ab45c9f6b49280a5e8742a8fcf 100644 +index f7f05b6bb..b03b925c6 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -11,6 +11,8 @@ @@ -3253,7 +3253,7 @@ index f7f05b6bbcbf3e621c411ed3f75e7a8563a69466..b03b925c650ca5ab45c9f6b49280a5e8 + return true; +} diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp -index bcd70c797f54b41eb9c6c291c6282a22a30719f5..ad75738511e1ea131b394c6953d57b7cafbdeef4 100644 +index bcd70c797..ad7573851 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -1021,6 +1021,9 @@ static void * ggml_backend_metal_get_proc_address(ggml_backend_reg_t reg, const @@ -3268,7 +3268,7 @@ index bcd70c797f54b41eb9c6c291c6282a22a30719f5..ad75738511e1ea131b394c6953d57b7c } diff --git a/ggml/src/ggml-metal/kernels/cachegen.metal b/ggml/src/ggml-metal/kernels/cachegen.metal new file mode 100644 -index 0000000000000000000000000000000000000000..728899e4b43bbdd273c6f9b562ecce49f59918c7 +index 000000000..728899e4b --- /dev/null +++ b/ggml/src/ggml-metal/kernels/cachegen.metal @@ -0,0 +1,195 @@ @@ -3468,7 +3468,7 @@ index 0000000000000000000000000000000000000000..728899e4b43bbdd273c6f9b562ecce49 + } +} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 426c487411eeead95e75076f936ab4c1e2518e2a..2bc7d6f6e49c99171722661daf308d435d260b6a 100644 +index 426c48741..2bc7d6f6e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,4 +1,5 @@ @@ -4174,7 +4174,7 @@ index 426c487411eeead95e75076f936ab4c1e2518e2a..2bc7d6f6e49c99171722661daf308d43 + target_link_libraries(llama PRIVATE ${SKIPPY_ACCELERATE_FRAMEWORK}) +endif() diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h -index 269e78cc40f5b43086973aa0dad3b7e561afe208..7ca00190cf7a7e39b8f0660ad48a997035d8a2a8 100644 +index 269e78cc4..7ca00190c 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -75,6 +75,7 @@ struct mtmd_audio_mel_config { @@ -4186,7 +4186,7 @@ index 269e78cc40f5b43086973aa0dad3b7e561afe208..7ca00190cf7a7e39b8f0660ad48a9970 const mtmd_audio_cache * cache = nullptr; diff --git a/tools/mtmd/mtmd-helper.cpp b/tools/mtmd/mtmd-helper.cpp -index 165936d80c1a79b1ab5f1c5c5f649f209889975b..9a27d955abe90557e3c504b29f0de7be5f1f95de 100644 +index 165936d80..9a27d955a 100644 --- a/tools/mtmd/mtmd-helper.cpp +++ b/tools/mtmd/mtmd-helper.cpp @@ -132,6 +132,11 @@ int32_t mtmd_helper_decode_image_chunk( @@ -4279,7 +4279,7 @@ index 165936d80c1a79b1ab5f1c5c5f649f209889975b..9a27d955abe90557e3c504b29f0de7be LOG_ERR("failed to decode %s\n", name); return ret; diff --git a/tools/mtmd/mtmd-helper.h b/tools/mtmd/mtmd-helper.h -index c20cb0a20bbd3ca672517a4d03cb2d4160e372dc..6f8c7475fa41a9a2ca5912b95405dd0ed6c655be 100644 +index c20cb0a20..6f8c7475f 100644 --- a/tools/mtmd/mtmd-helper.h +++ b/tools/mtmd/mtmd-helper.h @@ -183,6 +183,35 @@ MTMD_API int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx, @@ -4319,7 +4319,7 @@ index c20cb0a20bbd3ca672517a4d03cb2d4160e372dc..6f8c7475fa41a9a2ca5912b95405dd0e struct mtmd_helper_embd_batch { int32_t n_tokens; diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp -index 640950c5c8324987a1fcbb157477887af66e9845..4ea2217d04bb1d4d5de91cc05b81ac70c94e5b0a 100644 +index 640950c5c..4ea2217d0 100644 --- a/tools/mtmd/mtmd-subcontext.cpp +++ b/tools/mtmd/mtmd-subcontext.cpp @@ -323,6 +323,10 @@ bool mtmd_audio_log_mel(const mtmd_audio_mel_config & config, const float * samp @@ -4333,3 +4333,6 @@ index 640950c5c8324987a1fcbb157477887af66e9845..4ea2217d04bb1d4d5de91cc05b81ac70 if (config.use_magnitude) { cur = ggml_sqrt(ctx0, cur); } +-- +2.56.0 + diff --git a/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch b/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch index 95ac9b0b..28dbee65 100644 --- a/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch +++ b/llama_cpp/patches/0006-test-skippy-cover-live-graph-and-state-contracts.patch @@ -1,9 +1,12 @@ -From 62df298ca530d31b8772ace3f538ec549317d451 Mon Sep 17 00:00:00 2001 +From d2fc9508316b2aad208eedc74ba54f1764b7050c 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 +Co-authored-by: Melkor --- + src/CMakeLists.txt | 9 + + 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 ++++++++++ @@ -42,7 +45,8 @@ Subject: [PATCH] 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, 10270 insertions(+), 30 deletions(-) + 40 files changed, 10524 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,9 +80,280 @@ Subject: [PATCH] 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..efe8d28ba +--- /dev/null ++++ b/src/skippy/tests/async_state.cpp +@@ -0,0 +1,245 @@ ++#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_pooled_embedding_accounting(const skippy_model * model) { ++ auto params = llama_context_default_params(); ++ params.n_ctx = 64; ++ params.n_batch = 64; ++ params.n_ubatch = 64; ++ params.n_threads = 1; ++ params.n_threads_batch = 1; ++ params.embeddings = true; ++ params.pooling_type = LLAMA_POOLING_TYPE_MEAN; ++ params.no_perf = false; ++ llama_context * ctx = llama_init_from_model(model->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; ++ 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); ++ 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); ++} ++ ++} // 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); ++ if (std::strcmp(mode, "all") == 0) { ++ test_pooled_embedding_accounting(model); ++ } ++ 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 0000000000000000000000000000000000000000..84da82c91140944ce7c2b4e6cb9aaa7f4d1b555c +index 000000000..84da82c91 --- /dev/null +++ b/src/skippy/tests/cast_destination_regression.h @@ -0,0 +1,27 @@ @@ -111,7 +386,7 @@ index 0000000000000000000000000000000000000000..84da82c91140944ce7c2b4e6cb9aaa7f +} diff --git a/src/skippy/tests/embedding_input_regression.h b/src/skippy/tests/embedding_input_regression.h new file mode 100644 -index 0000000000000000000000000000000000000000..803489be0755fc4e731a9efe9afcf3bf4ebaa889 +index 000000000..803489be0 --- /dev/null +++ b/src/skippy/tests/embedding_input_regression.h @@ -0,0 +1,91 @@ @@ -208,7 +483,7 @@ index 0000000000000000000000000000000000000000..803489be0755fc4e731a9efe9afcf3bf +} diff --git a/src/skippy/tests/graph_build_inputs.cpp b/src/skippy/tests/graph_build_inputs.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..f1a028195e12723dc09efd6b2dcdddaebd4251a4 +index 000000000..f1a028195 --- /dev/null +++ b/src/skippy/tests/graph_build_inputs.cpp @@ -0,0 +1,948 @@ @@ -1162,7 +1437,7 @@ index 0000000000000000000000000000000000000000..f1a028195e12723dc09efd6b2dcdddae +} diff --git a/src/skippy/tests/graph_contract_cases.cmake b/src/skippy/tests/graph_contract_cases.cmake new file mode 100644 -index 0000000000000000000000000000000000000000..4ee862411340737eaf63fe9bbd3e3268b444d413 +index 000000000..4ee862411 --- /dev/null +++ b/src/skippy/tests/graph_contract_cases.cmake @@ -0,0 +1,120 @@ @@ -1288,7 +1563,7 @@ index 0000000000000000000000000000000000000000..4ee862411340737eaf63fe9bbd3e3268 + FIXTURES_REQUIRED contract-glm53-synthetic TIMEOUT 900) diff --git a/src/skippy/tests/graph_contract_checks.h b/src/skippy/tests/graph_contract_checks.h new file mode 100644 -index 0000000000000000000000000000000000000000..69844b1f896bf4b4b40cc5202246f195b5668220 +index 000000000..69844b1f8 --- /dev/null +++ b/src/skippy/tests/graph_contract_checks.h @@ -0,0 +1,138 @@ @@ -1432,7 +1707,7 @@ index 0000000000000000000000000000000000000000..69844b1f896bf4b4b40cc5202246f195 +} diff --git a/src/skippy/tests/graph_contract_models.cpp b/src/skippy/tests/graph_contract_models.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..5dd31d608d3b35896992a24eabb984893505ddd9 +index 000000000..5dd31d608 --- /dev/null +++ b/src/skippy/tests/graph_contract_models.cpp @@ -0,0 +1,223 @@ @@ -1661,7 +1936,7 @@ index 0000000000000000000000000000000000000000..5dd31d608d3b35896992a24eabb98489 +} diff --git a/src/skippy/tests/hardware_application_probe.cpp b/src/skippy/tests/hardware_application_probe.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..cfc17776b8f58f26654a160d4ee75deb88f4ee67 +index 000000000..cfc17776b --- /dev/null +++ b/src/skippy/tests/hardware_application_probe.cpp @@ -0,0 +1,78 @@ @@ -1745,7 +2020,7 @@ index 0000000000000000000000000000000000000000..cfc17776b8f58f26654a160d4ee75deb +} diff --git a/src/skippy/tests/input_capabilities.cpp b/src/skippy/tests/input_capabilities.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..e4902c3d26ef99e1618630726bfc4132470ec7fa +index 000000000..e4902c3d2 --- /dev/null +++ b/src/skippy/tests/input_capabilities.cpp @@ -0,0 +1,80 @@ @@ -1831,7 +2106,7 @@ index 0000000000000000000000000000000000000000..e4902c3d26ef99e1618630726bfc4132 +} diff --git a/src/skippy/tests/input_leaf_state_regression.h b/src/skippy/tests/input_leaf_state_regression.h new file mode 100644 -index 0000000000000000000000000000000000000000..33d3faca9f56b6926fcd7bb05e4470b2cd53b592 +index 000000000..33d3faca9 --- /dev/null +++ b/src/skippy/tests/input_leaf_state_regression.h @@ -0,0 +1,49 @@ @@ -1886,7 +2161,7 @@ index 0000000000000000000000000000000000000000..33d3faca9f56b6926fcd7bb05e4470b2 +} diff --git a/src/skippy/tests/live_graph_reference.h b/src/skippy/tests/live_graph_reference.h new file mode 100644 -index 0000000000000000000000000000000000000000..73129bf076f48002e9f7010fbfef16c9a438f654 +index 000000000..73129bf07 --- /dev/null +++ b/src/skippy/tests/live_graph_reference.h @@ -0,0 +1,194 @@ @@ -2086,7 +2361,7 @@ index 0000000000000000000000000000000000000000..73129bf076f48002e9f7010fbfef16c9 +}; diff --git a/src/skippy/tests/log_gate.h b/src/skippy/tests/log_gate.h new file mode 100644 -index 0000000000000000000000000000000000000000..afafe0565442231095fd877319f2304bf6799ea9 +index 000000000..afafe0565 --- /dev/null +++ b/src/skippy/tests/log_gate.h @@ -0,0 +1,138 @@ @@ -2230,7 +2505,7 @@ index 0000000000000000000000000000000000000000..afafe0565442231095fd877319f2304b +} // namespace skippy::log_gate diff --git a/src/skippy/tests/noalloc_graph_planning.cpp b/src/skippy/tests/noalloc_graph_planning.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..7470f33093c372d6ba12826d1f45500d0a527ea0 +index 000000000..7470f3309 --- /dev/null +++ b/src/skippy/tests/noalloc_graph_planning.cpp @@ -0,0 +1,1139 @@ @@ -3375,7 +3650,7 @@ index 0000000000000000000000000000000000000000..7470f33093c372d6ba12826d1f45500d +} diff --git a/src/skippy/tests/profile_residency.cpp b/src/skippy/tests/profile_residency.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..c63f518c6628b7258babf9b077ec36da71367e3a +index 000000000..c63f518c6 --- /dev/null +++ b/src/skippy/tests/profile_residency.cpp @@ -0,0 +1,232 @@ @@ -3613,7 +3888,7 @@ index 0000000000000000000000000000000000000000..c63f518c6628b7258babf9b077ec36da +} diff --git a/src/skippy/tests/renamed_multishard_planning.cpp b/src/skippy/tests/renamed_multishard_planning.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..720ba457a714f33af14b6a234f6b563da5e5846d +index 000000000..720ba457a --- /dev/null +++ b/src/skippy/tests/renamed_multishard_planning.cpp @@ -0,0 +1,1667 @@ @@ -5286,7 +5561,7 @@ index 0000000000000000000000000000000000000000..720ba457a714f33af14b6a234f6b563d +} diff --git a/src/skippy/tests/residual_checkpoint_regression.h b/src/skippy/tests/residual_checkpoint_regression.h new file mode 100644 -index 0000000000000000000000000000000000000000..31734bf5660b7b3c6db41785425e6eb2b2da3e44 +index 000000000..31734bf56 --- /dev/null +++ b/src/skippy/tests/residual_checkpoint_regression.h @@ -0,0 +1,52 @@ @@ -5344,7 +5619,7 @@ index 0000000000000000000000000000000000000000..31734bf5660b7b3c6db41785425e6eb2 +} diff --git a/src/skippy/tests/runtime_events.cpp b/src/skippy/tests/runtime_events.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d764514ed16b47c3177cb3641d7686a9de7e05ba +index 000000000..d764514ed --- /dev/null +++ b/src/skippy/tests/runtime_events.cpp @@ -0,0 +1,697 @@ @@ -6047,7 +6322,7 @@ index 0000000000000000000000000000000000000000..d764514ed16b47c3177cb3641d7686a9 +} diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..b191ecf34eb520294c09efe517676db6d9ab16bb +index 000000000..b191ecf34 --- /dev/null +++ b/src/skippy/tests/sampling_history.cpp @@ -0,0 +1,520 @@ @@ -6573,7 +6848,7 @@ index 0000000000000000000000000000000000000000..b191ecf34eb520294c09efe517676db6 +} diff --git a/src/skippy/tests/stage_plan_header.c b/src/skippy/tests/stage_plan_header.c new file mode 100644 -index 0000000000000000000000000000000000000000..2e5a5e1a6926cab5c1d6469ed319d58cc50112b6 +index 000000000..2e5a5e1a6 --- /dev/null +++ b/src/skippy/tests/stage_plan_header.c @@ -0,0 +1,10 @@ @@ -6589,7 +6864,7 @@ index 0000000000000000000000000000000000000000..2e5a5e1a6926cab5c1d6469ed319d58c +} diff --git a/src/skippy/tests/stage_plan_header.cpp b/src/skippy/tests/stage_plan_header.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..beb86aaae57619dba877196b08ddd78b33167e79 +index 000000000..beb86aaae --- /dev/null +++ b/src/skippy/tests/stage_plan_header.cpp @@ -0,0 +1,13 @@ @@ -6608,7 +6883,7 @@ index 0000000000000000000000000000000000000000..beb86aaae57619dba877196b08ddd78b +} diff --git a/src/skippy/tests/stage_slice_plan.cpp b/src/skippy/tests/stage_slice_plan.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..21f659cbd3ba2c14ae0cbf24417334da3d32a791 +index 000000000..21f659cbd --- /dev/null +++ b/src/skippy/tests/stage_slice_plan.cpp @@ -0,0 +1,1200 @@ @@ -7813,7 +8088,7 @@ index 0000000000000000000000000000000000000000..21f659cbd3ba2c14ae0cbf24417334da + return result; +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 46fd38d5f585170bceae9e6a648850dfdfa90fc5..3f6218e13f75152185292df3dfb6b5bb662ddd24 100644 +index 46fd38d5f..3f6218e13 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -181,7 +181,16 @@ set(LLAMA_CONTEXT_TEST_SRC @@ -7881,7 +8156,7 @@ index 46fd38d5f585170bceae9e6a648850dfdfa90fc5..3f6218e13f75152185292df3dfb6b5bb llama_build(test-chat-analysis.cpp) llama_build_and_test(test-log.cpp LABEL behavior) diff --git a/tests/test-chat-auto-parser.cpp b/tests/test-chat-auto-parser.cpp -index b9a40718276b3c7aafd7b890f07ffaaef7486f12..7cc5c57f686508d742da92a12380a98c80cd557e 100644 +index b9a407182..7cc5c57f6 100644 --- a/tests/test-chat-auto-parser.cpp +++ b/tests/test-chat-auto-parser.cpp @@ -74,9 +74,11 @@ static void test_laguna_s_preserve_reasoning(testing & t); @@ -7962,7 +8237,7 @@ index b9a40718276b3c7aafd7b890f07ffaaef7486f12..7cc5c57f686508d742da92a12380a98c static void test_cohere_reasoning_detection(testing & t) { diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp -index cb075a75e86f114825d8379b247a8a5200650376..49d9417d4c88bed9351ce53beeea46bae6088f58 100644 +index cb075a75e..49d9417d4 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -518,6 +518,21 @@ static common_chat_tool special_function_tool{ @@ -8233,7 +8508,7 @@ index cb075a75e86f114825d8379b247a8a5200650376..49d9417d4c88bed9351ce53beeea46ba return 0; diff --git a/tests/test-deepseek4-mtp.h b/tests/test-deepseek4-mtp.h new file mode 100644 -index 0000000000000000000000000000000000000000..87a499031677d9714425c58c06d984017497757f +index 000000000..87a499031 --- /dev/null +++ b/tests/test-deepseek4-mtp.h @@ -0,0 +1,88 @@ @@ -8327,7 +8602,7 @@ index 0000000000000000000000000000000000000000..87a499031677d9714425c58c06d98401 +} diff --git a/tests/test-graph-contract-fixture.h b/tests/test-graph-contract-fixture.h new file mode 100644 -index 0000000000000000000000000000000000000000..c45915888339575d44e94e5b62514dd7906cc3d8 +index 000000000..c45915888 --- /dev/null +++ b/tests/test-graph-contract-fixture.h @@ -0,0 +1,155 @@ @@ -8487,7 +8762,7 @@ index 0000000000000000000000000000000000000000..c45915888339575d44e94e5b62514dd7 + return 0; +} diff --git a/tests/test-jinja.cpp b/tests/test-jinja.cpp -index 624542838540c8aa47c6446cabc07b3a65983dab..fe4869cc1998f001712009ae9f4a7f6f0ec235b3 100644 +index 624542838..fe4869cc1 100644 --- a/tests/test-jinja.cpp +++ b/tests/test-jinja.cpp @@ -3363,6 +3363,11 @@ sys.stdout.buffer.write(result.encode()) @@ -8503,7 +8778,7 @@ index 624542838540c8aa47c6446cabc07b3a65983dab..fe4869cc1998f001712009ae9f4a7f6f const size_t pos = path.find_last_of("/\\"); return (pos == std::string::npos ? std::string(".") : path.substr(0, pos)) + "/../scripts/chat_tts_norm.py"; diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp -index d7ecf29bf519f8d69419a42ee37d533b138349e5..f4c09dc492b8a092b4e5f2f2a38d7a7bf9257bf1 100644 +index d7ecf29bf..f4c09dc49 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -7,12 +7,14 @@ @@ -9043,7 +9318,7 @@ index d7ecf29bf519f8d69419a42ee37d533b138349e5..f4c09dc492b8a092b4e5f2f2a38d7a7b if (kv_shift) { return test_kv_shift(arch_filter, seed, stdev, verbosity); diff --git a/tests/test-reasoning-budget.cpp b/tests/test-reasoning-budget.cpp -index a50a10824db72654ee93c61cec753551e290cf72..e87e0b064b88b88e5e29f93b8c26ba6f1c508648 100644 +index a50a10824..e87e0b064 100644 --- a/tests/test-reasoning-budget.cpp +++ b/tests/test-reasoning-budget.cpp @@ -1,5 +1,6 @@ @@ -9085,7 +9360,7 @@ index a50a10824db72654ee93c61cec753551e290cf72..e87e0b064b88b88e5e29f93b8c26ba6f auto * sampler = common_reasoning_budget_init(nullptr, start, end, {102}, 0, REASONING_BUDGET_FORCING); diff --git a/tests/test-skippy-activation-validation.cpp b/tests/test-skippy-activation-validation.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..7466f03c119202b9501d3042adc95c2ec48cb84a +index 000000000..7466f03c1 --- /dev/null +++ b/tests/test-skippy-activation-validation.cpp @@ -0,0 +1,18 @@ @@ -9109,7 +9384,7 @@ index 0000000000000000000000000000000000000000..7466f03c119202b9501d3042adc95c2e +} diff --git a/tests/test-skippy-cachegen-import.cpp b/tests/test-skippy-cachegen-import.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..43cc3f7d6b6c06ffda668a68544d7585db66b32c +index 000000000..43cc3f7d6 --- /dev/null +++ b/tests/test-skippy-cachegen-import.cpp @@ -0,0 +1,347 @@ @@ -9462,7 +9737,7 @@ index 0000000000000000000000000000000000000000..43cc3f7d6b6c06ffda668a68544d7585 +} diff --git a/tests/test-skippy-cachegen-metal.cpp b/tests/test-skippy-cachegen-metal.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..b15b5e53a6918b43d72d4ad7aedf531282214bdd +index 000000000..b15b5e53a --- /dev/null +++ b/tests/test-skippy-cachegen-metal.cpp @@ -0,0 +1,399 @@ @@ -9867,7 +10142,7 @@ index 0000000000000000000000000000000000000000..b15b5e53a6918b43d72d4ad7aedf5312 +} diff --git a/tests/test-skippy-kv-cells-contiguous.cpp b/tests/test-skippy-kv-cells-contiguous.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..0e95c35b29ff81c65f0a4fef6de24ae2e4b2a597 +index 000000000..0e95c35b2 --- /dev/null +++ b/tests/test-skippy-kv-cells-contiguous.cpp @@ -0,0 +1,20 @@ @@ -9893,7 +10168,7 @@ index 0000000000000000000000000000000000000000..0e95c35b29ff81c65f0a4fef6de24ae2 +} diff --git a/tests/test-skippy-kv-page-export.cpp b/tests/test-skippy-kv-page-export.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..30c88b49028395dea438ab6697a578463457d1b8 +index 000000000..30c88b490 --- /dev/null +++ b/tests/test-skippy-kv-page-export.cpp @@ -0,0 +1,367 @@ @@ -10266,7 +10541,7 @@ index 0000000000000000000000000000000000000000..30c88b49028395dea438ab6697a57846 +} diff --git a/tests/test-skippy-model-loader-accounting.cpp b/tests/test-skippy-model-loader-accounting.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..22b92c0a8513c9ea5c1983d942aba98dcd0acee0 +index 000000000..22b92c0a8 --- /dev/null +++ b/tests/test-skippy-model-loader-accounting.cpp @@ -0,0 +1,320 @@ @@ -10592,7 +10867,7 @@ index 0000000000000000000000000000000000000000..22b92c0a8513c9ea5c1983d942aba98d +} diff --git a/tests/test-skippy-recurrent-state-roundtrip.cpp b/tests/test-skippy-recurrent-state-roundtrip.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..0fae7bbd4efbd65e862972e7bbed24e41a378753 +index 000000000..0fae7bbd4 --- /dev/null +++ b/tests/test-skippy-recurrent-state-roundtrip.cpp @@ -0,0 +1,160 @@ @@ -10758,7 +11033,7 @@ index 0000000000000000000000000000000000000000..0fae7bbd4efbd65e862972e7bbed24e4 +} diff --git a/tests/test-skippy-rerank-template.cpp b/tests/test-skippy-rerank-template.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d6f9570ba4631f77a672fe080ff1d5709764602d +index 000000000..d6f9570ba --- /dev/null +++ b/tests/test-skippy-rerank-template.cpp @@ -0,0 +1,34 @@ @@ -10798,7 +11073,7 @@ index 0000000000000000000000000000000000000000..d6f9570ba4631f77a672fe080ff1d570 +} diff --git a/tests/test-skippy-sampling-suppress.cpp b/tests/test-skippy-sampling-suppress.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..3f797cbe8a9a07892f15172786c654352786f750 +index 000000000..3f797cbe8 --- /dev/null +++ b/tests/test-skippy-sampling-suppress.cpp @@ -0,0 +1,90 @@ @@ -10894,7 +11169,7 @@ index 0000000000000000000000000000000000000000..3f797cbe8a9a07892f15172786c65435 +} diff --git a/tests/test-skippy-verify-checkpoint-retirement.cpp b/tests/test-skippy-verify-checkpoint-retirement.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d09acccb4434eb7fbc05f3bf09a88763f4532450 +index 000000000..d09acccb4 --- /dev/null +++ b/tests/test-skippy-verify-checkpoint-retirement.cpp @@ -0,0 +1,26 @@ @@ -10924,3 +11199,6 @@ index 0000000000000000000000000000000000000000..d09acccb4434eb7fbc05f3bf09a88763 + if (skippy_retire_verify_checkpoint_exact(checkpoints, 10, 3)) return 6; + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch b/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch index 36ad7c30..c17279c9 100644 --- a/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch +++ b/llama_cpp/patches/0007-fix-skippy-keep-native-MTP-state-across-verify-trims.patch @@ -1,4 +1,4 @@ -From 4b425d26ff07b67e59783a57899fe84fcfcb25d6 Mon Sep 17 00:00:00 2001 +From 2601bcc5aa56f686b1c86de1bc400870ee848b5f Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Sat, 10 Oct 2026 17:10:06 +0100 Subject: [PATCH] fix(skippy): keep native MTP state across verify trims @@ -29,7 +29,7 @@ resumes. Callers that discard drafts from rejected windows are unaffected. 6 files changed, 144 insertions(+), 8 deletions(-) diff --git a/src/skippy/runtime_support.h b/src/skippy/runtime_support.h -index d7e99130754c2447fac040b6af979b687b59241b..8ba5956234e4e322463d515d93f18271a3d94a84 100644 +index d7e991307..8ba595623 100644 --- a/src/skippy/runtime_support.h +++ b/src/skippy/runtime_support.h @@ -36,6 +36,7 @@ void skippy_mark_context_synchronized(skippy_model * model); @@ -41,7 +41,7 @@ index d7e99130754c2447fac040b6af979b687b59241b..8ba5956234e4e322463d515d93f18271 bool skippy_verify_window_can_roll_back_in_place( const skippy_session * session, diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index f19a25b76a54088ef1cf49c27ac75a22f88514cd..38ebae8d74ec710d59ed3d07ccded0a42836b7af 100644 +index f19a25b76..38ebae8d7 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -177,6 +177,11 @@ struct skippy_session { @@ -57,7 +57,7 @@ index f19a25b76a54088ef1cf49c27ac75a22f88514cd..38ebae8d74ec710d59ed3d07ccded0a4 bool reset_required = false; std::vector verify_checkpoints; diff --git a/src/skippy/speculative_decoding.cpp b/src/skippy/speculative_decoding.cpp -index 3d15111fb304c38341aade0a9e44e09962f55c87..7f55c0d88d493f9d9aae9245877dd208bbfcf54e 100644 +index 3d15111fb..7f55c0d88 100644 --- a/src/skippy/speculative_decoding.cpp +++ b/src/skippy/speculative_decoding.cpp @@ -91,6 +91,8 @@ void skippy_mtp_clear_session_state(skippy_session * session) { @@ -200,7 +200,7 @@ index 3d15111fb304c38341aade0a9e44e09962f55c87..7f55c0d88d493f9d9aae9245877dd208 + return status; +} diff --git a/src/skippy/speculative_internal.h b/src/skippy/speculative_internal.h -index d8276944dea03fc64c202fa184213d47a73cfcf3..3a147d14d8c87f44fe73b84dd7296183ba3f60eb 100644 +index d8276944d..3a147d14d 100644 --- a/src/skippy/speculative_internal.h +++ b/src/skippy/speculative_internal.h @@ -30,3 +30,15 @@ enum skippy_status skippy_mtp_propose_next( @@ -220,10 +220,10 @@ index d8276944dea03fc64c202fa184213d47a73cfcf3..3a147d14d8c87f44fe73b84dd7296183 + skippy_native_mtp_draft * out_mtp_draft, + skippy_error ** out_error); diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index f035ea13fdcfd88fb0681918f3acf389199bc81b..15c48419d05f9c1ea36751e793de609c37e7ad06 100644 +index d4a5c9673..7571b2cae 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp -@@ -852,7 +852,7 @@ enum skippy_status skippy_trim_session( +@@ -858,7 +858,7 @@ enum skippy_status skippy_trim_session( if (session->signal_history.size() > token_count) { session->signal_history.resize(static_cast(token_count)); } @@ -233,7 +233,7 @@ index f035ea13fdcfd88fb0681918f3acf389199bc81b..15c48419d05f9c1ea36751e793de609c session->ctx->synchronize(); diff --git a/src/skippy/verification.cpp b/src/skippy/verification.cpp -index 0812485d71dfedc65a8760fe682ab8b89c3771a0..bb3c0e6214fcae24ae75193ee1dbbf31f4a2670c 100644 +index 0812485d7..bb3c0e621 100644 --- a/src/skippy/verification.cpp +++ b/src/skippy/verification.cpp @@ -230,13 +230,24 @@ enum skippy_status skippy_verify_tokens_frame_sampled( @@ -268,3 +268,6 @@ index 0812485d71dfedc65a8760fe682ab8b89c3771a0..bb3c0e6214fcae24ae75193ee1dbbf31 if (status != SKIPPY_STATUS_OK) { return status; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch b/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch index 8521d9f0..0e28b20b 100644 --- a/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch +++ b/llama_cpp/patches/0008-fix-skippy-stop-re-attaching-backend-samplers-betwee.patch @@ -1,4 +1,4 @@ -From 4fe4735053162b25c6b771932088a7b33c9bd42b Mon Sep 17 00:00:00 2001 +From 1e659ea03459ca72184873b2dc7e462b0313d88a Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Sat, 10 Oct 2026 18:34:14 +0100 Subject: [PATCH] fix(skippy): stop re-attaching backend samplers between @@ -23,7 +23,7 @@ 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 38ebae8d74ec710d59ed3d07ccded0a42836b7af..f44e874d9f33529cbf4a62b2c2cf6070556d44cf 100644 +index 38ebae8d7..f44e874d9 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -158,6 +158,11 @@ struct skippy_session { @@ -39,7 +39,7 @@ index 38ebae8d74ec710d59ed3d07ccded0a42836b7af..f44e874d9f33529cbf4a62b2c2cf6070 uint64_t sampling_rebuild_count = 0; skippy_sampling_config sampling_config = {}; diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp -index 6fd1240e375eb08280bdc303ff6ce90a1e8ccf67..de5fa6ba5b7eaab955cd2bc4169b38e6830e797f 100644 +index 6fd1240e3..de5fa6ba5 100644 --- a/src/skippy/sampling.cpp +++ b/src/skippy/sampling.cpp @@ -138,6 +138,7 @@ enum skippy_status skippy_verify_token_batch( @@ -61,7 +61,7 @@ index 6fd1240e375eb08280bdc303ff6ce90a1e8ccf67..de5fa6ba5b7eaab955cd2bc4169b38e6 // 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 f1de95cc5290334672181cdda2ce7c7796e772c5..36c972d921626cc32f1411d43ae2bf99630d80d4 100644 +index f1de95cc5..36c972d92 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp @@ -392,6 +392,7 @@ enum skippy_status skippy_session_reset( @@ -73,7 +73,7 @@ index f1de95cc5290334672181cdda2ce7c7796e772c5..36c972d921626cc32f1411d43ae2bf99 session->reset_required = false; session->verify_checkpoints.clear(); diff --git a/src/skippy/tests/runtime_events.cpp b/src/skippy/tests/runtime_events.cpp -index d764514ed16b47c3177cb3641d7686a9de7e05ba..4bceea3cdb3072a2e86627a40781c1a7947289ae 100644 +index d764514ed..4bceea3cd 100644 --- a/src/skippy/tests/runtime_events.cpp +++ b/src/skippy/tests/runtime_events.cpp @@ -500,9 +500,19 @@ int test_native_model_load_production(const char * fixture_path) { @@ -97,7 +97,7 @@ index d764514ed16b47c3177cb3641d7686a9de7e05ba..4bceea3cdb3072a2e86627a40781c1a7 // Embedding and rerank batches request every output row. Their shared diff --git a/src/skippy/verification.cpp b/src/skippy/verification.cpp -index bb3c0e6214fcae24ae75193ee1dbbf31f4a2670c..2e9b20c48db9a617880c692499079ee1652f1a78 100644 +index bb3c0e621..2e9b20c48 100644 --- a/src/skippy/verification.cpp +++ b/src/skippy/verification.cpp @@ -138,6 +138,7 @@ enum skippy_status skippy_verify_tokens_frame_sampled( @@ -108,3 +108,6 @@ index bb3c0e6214fcae24ae75193ee1dbbf31f4a2670c..2e9b20c48db9a617880c692499079ee1 const bool activation_input = skippy_is_filtered(session) && session->stage_model->config.layer_start > 0; status = skippy_checkpoint_verify_window( +-- +2.56.0 + diff --git a/llama_cpp/patches/0009-server-use-a-secure-RNG-for-generated-IDs.patch b/llama_cpp/patches/0009-server-use-a-secure-RNG-for-generated-IDs.patch index 40e7e185..2489dfa5 100644 --- a/llama_cpp/patches/0009-server-use-a-secure-RNG-for-generated-IDs.patch +++ b/llama_cpp/patches/0009-server-use-a-secure-RNG-for-generated-IDs.patch @@ -1,4 +1,4 @@ -From d98c60b727be7a04ea071c9c91336cec36ad913c Mon Sep 17 00:00:00 2001 +From 2a3e248834ac4d6681496542eaddb239364f46d4 Mon Sep 17 00:00:00 2001 From: benthecarman Date: Wed, 7 Oct 2026 14:42:10 -0500 Subject: [PATCH] server: use a secure RNG for generated IDs @@ -18,7 +18,7 @@ size. 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp -index 8bceea6aaa733290a77a861c1d4626a05078f579..5721a7bedc7ee3ccd2fc1bf1110de23b46d4a2b0 100644 +index 8bceea6aa..5721a7bed 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -175,12 +175,12 @@ std::string random_string() { @@ -36,3 +36,6 @@ index 8bceea6aaa733290a77a861c1d4626a05078f579..5721a7bedc7ee3ccd2fc1bf1110de23b } return result; +-- +2.56.0 + diff --git a/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch b/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch index 87c7b287..508bbb22 100644 --- a/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch +++ b/llama_cpp/patches/0010-feat-skippy-read-selected-token-scores-in-causal-bat.patch @@ -1,4 +1,4 @@ -From 9507f9671c900095db714613576fc3ce6afd4468 Mon Sep 17 00:00:00 2001 +From 051a1c265f68f9cf814d269cd67a4634d33d9b7d 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] feat(skippy): read selected token scores in causal batches @@ -8,16 +8,16 @@ 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 diff --git a/include/skippy/execution.h b/include/skippy/execution.h -index 7098677d8bf27a333c7438dc4895d1859fc8eab4..bf9fb497cfc4a9c78d9e6f7af065cf8ca0303641 100644 +index 7098677d8..bf9fb497c 100644 --- a/include/skippy/execution.h +++ b/include/skippy/execution.h @@ -15,6 +15,23 @@ @@ -54,7 +54,7 @@ index 7098677d8bf27a333c7438dc4895d1859fc8eab4..bf9fb497cfc4a9c78d9e6f7af065cf8c /** diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 2bc7d6f6e49c99171722661daf308d435d260b6a..05108ad3894886d92e0e376bc2e3b40c296965a1 100644 +index dc8465589..a2cd419b3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -168,6 +168,10 @@ endif() @@ -69,7 +69,7 @@ index 2bc7d6f6e49c99171722661daf308d435d260b6a..05108ad3894886d92e0e376bc2e3b40c 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 2b9593e0cfc957c583a5c4c9d2679f8ab4c70d9a..86ea1ed55749ec66d964197a68eaa1437e53a4e8 100644 +index 31a65905b..07ccf0b7a 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -5,6 +5,7 @@ @@ -149,7 +149,25 @@ index 2b9593e0cfc957c583a5c4c9d2679f8ab4c70d9a..86ea1ed55749ec66d964197a68eaa143 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); @@ -168,7 +186,7 @@ index 2b9593e0cfc957c583a5c4c9d2679f8ab4c70d9a..86ea1ed55749ec66d964197a68eaa143 // sparse output-row translation internally. diff --git a/src/skippy/selected_logits.h b/src/skippy/selected_logits.h new file mode 100644 -index 0000000000000000000000000000000000000000..0fa526e5d8bf3ec8cbebf9caceba774562a82287 +index 000000000..0fa526e5d --- /dev/null +++ b/src/skippy/selected_logits.h @@ -0,0 +1,43 @@ @@ -217,7 +235,7 @@ index 0000000000000000000000000000000000000000..0fa526e5d8bf3ec8cbebf9caceba7745 +#endif diff --git a/src/skippy/tests/selected_logits.cpp b/src/skippy/tests/selected_logits.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d33237d1a62c4200d6659f14b13488f4c04f726c +index 000000000..d33237d1a --- /dev/null +++ b/src/skippy/tests/selected_logits.cpp @@ -0,0 +1,25 @@ @@ -246,3 +264,6 @@ index 0000000000000000000000000000000000000000..d33237d1a62c4200d6659f14b13488f4 + 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/llama_cpp/patches/0011-grammar-match-literal-lazy-triggers-without-regex.patch b/llama_cpp/patches/0011-grammar-match-literal-lazy-triggers-without-regex.patch index 95c8a93e..c47a9387 100644 --- a/llama_cpp/patches/0011-grammar-match-literal-lazy-triggers-without-regex.patch +++ b/llama_cpp/patches/0011-grammar-match-literal-lazy-triggers-without-regex.patch @@ -1,4 +1,4 @@ -From f3416779a6cda73c5dc5d854c28132ab05107e95 Mon Sep 17 00:00:00 2001 +From a33b274d34b7ff9fd468a687db9996c1bc775d3b Mon Sep 17 00:00:00 2001 From: Mesh-LLM CI Date: Wed, 28 Oct 2026 20:57:15 +1300 Subject: [PATCH] grammar: match literal lazy triggers without regex @@ -11,7 +11,7 @@ Subject: [PATCH] grammar: match literal lazy triggers without regex create mode 100644 tests/test-grammar-trigger-patterns.cpp diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp -index 21a018c8c7096e1a26f5e7f1ae01ef1c3e70b2ea..40eca5a1e4146a7946939475d3ad9c91a4a33096 100644 +index 21a018c8c..40eca5a1e 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -440,6 +440,16 @@ static void print_rule( @@ -32,7 +32,7 @@ index 21a018c8c7096e1a26f5e7f1ae01ef1c3e70b2ea..40eca5a1e4146a7946939475d3ad9c91 // get from the first matched capturing group to the end of the string size_t start = std::string::npos; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 3f6218e13f75152185292df3dfb6b5bb662ddd24..2e017268d51396c450c2d12b672f6ea29ff962db 100644 +index 3f6218e13..2e017268d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -196,6 +196,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) @@ -45,7 +45,7 @@ index 3f6218e13f75152185292df3dfb6b5bb662ddd24..2e017268d51396c450c2d12b672f6ea2 llama_build_and_test(test-batch-alloc.cpp LABEL behavior LINK llama) diff --git a/tests/test-grammar-trigger-patterns.cpp b/tests/test-grammar-trigger-patterns.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..6df57b5c68256a142e3d28400f7ca49a5292d915 +index 000000000..6df57b5c6 --- /dev/null +++ b/tests/test-grammar-trigger-patterns.cpp @@ -0,0 +1,72 @@ @@ -121,3 +121,6 @@ index 0000000000000000000000000000000000000000..6df57b5c68256a142e3d28400f7ca49a + assert(insensitive.find("WORD") == 0); + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch b/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch index 01a78f97..c411551e 100644 --- a/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch +++ b/llama_cpp/patches/0012-feat-skippy-place-routed-experts-of-a-block-range-in.patch @@ -1,4 +1,4 @@ -From 7d636470577be394a914c8e31f03a196dd6ac9c8 Mon Sep 17 00:00:00 2001 +From e66126c3cc07ee45afe4ecbc4bff01fe7ccc1520 Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Fri, 16 Oct 2026 19:21:00 +0300 Subject: [PATCH] feat(skippy): place routed experts of a block range in host @@ -24,7 +24,7 @@ object because llama.cpp borrows both until the load call returns. 7 files changed, 109 insertions(+), 1 deletion(-) diff --git a/include/skippy/common.h b/include/skippy/common.h -index b9b5259afe44fe588e485a3abeccb8bc58bf0ed8..df831c43ebf0be1038278eddf6c7d68596c01082 100644 +index b9b5259af..df831c43e 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -37,7 +37,7 @@ index b9b5259afe44fe588e485a3abeccb8bc58bf0ed8..df831c43ebf0be1038278eddf6c7d685 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index 799bdca2dadf1ef102ea5b207827ffda1ef8abf0..bc4da9a07b869c11b4ec8d6e04c447632d7423eb 100644 +index 799bdca2d..bc4da9a07 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -117,6 +117,12 @@ struct skippy_runtime_config { @@ -54,7 +54,7 @@ index 799bdca2dadf1ef102ea5b207827ffda1ef8abf0..bc4da9a07b869c11b4ec8d6e04c44763 /** @brief Returns a C-safe runtime configuration with all derived-default controls set to auto. */ diff --git a/src/skippy/model_load_config.cpp b/src/skippy/model_load_config.cpp -index 2e8d3c4ed6d312e4ce618d04eddf18dae7782c5b..5a5834038f40888da049a5d22e5bbd24de69ad93 100644 +index 2e8d3c4ed..5a5834038 100644 --- a/src/skippy/model_load_config.cpp +++ b/src/skippy/model_load_config.cpp @@ -176,6 +176,39 @@ void skippy_apply_model_load_memory_config( @@ -98,7 +98,7 @@ index 2e8d3c4ed6d312e4ce618d04eddf18dae7782c5b..5a5834038f40888da049a5d22e5bbd24 const struct skippy_runtime_config * config, llama_context_params & params) { diff --git a/src/skippy/model_load_config_internal.h b/src/skippy/model_load_config_internal.h -index 554d2bdd3be1a734c30fdd53ae7ef05658fb45e4..e3649e7135d8ae215f67e20a00896747bcbcdfc3 100644 +index 554d2bdd3..e3649e713 100644 --- a/src/skippy/model_load_config_internal.h +++ b/src/skippy/model_load_config_internal.h @@ -6,6 +6,7 @@ @@ -132,7 +132,7 @@ index 554d2bdd3be1a734c30fdd53ae7ef05658fb45e4..e3649e7135d8ae215f67e20a00896747 const skippy_runtime_config * config, llama_context_params & params); diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 60a27669fb6a2ef80651e41bc79de1da494a43a8..7305cc5298062b5c70b2c38136a14afbfda8805e 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( @@ -174,7 +174,7 @@ index 60a27669fb6a2ef80651e41bc79de1da494a43a8..7305cc5298062b5c70b2c38136a14afb llama_backend_init(); diff --git a/src/skippy/model_source.cpp b/src/skippy/model_source.cpp -index 02ad771ade0bac7dddfc4d31eff27247fbadd207..2b91f2b71bb228cec598aab02dc0585c128b8bad 100644 +index 02ad771ad..2b91f2b71 100644 --- a/src/skippy/model_source.cpp +++ b/src/skippy/model_source.cpp @@ -393,9 +393,11 @@ static enum skippy_status skippy_model_open_from_source_impl( @@ -190,7 +190,7 @@ index 02ad771ade0bac7dddfc4d31eff27247fbadd207..2b91f2b71bb228cec598aab02dc0585c llama_backend_init(); if (!ggml_backend_reg_count()) { diff --git a/src/skippy/tests/hardware_application_probe.cpp b/src/skippy/tests/hardware_application_probe.cpp -index cfc17776b8f58f26654a160d4ee75deb88f4ee67..417c07dbb40f00a408913ff5fa41f37154be7d0c 100644 +index cfc17776b..417c07dbb 100644 --- a/src/skippy/tests/hardware_application_probe.cpp +++ b/src/skippy/tests/hardware_application_probe.cpp @@ -4,6 +4,7 @@ static const skippy::log_gate::installer skippy_log_gate_installer{}; @@ -251,3 +251,6 @@ index cfc17776b8f58f26654a160d4ee75deb88f4ee67..417c07dbb40f00a408913ff5fa41f371 + return passed ? 0 : 1; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch b/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch index a9cb94fb..5ec26b0e 100644 --- a/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch +++ b/llama_cpp/patches/0013-fix-skippy-take-the-argmax-path-for-temperature-0-ch.patch @@ -1,4 +1,4 @@ -From aa530bbd0e840eae5f0eb64dc3639b4920b332cb Mon Sep 17 00:00:00 2001 +From 33d65a90aea33d4cdd5bd6d708b731605e5f616d Mon Sep 17 00:00:00 2001 From: Mesh-LLM CI Date: Thu, 29 Oct 2026 19:55:52 -0400 Subject: [PATCH] fix(skippy): take the argmax path for temperature-0 chains @@ -17,7 +17,7 @@ Subject: [PATCH] fix(skippy): take the argmax path for temperature-0 chains create mode 100644 src/skippy/sampling_argmax.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 05108ad3894886d92e0e376bc2e3b40c296965a1..ead5ea4b4527ab884a792174afa50a75aef32eb4 100644 +index a2cd419b3..d3e29d8e2 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -50,6 +50,7 @@ add_library(llama @@ -28,7 +28,7 @@ index 05108ad3894886d92e0e376bc2e3b40c296965a1..ead5ea4b4527ab884a792174afa50a75 skippy/execution-batch.cpp skippy/execution-single.cpp skippy/model_load_config.cpp -@@ -417,7 +418,7 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -426,7 +427,7 @@ if (LLAMA_STAGE_BUILD_TESTS) 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) @@ -38,7 +38,7 @@ index 05108ad3894886d92e0e376bc2e3b40c296965a1..ead5ea4b4527ab884a792174afa50a75 COMMAND skippy-sampling-history "${SKIPPY_MODEL_FIXTURE_DIR}/${family}-dense.gguf" ${mode} ${state}) diff --git a/src/skippy/chat_sampling.cpp b/src/skippy/chat_sampling.cpp -index 3c9fc758bdae343a7ae9581a32bb95b436d5de28..2d266fbb71755be7e27aeed0f756f6b0f19ba364 100644 +index 3c9fc758b..2d266fbb7 100644 --- a/src/skippy/chat_sampling.cpp +++ b/src/skippy/chat_sampling.cpp @@ -5,6 +5,7 @@ @@ -106,7 +106,7 @@ index 3c9fc758bdae343a7ae9581a32bb95b436d5de28..2d266fbb71755be7e27aeed0f756f6b0 skippy_mark_context_synchronized(session->stage_model); const auto * candidates = common_sampler_get_candidates(session->sampler, false); diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index f44e874d9f33529cbf4a62b2c2cf6070556d44cf..46e907aa0d03e2b8eeb1cfbaf70e4ab845026390 100644 +index f44e874d9..46e907aa0 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -1,6 +1,7 @@ @@ -128,7 +128,7 @@ index f44e874d9f33529cbf4a62b2c2cf6070556d44cf..46e907aa0d03e2b8eeb1cfbaf70e4ab8 bool sampling_config_valid = false; std::string chat_sampling_metadata; diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp -index de5fa6ba5b7eaab955cd2bc4169b38e6830e797f..6a13522711cd8119231df0dad8aa64219ca8e6a7 100644 +index de5fa6ba5..6a1352271 100644 --- a/src/skippy/sampling.cpp +++ b/src/skippy/sampling.cpp @@ -331,6 +331,7 @@ void skippy_clear_chat_sampling(skippy_session * session) { @@ -149,7 +149,7 @@ index de5fa6ba5b7eaab955cd2bc4169b38e6830e797f..6a13522711cd8119231df0dad8aa6421 static void skippy_log_sampling_cache_metrics( diff --git a/src/skippy/sampling_argmax.cpp b/src/skippy/sampling_argmax.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..42e777f8991ee8a1b4034652aaee7ab66be2346f +index 000000000..42e777f89 --- /dev/null +++ b/src/skippy/sampling_argmax.cpp @@ -0,0 +1,136 @@ @@ -291,7 +291,7 @@ index 0000000000000000000000000000000000000000..42e777f8991ee8a1b4034652aaee7ab6 +} diff --git a/src/skippy/sampling_argmax.h b/src/skippy/sampling_argmax.h new file mode 100644 -index 0000000000000000000000000000000000000000..d06000f1149c0d43ac1ce340136f1614ef394bda +index 000000000..d06000f11 --- /dev/null +++ b/src/skippy/sampling_argmax.h @@ -0,0 +1,42 @@ @@ -338,7 +338,7 @@ index 0000000000000000000000000000000000000000..d06000f1149c0d43ac1ce340136f1614 + 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 b191ecf34eb520294c09efe517676db6d9ab16bb..5ae8e15b4b0bf31f2cd3b15ce96ac8a6a8463de1 100644 +index b191ecf34..5ae8e15b4 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -1,5 +1,7 @@ @@ -485,3 +485,6 @@ index b191ecf34eb520294c09efe517676db6d9ab16bb..5ae8e15b4b0bf31f2cd3b15ce96ac8a6 } else { for (const bool full : {false, true}) { if (grammar) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch b/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch index a4a434ba..b53594b9 100644 --- a/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch +++ b/llama_cpp/patches/0014-skippy-size-recurrent-rollback-for-speculative-verif.patch @@ -1,4 +1,4 @@ -From 0044d1c94f1bf536e856ea03249ab9e3450f6026 Mon Sep 17 00:00:00 2001 +From f9f7f370af2d56595b9c203cdee24f81a7d2f29c Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Wed, 28 Oct 2026 14:17:38 +1100 Subject: [PATCH] skippy: size recurrent rollback for speculative verify @@ -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 bc4da9a07b869c11b4ec8d6e04c447632d7423eb..b570682ef1a9559bd0d76429908bd06de34dc84b 100644 +index bc4da9a07..b570682ef 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -123,6 +123,10 @@ struct skippy_runtime_config { @@ -38,10 +38,10 @@ index bc4da9a07b869c11b4ec8d6e04c447632d7423eb..b570682ef1a9559bd0d76429908bd06d /** @brief Returns a C-safe runtime configuration with all derived-default controls set to auto. */ diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 52dfe91c75de4526f662d73b692346d23423fdf0..2657085306eae301b88dde6fa09f57c6e0cbf571 100644 +index 7ec63d58b..28601c0e2 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -2339,9 +2339,10 @@ int llama_context::decode( +@@ -2342,9 +2342,10 @@ int llama_context::decode( // are limited to one output row; a sampler on some other // sequence of this context must not reject a multi-output // batch (e.g. speculative verification) for this one. @@ -56,7 +56,7 @@ index 52dfe91c75de4526f662d73b692346d23423fdf0..2657085306eae301b88dde6fa09f57c6 } } diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 7305cc5298062b5c70b2c38136a14afbfda8805e..db5a69e38f4f32163ce796436501cfed76db1065 100644 +index 7305cc529..db5a69e38 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -733,7 +733,13 @@ enum skippy_status skippy_finish_model_open( @@ -75,7 +75,7 @@ index 7305cc5298062b5c70b2c38136a14afbfda8805e..db5a69e38f4f32163ce796436501cfed } // Multi-lane activation exports rely on the shared KV pool's batch order. diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp -index 6a13522711cd8119231df0dad8aa64219ca8e6a7..b688fce731da6af004ad3d6444cd9d679a890324 100644 +index 6a1352271..b688fce73 100644 --- a/src/skippy/sampling.cpp +++ b/src/skippy/sampling.cpp @@ -325,7 +325,9 @@ void skippy_clear_chat_sampling(skippy_session * session) { @@ -90,7 +90,7 @@ index 6a13522711cd8119231df0dad8aa64219ca8e6a7..b688fce731da6af004ad3d6444cd9d67 session->sampling_config_valid = false; session->chat_sampling_metadata.clear(); diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 36c972d921626cc32f1411d43ae2bf99630d80d4..4741f55cb5271c78b2947596ae987bed1c0b19f5 100644 +index 36c972d92..4741f55cb 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp @@ -390,6 +390,7 @@ enum skippy_status skippy_session_reset( @@ -101,3 +101,6 @@ index 36c972d921626cc32f1411d43ae2bf99630d80d4..4741f55cb5271c78b2947596ae987bed } skippy_mtp_clear_session_state(session); session->sampling_backend_verifying = false; +-- +2.56.0 + diff --git a/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch b/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch index f220e11b..0fc4a230 100644 --- a/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch +++ b/llama_cpp/patches/0015-skippy-roll-back-staged-verify-windows-in-place.patch @@ -1,4 +1,4 @@ -From 973a3878cf49a7b6a20d9793f520a387ae747025 Mon Sep 17 00:00:00 2001 +From a0a69bdd2da62a73035f73dd6c586f920de13163 Mon Sep 17 00:00:00 2001 From: Daniel Winter Date: Thu, 29 Oct 2026 21:32:31 +1100 Subject: [PATCH] skippy: roll back staged verify windows in place @@ -71,7 +71,7 @@ rewind must be refused as unsupported. create mode 100644 src/skippy/verify_window.h diff --git a/include/skippy/common.h b/include/skippy/common.h -index df831c43ebf0be1038278eddf6c7d68596c01082..3448095a1935d0d2ba3a12ca72f4d178c3f317e5 100644 +index df831c43e..3448095a1 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -84,7 +84,7 @@ index df831c43ebf0be1038278eddf6c7d68596c01082..3448095a1935d0d2ba3a12ca72f4d178 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/state.h b/include/skippy/state.h -index 1cfaaa5c69329eb0d21307c72cb7629267002be3..e8d0874a1bf45a002f86c2459af75a426efcc05e 100644 +index 1cfaaa5c6..e8d0874a1 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h @@ -173,6 +173,21 @@ LLAMA_API enum skippy_status skippy_retire_verify_checkpoint( @@ -110,7 +110,7 @@ index 1cfaaa5c69329eb0d21307c72cb7629267002be3..e8d0874a1bf45a002f86c2459af75a42 LLAMA_API enum skippy_status skippy_export_kv_page( struct skippy_session * session, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index ead5ea4b4527ab884a792174afa50a75aef32eb4..bb9de46afbefd642f11c7bf4e3d9ed3d4b87e29b 100644 +index d3e29d8e2..196030bfa 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -59,6 +59,7 @@ add_library(llama @@ -121,7 +121,7 @@ index ead5ea4b4527ab884a792174afa50a75aef32eb4..bb9de46afbefd642f11c7bf4e3d9ed3d skippy/workloads.cpp skippy/abi.cpp skippy/block_boundaries.cpp -@@ -413,6 +414,26 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -422,6 +423,26 @@ if (LLAMA_STAGE_BUILD_TESTS) set_tests_properties(skippy_generate_gemma_fixture PROPERTIES FIXTURES_SETUP skippy-model-loader-fixtures) @@ -149,7 +149,7 @@ index ead5ea4b4527ab884a792174afa50a75aef32eb4..bb9de46afbefd642f11c7bf4e3d9ed3d 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 -index 8793000c101ace2fa78b5ae4356c4bed9393fcb9..f6ce0295e9badcb850bcb7feccd5781e2dc0b7a5 100644 +index 8793000c1..f6ce0295e 100644 --- a/src/skippy-verify-checkpoint.h +++ b/src/skippy-verify-checkpoint.h @@ -2,13 +2,17 @@ @@ -182,7 +182,7 @@ index 8793000c101ace2fa78b5ae4356c4bed9393fcb9..f6ce0295e9badcb850bcb7feccd5781e return true; } diff --git a/src/skippy/activation.cpp b/src/skippy/activation.cpp -index d1c094548c7c3e0273366d2fb067c037d1878255..7167e5f7a49541628823aee6dd5a695ec183f4d4 100644 +index d1c094548..7167e5f7a 100644 --- a/src/skippy/activation.cpp +++ b/src/skippy/activation.cpp @@ -6,6 +6,7 @@ @@ -450,7 +450,7 @@ index d1c094548c7c3e0273366d2fb067c037d1878255..7167e5f7a49541628823aee6dd5a695e false, SKIPPY_GLM_DSA_PHASE_HINT_VERIFY, diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp -index 86ea1ed55749ec66d964197a68eaa1437e53a4e8..40faff815be00b44a316945bcf7d345cb008b9ce 100644 +index 07ccf0b7a..7d7973520 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -393,6 +393,13 @@ enum skippy_status skippy_iteration_batch_sampled( @@ -468,7 +468,7 @@ index 86ea1ed55749ec66d964197a68eaa1437e53a4e8..40faff815be00b44a316945bcf7d345c &first->stage_model->config, SKIPPY_GLM_DSA_PHASE_HINT_AUTO); std::vector> frontier_storage; diff --git a/src/skippy/execution-single.cpp b/src/skippy/execution-single.cpp -index 4ce3d4ba92e3a572bc8bc229d41f84eef8c36b61..8a1b320ff3e5fe0d410aa82c4b86d67d70dd4b89 100644 +index 4ce3d4ba9..8a1b320ff 100644 --- a/src/skippy/execution-single.cpp +++ b/src/skippy/execution-single.cpp @@ -210,6 +210,11 @@ enum skippy_status skippy_decode_batch_sampled( @@ -484,7 +484,7 @@ index 4ce3d4ba92e3a572bc8bc229d41f84eef8c36b61..8a1b320ff3e5fe0d410aa82c4b86d67d batch.pos[i] = session->n_past; batch.n_seq_id[i] = 1; diff --git a/src/skippy/runtime_support.h b/src/skippy/runtime_support.h -index 8ba5956234e4e322463d515d93f18271a3d94a84..bbba808a303ae0d2be2fc680f140db069ce7e58d 100644 +index 8ba595623..bbba808a3 100644 --- a/src/skippy/runtime_support.h +++ b/src/skippy/runtime_support.h @@ -41,6 +41,13 @@ void skippy_clear_chat_sampling(skippy_session * session); @@ -502,7 +502,7 @@ index 8ba5956234e4e322463d515d93f18271a3d94a84..bbba808a303ae0d2be2fc680f140db06 skippy_session * session, uint64_t token_count, diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index 46e907aa0d03e2b8eeb1cfbaf70e4ab845026390..ec9fb94b1b65e552d016527984f588f79296ea56 100644 +index 46e907aa0..ec9fb94b1 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -121,6 +121,11 @@ struct skippy_verify_checkpoint { @@ -535,7 +535,7 @@ index 46e907aa0d03e2b8eeb1cfbaf70e4ab845026390..ec9fb94b1b65e552d016527984f588f7 + uint64_t verify_windows_checkpointed = 0; }; diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 4741f55cb5271c78b2947596ae987bed1c0b19f5..9d0ba6ee54f0cd039ee1615923f11f55ad6846b8 100644 +index 4741f55cb..9d0ba6ee5 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp @@ -190,7 +190,7 @@ int32_t skippy_session_batch_size( @@ -580,7 +580,7 @@ index 4741f55cb5271c78b2947596ae987bed1c0b19f5..9d0ba6ee54f0cd039ee1615923f11f55 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 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5185d6edd 100644 +index 7571b2cae..ff0cc8ab9 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp @@ -74,7 +74,7 @@ static void skippy_update_session_state_after_import( @@ -592,7 +592,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 } static enum skippy_status skippy_imported_session_position( -@@ -646,7 +646,7 @@ enum skippy_status skippy_import_kv_page( +@@ -649,7 +649,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); @@ -601,7 +601,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 session->ctx->synchronize(); return skippy_success(out_error); } -@@ -742,7 +742,7 @@ enum skippy_status skippy_import_cachegen_kv_page_v1(struct skippy_session * +@@ -748,7 +748,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); @@ -610,7 +610,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 session->ctx->synchronize(); return skippy_success(out_error); } -@@ -759,17 +759,28 @@ enum skippy_status skippy_retire_verify_checkpoint( +@@ -765,17 +765,28 @@ enum skippy_status skippy_retire_verify_checkpoint( if (!skippy_memory_needs_verify_checkpoint(session->ctx->get_memory())) { return skippy_success(out_error); } @@ -647,7 +647,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 } enum skippy_status skippy_trim_session( -@@ -799,6 +810,25 @@ enum skippy_status skippy_trim_session( +@@ -805,6 +816,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; } @@ -673,7 +673,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 bool restored_verify_prefix = false; enum skippy_status status = skippy_restore_verify_prefix( session, -@@ -836,8 +866,13 @@ enum skippy_status skippy_trim_session( +@@ -842,8 +872,13 @@ enum skippy_status skippy_trim_session( return SKIPPY_STATUS_RUNTIME_ERROR; } } else if (dynamic_cast(memory) == nullptr) { @@ -689,7 +689,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 } } session->n_past = static_cast(token_count); -@@ -853,7 +888,7 @@ enum skippy_status skippy_trim_session( +@@ -859,7 +894,7 @@ enum skippy_status skippy_trim_session( session->signal_history.resize(static_cast(token_count)); } skippy_mtp_trim_session_state(session, static_cast(token_count)); @@ -698,7 +698,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 session->ctx->synchronize(); return skippy_success(out_error); -@@ -1008,7 +1043,7 @@ enum skippy_status skippy_session_restore_prefix( +@@ -1014,7 +1049,7 @@ enum skippy_status skippy_session_restore_prefix( } session->signal_history.clear(); skippy_mtp_clear_session_state(session); @@ -708,7 +708,7 @@ index 15c48419d05f9c1ea36751e793de609c37e7ad06..44b924b0b45ce004e3ea3408f024d2f5 } diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 5ae8e15b4b0bf31f2cd3b15ce96ac8a6a8463de1..0c81c9d473c504fe540c0b1a2b79ef1f9aa54443 100644 +index 5ae8e15b4..0c81c9d47 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -3,6 +3,7 @@ @@ -783,7 +783,7 @@ index 5ae8e15b4b0bf31f2cd3b15ce96ac8a6a8463de1..0c81c9d473c504fe540c0b1a2b79ef1f } diff --git a/src/skippy/tests/verify_rollback.cpp b/src/skippy/tests/verify_rollback.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..f479a8e4ec0bb387d0f17c96d9319b7ec2976892 +index 000000000..f479a8e4e --- /dev/null +++ b/src/skippy/tests/verify_rollback.cpp @@ -0,0 +1,392 @@ @@ -1181,7 +1181,7 @@ index 0000000000000000000000000000000000000000..f479a8e4ec0bb387d0f17c96d9319b7e +} diff --git a/src/skippy/verify_window.cpp b/src/skippy/verify_window.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..c578edf61ba776fd452d795c21b66239eace38c5 +index 000000000..c578edf61 --- /dev/null +++ b/src/skippy/verify_window.cpp @@ -0,0 +1,229 @@ @@ -1416,7 +1416,7 @@ index 0000000000000000000000000000000000000000..c578edf61ba776fd452d795c21b66239 +} diff --git a/src/skippy/verify_window.h b/src/skippy/verify_window.h new file mode 100644 -index 0000000000000000000000000000000000000000..45bb92cbab5ddd38cc29d2a805d11ea89ed6c084 +index 000000000..45bb92cba --- /dev/null +++ b/src/skippy/verify_window.h @@ -0,0 +1,38 @@ @@ -1459,7 +1459,7 @@ index 0000000000000000000000000000000000000000..45bb92cbab5ddd38cc29d2a805d11ea8 + std::vector & state, + skippy_error ** out_error); diff --git a/tests/test-skippy-verify-checkpoint-retirement.cpp b/tests/test-skippy-verify-checkpoint-retirement.cpp -index d09acccb4434eb7fbc05f3bf09a88763f4532450..8d68604c31b4bed3c1660cfe1033e87ecc3cc386 100644 +index d09acccb4..8d68604c3 100644 --- a/tests/test-skippy-verify-checkpoint-retirement.cpp +++ b/tests/test-skippy-verify-checkpoint-retirement.cpp @@ -7,6 +7,7 @@ struct checkpoint { @@ -1484,3 +1484,6 @@ index d09acccb4434eb7fbc05f3bf09a88763f4532450..8d68604c31b4bed3c1660cfe1033e87e + if (skippy_retire_verify_checkpoint_exact(checkpoints, 30, 4, &retired)) return 10; return 0; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0016-skippy-report-which-layer-inputs-a-graph-publishes.patch b/llama_cpp/patches/0016-skippy-report-which-layer-inputs-a-graph-publishes.patch index 5d5f5374..9b5f2e4d 100644 --- a/llama_cpp/patches/0016-skippy-report-which-layer-inputs-a-graph-publishes.patch +++ b/llama_cpp/patches/0016-skippy-report-which-layer-inputs-a-graph-publishes.patch @@ -1,4 +1,4 @@ -From 78878c7d68e1f334f8d798bf17c0be70a2498091 Mon Sep 17 00:00:00 2001 +From 7a847dc040144e9eac4ae96e19146bc6cd1ee298 Mon Sep 17 00:00:00 2001 From: Mesh-LLM CI Date: Thu, 29 Oct 2026 19:55:52 -0400 Subject: [PATCH] skippy: report published layer inputs including head input @@ -10,7 +10,7 @@ Subject: [PATCH] skippy: report published layer inputs including head input 3 files changed, 104 insertions(+), 1 deletion(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 2657085306eae301b88dde6fa09f57c6e0cbf571..2bdbaed596961785e4915919ff33d969ec3a0b98 100644 +index 28601c0e2..b6e03da05 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -25,6 +25,7 @@ @@ -33,7 +33,7 @@ index 2657085306eae301b88dde6fa09f57c6e0cbf571..2bdbaed596961785e4915919ff33d969 if (cparams.embeddings_layer_inp[lid] == enable) return; ++computation_generation; -@@ -2278,6 +2280,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { +@@ -2281,6 +2283,7 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { int llama_context::decode( const llama_batch_ext & batch_inp, const skippy_graph_build_inputs & graph_build_inputs) { @@ -41,7 +41,7 @@ index 2657085306eae301b88dde6fa09f57c6e0cbf571..2bdbaed596961785e4915919ff33d969 if (!memory) { LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__); return encode(batch_inp, graph_build_inputs); -@@ -3190,6 +3193,43 @@ bool llama_context::get_input_activation_frontier(std::vectorset_embeddings_layer_inp(lid, value); } @@ -97,7 +97,7 @@ index 2657085306eae301b88dde6fa09f57c6e0cbf571..2bdbaed596961785e4915919ff33d969 ctx->set_nextn_layer_offset(offset); } diff --git a/src/llama-context.h b/src/llama-context.h -index c26fdd61584b9ae677f530871d7b0a401bf25da7..75cea4e84b48484ab40020c4508219d9ee97acb3 100644 +index c26fdd615..75cea4e84 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -14,6 +14,7 @@ @@ -129,7 +129,7 @@ index c26fdd61584b9ae677f530871d7b0a401bf25da7..75cea4e84b48484ab40020c4508219d9 const skippy_graph_build_inputs graph_build_inputs; uint64_t computation_generation = 0; diff --git a/src/llama-ext.h b/src/llama-ext.h -index e5f2e6c919019ad07667c8cd6b54b993a5ea2d54..f9c4b0c65f5a937fc555318978103c7818199e44 100644 +index e5f2e6c91..f9c4b0c65 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -152,6 +152,58 @@ LLAMA_API bool llama_batch_ext_set_decision_group(struct llama_batch_ext * batch @@ -191,3 +191,6 @@ index e5f2e6c919019ad07667c8cd6b54b993a5ea2d54..f9c4b0c65f5a937fc555318978103c78 // // model/context data extraction // +-- +2.56.0 + diff --git a/llama_cpp/patches/0017-skippy-retain-fatal-CUDA-diagnostics.patch b/llama_cpp/patches/0017-skippy-retain-fatal-CUDA-diagnostics.patch index 9beb1a3d..be08edde 100644 --- a/llama_cpp/patches/0017-skippy-retain-fatal-CUDA-diagnostics.patch +++ b/llama_cpp/patches/0017-skippy-retain-fatal-CUDA-diagnostics.patch @@ -1,4 +1,4 @@ -From 41e455ce88047dd92c318db85018cebe9762185d Mon Sep 17 00:00:00 2001 +From 965d254b39f12647d60c9f2c800ebcb5e6f8178f Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Tue, 17 Nov 2026 21:32:09 +1100 Subject: [PATCH] skippy: retain fatal CUDA diagnostics during quiet device @@ -9,7 +9,7 @@ Subject: [PATCH] skippy: retain fatal CUDA diagnostics during quiet device 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu -index 4700191f7754f1975494130141c7244ac2b2dda2..c35b4a1db70556643cdc607d049ac6be78ecc5fc 100644 +index 4700191f7..c35b4a1db 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -115,7 +115,10 @@ void ggml_cuda_error(const char * stmt, const char * func, const char * file, in @@ -24,3 +24,6 @@ index 4700191f7754f1975494130141c7244ac2b2dda2..c35b4a1db70556643cdc607d049ac6be } // map a (possibly virtual) device id to the physical CUDA device that backs it +-- +2.56.0 + diff --git a/llama_cpp/patches/0018-test-bound-synthetic-MiMo2-KV-geometry.patch b/llama_cpp/patches/0018-test-bound-synthetic-MiMo2-KV-geometry.patch index dd02e8df..20b03d85 100644 --- a/llama_cpp/patches/0018-test-bound-synthetic-MiMo2-KV-geometry.patch +++ b/llama_cpp/patches/0018-test-bound-synthetic-MiMo2-KV-geometry.patch @@ -1,4 +1,4 @@ -From 92add8dd859638c1678c0b585b3d36eeec795d89 Mon Sep 17 00:00:00 2001 +From 35bc269d756620a97924bd67793fc4c767cf2fe5 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Tue, 17 Nov 2026 22:14:38 +1100 Subject: [PATCH] test: bound MiMo2 KV geometry and derive fused MTP shape from @@ -10,7 +10,7 @@ Subject: [PATCH] test: bound MiMo2 KV geometry and derive fused MTP shape from 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/test-graph-contract-fixture.h b/tests/test-graph-contract-fixture.h -index c45915888339575d44e94e5b62514dd7906cc3d8..3a520bddaab136148b7734df7cf12f9826322b39 100644 +index c45915888..3a520bdda 100644 --- a/tests/test-graph-contract-fixture.h +++ b/tests/test-graph-contract-fixture.h @@ -135,7 +135,11 @@ static int save_graph_contract_fixture(llm_arch arch, const std::string & out, u @@ -27,7 +27,7 @@ index c45915888339575d44e94e5b62514dd7906cc3d8..3a520bddaab136148b7734df7cf12f98 gguf_add_tensor(output.get(), qkv); } diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp -index f4c09dc492b8a092b4e5f2f2a38d7a7bf9257bf1..37115641bb4cd65b42d531f6939621c5061a2bef 100644 +index f4c09dc49..37115641b 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -400,6 +400,13 @@ static gguf_context_ptr get_gguf_ctx( @@ -44,3 +44,6 @@ index f4c09dc492b8a092b4e5f2f2a38d7a7bf9257bf1..37115641bb4cd65b42d531f6939621c5 if (arch == LLM_ARCH_BEAM) { n_head = 4; n_head_kv = 2; +-- +2.56.0 + diff --git a/llama_cpp/patches/0019-skippy-release-temporary-MTP-planning-contexts.patch b/llama_cpp/patches/0019-skippy-release-temporary-MTP-planning-contexts.patch index ebc7bfa8..db5f1aa9 100644 --- a/llama_cpp/patches/0019-skippy-release-temporary-MTP-planning-contexts.patch +++ b/llama_cpp/patches/0019-skippy-release-temporary-MTP-planning-contexts.patch @@ -1,4 +1,4 @@ -From d77c0428c3b1a7f44bd1b3e824727fd3ad3ddb06 Mon Sep 17 00:00:00 2001 +From 0422169e40e5f99422e251ab8e9fce92ab415a64 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Tue, 17 Nov 2026 22:23:21 +1100 Subject: [PATCH] skippy: release temporary MTP planning contexts @@ -8,7 +8,7 @@ Subject: [PATCH] skippy: release temporary MTP planning contexts 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/skippy/stage_plan.cpp b/src/skippy/stage_plan.cpp -index 380e1eaad93d222fd8f9ab318a5c34c3ae26059e..0c4ab443bfffbbb5a9ab6b501f46b076edd82b3e 100644 +index 380e1eaad..0c4ab443b 100644 --- a/src/skippy/stage_plan.cpp +++ b/src/skippy/stage_plan.cpp @@ -402,7 +402,9 @@ bool add_mtp_profiles( @@ -22,3 +22,6 @@ index 380e1eaad93d222fd8f9ab318a5c34c3ae26059e..0c4ab443bfffbbb5a9ab6b501f46b076 } } plan.guarded.resident_parameter_identities.assign(residents.begin(), residents.end()); +-- +2.56.0 + diff --git a/llama_cpp/patches/0020-skippy-restore-resident-prefixes-as-shared-cells-plu.patch b/llama_cpp/patches/0020-skippy-restore-resident-prefixes-as-shared-cells-plu.patch index 06572888..8cbe1881 100644 --- a/llama_cpp/patches/0020-skippy-restore-resident-prefixes-as-shared-cells-plu.patch +++ b/llama_cpp/patches/0020-skippy-restore-resident-prefixes-as-shared-cells-plu.patch @@ -1,4 +1,4 @@ -From ca08167b5e6a52e9deec0f9dddcec08c67ebf12c Mon Sep 17 00:00:00 2001 +From 09f1dbfa4e5d5f9d301eb553369b03b8c14c863b Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 10 Nov 2026 21:00:00 +1100 Subject: [PATCH] skippy: restore resident prefixes as shared cells plus @@ -69,7 +69,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 src/skippy/tests/resident_checkpoint_writer.cpp diff --git a/include/skippy/common.h b/include/skippy/common.h -index 3448095a1935d0d2ba3a12ca72f4d178c3f317e5..cbba9184990715d863c59a19fa68a3a08f72d591 100644 +index 3448095a1..cbba91849 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -82,7 +82,7 @@ index 3448095a1935d0d2ba3a12ca72f4d178c3f317e5..cbba9184990715d863c59a19fa68a3a0 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index b570682ef1a9559bd0d76429908bd06de34dc84b..856c98f97a4ff9853d7777eec51183f48c5039e6 100644 +index b570682ef..856c98f97 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -96,7 +96,7 @@ struct skippy_runtime_config { @@ -95,7 +95,7 @@ index b570682ef1a9559bd0d76429908bd06de34dc84b..856c98f97a4ff9853d7777eec51183f4 /** @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 e8d0874a1bf45a002f86c2459af75a426efcc05e..6d9028a18e72dc4c6b0ee19f5110e91afe837afb 100644 +index e8d0874a1..6d9028a18 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h @@ -17,6 +17,10 @@ enum skippy_memory_cache_capability { @@ -186,7 +186,7 @@ index e8d0874a1bf45a002f86c2459af75a426efcc05e..6d9028a18e72dc4c6b0ee19f5110e91a 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 bb9de46afbefd642f11c7bf4e3d9ed3d4b87e29b..2e85dbfe12ae83a942324304529a6c3c7959d725 100644 +index 196030bfa..85a8a59cc 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -89,6 +89,7 @@ add_library(llama @@ -197,7 +197,7 @@ index bb9de46afbefd642f11c7bf4e3d9ed3d4b87e29b..2e85dbfe12ae83a942324304529a6c3c skippy/state_memory.cpp skippy/state_effects.cpp skippy/speculative_decoding.cpp -@@ -434,12 +435,17 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -443,12 +444,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) @@ -218,10 +218,10 @@ index bb9de46afbefd642f11c7bf4e3d9ed3d4b87e29b..2e85dbfe12ae83a942324304529a6c3c 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 2bdbaed596961785e4915919ff33d969ec3a0b98..9b1c1a4df93182f4634e7c798f3ddc4fcd883c29 100644 +index b6e03da05..768e14a25 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -3777,6 +3777,10 @@ private: +@@ -3785,6 +3785,10 @@ private: std::vector winfos; }; @@ -233,7 +233,7 @@ index 2bdbaed596961785e4915919ff33d969ec3a0b98..9b1c1a4df93182f4634e7c798f3ddc4f 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 0aca7331074d4a4a6d8ed99dc8901b02790d77a0..72aa587182dc81ec24718fae3e4a0e14506f5e4d 100644 +index 0aca73310..72aa58718 100644 --- a/src/llama-io.h +++ b/src/llama-io.h @@ -2,6 +2,7 @@ @@ -254,7 +254,7 @@ index 0aca7331074d4a4a6d8ed99dc8901b02790d77a0..72aa587182dc81ec24718fae3e4a0e14 +// 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 db5a69e38f4f32163ce796436501cfed76db1065..5bfd47c93c06128b7a0a4f00f81e2abf1931ca6e 100644 +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( @@ -286,7 +286,7 @@ index db5a69e38f4f32163ce796436501cfed76db1065..5bfd47c93c06128b7a0a4f00f81e2abf 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 0000000000000000000000000000000000000000..317c96b46e2670cfaab9b5460d258b28f7b1abb9 +index 000000000..317c96b46 --- /dev/null +++ b/src/skippy/resident_prefix.cpp @@ -0,0 +1,438 @@ @@ -729,7 +729,7 @@ index 0000000000000000000000000000000000000000..317c96b46e2670cfaab9b5460d258b28 + +} // extern "C" diff --git a/src/skippy/runtime_types.h b/src/skippy/runtime_types.h -index ec9fb94b1b65e552d016527984f588f79296ea56..3a2e3147e92af58ae1d11c844e5c3410e12b6dc0 100644 +index ec9fb94b1..3a2e3147e 100644 --- a/src/skippy/runtime_types.h +++ b/src/skippy/runtime_types.h @@ -10,6 +10,7 @@ @@ -774,7 +774,7 @@ index ec9fb94b1b65e552d016527984f588f79296ea56..3a2e3147e92af58ae1d11c844e5c3410 std::vector signal_history; std::vector prefill_positions; diff --git a/src/skippy/session.cpp b/src/skippy/session.cpp -index 9d0ba6ee54f0cd039ee1615923f11f55ad6846b8..d5ac795e95f2bd41947b282f02aa53583ac39d9a 100644 +index 9d0ba6ee5..d5ac795e9 100644 --- a/src/skippy/session.cpp +++ b/src/skippy/session.cpp @@ -147,9 +147,6 @@ enum skippy_status skippy_session_create( @@ -814,7 +814,7 @@ index 9d0ba6ee54f0cd039ee1615923f11f55ad6846b8..d5ac795e95f2bd41947b282f02aa5358 skippy_clear_chat_sampling(session); if (!session->borrowed_sequence) { diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp -index 44b924b0b45ce004e3ea3408f024d2f5185d6edd..a36c31925ab4906d3dd1e5d59a216c497914d598 100644 +index ff0cc8ab9..bab58a50f 100644 --- a/src/skippy/state.cpp +++ b/src/skippy/state.cpp @@ -18,6 +18,7 @@ @@ -947,7 +947,7 @@ index 44b924b0b45ce004e3ea3408f024d2f5185d6edd..a36c31925ab4906d3dd1e5d59a216c49 static llama_kv_cache * skippy_get_kv_cache( skippy_session * session, skippy_error ** out_error) { -@@ -894,331 +780,4 @@ enum skippy_status skippy_trim_session( +@@ -900,331 +786,4 @@ enum skippy_status skippy_trim_session( return skippy_success(out_error); } @@ -1280,7 +1280,7 @@ index 44b924b0b45ce004e3ea3408f024d2f5185d6edd..a36c31925ab4906d3dd1e5d59a216c49 - } // extern "C" diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp -index e271852ff0286fde08f61bdc18565c19b063d5a2..806e79d72ec960d12571d2acd2c5ecb22229c49b 100644 +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) { @@ -1342,7 +1342,7 @@ index e271852ff0286fde08f61bdc18565c19b063d5a2..806e79d72ec960d12571d2acd2c5ecb2 } diff --git a/src/skippy/tests/resident_checkpoint_gpu.cpp b/src/skippy/tests/resident_checkpoint_gpu.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..691e92c37c28e0254a97ed306de7476968e7efd1 +index 000000000..691e92c37 --- /dev/null +++ b/src/skippy/tests/resident_checkpoint_gpu.cpp @@ -0,0 +1,287 @@ @@ -1635,7 +1635,7 @@ index 0000000000000000000000000000000000000000..691e92c37c28e0254a97ed306de74769 +} diff --git a/src/skippy/tests/resident_checkpoint_writer.cpp b/src/skippy/tests/resident_checkpoint_writer.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..d08029062144aa15c421dbd6d845bfc8c4229f1b +index 000000000..d08029062 --- /dev/null +++ b/src/skippy/tests/resident_checkpoint_writer.cpp @@ -0,0 +1,126 @@ @@ -1766,7 +1766,7 @@ index 0000000000000000000000000000000000000000..d08029062144aa15c421dbd6d845bfc8 + return 0; +} diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 0c81c9d473c504fe540c0b1a2b79ef1f9aa54443..4c7c891e168e59765050bdb322b0bd425b30767f 100644 +index 0c81c9d47..4c7c891e1 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -5,26 +5,115 @@ @@ -2224,3 +2224,6 @@ index 0c81c9d473c504fe540c0b1a2b79ef1f9aa54443..4c7c891e168e59765050bdb322b0bd42 + } return 0; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0021-skippy-open-models-without-rollback-snapshots-unless.patch b/llama_cpp/patches/0021-skippy-open-models-without-rollback-snapshots-unless.patch index 9aa01492..c461a413 100644 --- a/llama_cpp/patches/0021-skippy-open-models-without-rollback-snapshots-unless.patch +++ b/llama_cpp/patches/0021-skippy-open-models-without-rollback-snapshots-unless.patch @@ -1,4 +1,4 @@ -From 038023133b1e453a199b6bd92dcaa9ef46851faa Mon Sep 17 00:00:00 2001 +From 2f57a6738a260030326559421e181698942a89b9 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 10 Nov 2026 21:05:00 +1100 Subject: [PATCH] skippy: open models without rollback snapshots unless a plan @@ -45,7 +45,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 src/skippy/tests/recurrent_retention.cpp diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index 856c98f97a4ff9853d7777eec51183f48c5039e6..10ea60e7c436c9483b821149f72b582da3733cc7 100644 +index 856c98f97..10ea60e7c 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -125,11 +125,11 @@ struct skippy_runtime_config { @@ -63,10 +63,10 @@ index 856c98f97a4ff9853d7777eec51183f48c5039e6..10ea60e7c436c9483b821149f72b582d /** @brief Sentinel for `skippy_runtime_config` tri-state fields: keep the derived default. */ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 2e85dbfe12ae83a942324304529a6c3c7959d725..fb1c5b560dadc653821969f338d32bf0d5a51a15 100644 +index 85a8a59cc..d48a6ebaf 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -435,6 +435,33 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -444,6 +444,33 @@ 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) @@ -101,7 +101,7 @@ index 2e85dbfe12ae83a942324304529a6c3c7959d725..fb1c5b560dadc653821969f338d32bf0 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 8a1b320ff3e5fe0d410aa82c4b86d67d70dd4b89..9658800712be5cf26a689ecdd871bae6db0b6345 100644 +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( @@ -123,7 +123,7 @@ index 8a1b320ff3e5fe0d410aa82c4b86d67d70dd4b89..9658800712be5cf26a689ecdd871bae6 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 5bfd47c93c06128b7a0a4f00f81e2abf1931ca6e..bbc1c2d4204ec72a331fab992a8abce333e5eeec 100644 +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) { @@ -170,7 +170,7 @@ index 5bfd47c93c06128b7a0a4f00f81e2abf1931ca6e..bbc1c2d4204ec72a331fab992a8abce3 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 0000000000000000000000000000000000000000..b234872a70e8e97d211ecd317fbb3c317d77a1f9 +index 000000000..b234872a7 --- /dev/null +++ b/src/skippy/tests/backend_sample_capacity.cpp @@ -0,0 +1,251 @@ @@ -427,7 +427,7 @@ index 0000000000000000000000000000000000000000..b234872a70e8e97d211ecd317fbb3c31 +} diff --git a/src/skippy/tests/recurrent_retention.cpp b/src/skippy/tests/recurrent_retention.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..f78090f2cb1983e0fb8f725d72440a7fa7455021 +index 000000000..f78090f2c --- /dev/null +++ b/src/skippy/tests/recurrent_retention.cpp @@ -0,0 +1,338 @@ @@ -769,3 +769,6 @@ index 0000000000000000000000000000000000000000..f78090f2cb1983e0fb8f725d72440a7f + std::fprintf(stderr, "RECURRENT_RETENTION defaults=2 explicit_off=0 positive=1 teacher_steps=32 PASS\n"); + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0022-skippy-report-native-trace-spans-and-GPU-command-tim.patch b/llama_cpp/patches/0022-skippy-report-native-trace-spans-and-GPU-command-tim.patch index 11069c71..329423b2 100644 --- a/llama_cpp/patches/0022-skippy-report-native-trace-spans-and-GPU-command-tim.patch +++ b/llama_cpp/patches/0022-skippy-report-native-trace-spans-and-GPU-command-tim.patch @@ -1,4 +1,4 @@ -From d736fc4aa2e40b8924fc944fb4f6ce5ace1537d2 Mon Sep 17 00:00:00 2001 +From aaa47adb2a937814011661011187b533cebaa069 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 2 Nov 2026 09:00:00 +1100 Subject: [PATCH] skippy: report native trace spans and GPU command timing @@ -110,7 +110,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 tests/test-skippy-tracing.cpp diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h -index 60096c0df2d86f735355acb9744d3c1e4115c711..c73210ab5baa4c10e76e8e6ea330c83dd47cf6d5 100644 +index 60096c0df..c73210ab5 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -270,6 +270,111 @@ extern "C" { @@ -226,7 +226,7 @@ index 60096c0df2d86f735355acb9744d3c1e4115c711..c73210ab5baa4c10e76e8e6ea330c83d // Backend registry // diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt -index 14168ffec1516f46f2f0f4cfd2585643bc3fc159..bcd43abd6e35245b4e18b1856d6de8d70e8c6575 100644 +index 14168ffec..bcd43abd6 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 @@ -238,7 +238,7 @@ index 14168ffec1516f46f2f0f4cfd2585643bc3fc159..bcd43abd6e35245b4e18b1856d6de8d7 ) diff --git a/ggml/src/ggml-metal/ggml-metal-context.m b/ggml/src/ggml-metal/ggml-metal-context.m -index b3506772427d512633115a6fed61f87dc1255fdd..539aca1614ccb4f4dc6d3cef94ffd8333765bf5a 100644 +index b35067724..539aca161 100644 --- a/ggml/src/ggml-metal/ggml-metal-context.m +++ b/ggml/src/ggml-metal/ggml-metal-context.m @@ -7,6 +7,7 @@ @@ -462,7 +462,7 @@ index b3506772427d512633115a6fed61f87dc1255fdd..539aca1614ccb4f4dc6d3cef94ffd833 [cmd_buf commit]; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m -index b03b925c650ca5ab45c9f6b49280a5e8742a8fcf..52fe84b044002cc9d90810c3735790323e176412 100644 +index b03b925c6..52fe84b04 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -5,6 +5,7 @@ @@ -562,7 +562,7 @@ index b03b925c650ca5ab45c9f6b49280a5e8742a8fcf..52fe84b044002cc9d90810c373579032 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 0000000000000000000000000000000000000000..8bf274932ded2425d57ff2ffc503a52f11d50d1f +index 000000000..8bf274932 --- /dev/null +++ b/ggml/src/ggml-metal/ggml-metal-timing.cpp @@ -0,0 +1,529 @@ @@ -1097,7 +1097,7 @@ index 0000000000000000000000000000000000000000..8bf274932ded2425d57ff2ffc503a52f +} 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 0000000000000000000000000000000000000000..3cbe29099d2d332bdaf4fdac4d0192b8eb64eeae +index 000000000..3cbe29099 --- /dev/null +++ b/ggml/src/ggml-metal/ggml-metal-timing.h @@ -0,0 +1,102 @@ @@ -1204,7 +1204,7 @@ index 0000000000000000000000000000000000000000..3cbe29099d2d332bdaf4fdac4d0192b8 +} +#endif diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp -index ad75738511e1ea131b394c6953d57b7cafbdeef4..c54e571c84e773c65b6a880628a2a729880ad04d 100644 +index ad7573851..c54e571c8 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -7,6 +7,7 @@ @@ -1232,7 +1232,7 @@ index ad75738511e1ea131b394c6953d57b7cafbdeef4..c54e571c84e773c65b6a880628a2a729 return (void *)ggml_backend_metal_tuning_set_fa_vec_override; } diff --git a/include/skippy.h b/include/skippy.h -index dc8cbb431d31b21358507ce9136debd0fbe1fbbf..8d710ed646eb00880f69437e5a2130d6ab423047 100644 +index dc8cbb431..8d710ed64 100644 --- a/include/skippy.h +++ b/include/skippy.h @@ -12,6 +12,7 @@ @@ -1244,7 +1244,7 @@ index dc8cbb431d31b21358507ce9136debd0fbe1fbbf..8d710ed646eb00880f69437e5a2130d6 #include "skippy/runtime.h" #include "skippy/model_source.h" diff --git a/include/skippy/common.h b/include/skippy/common.h -index cbba9184990715d863c59a19fa68a3a08f72d591..0e7b4f8a2bd23f59f547d121309f79ac66dee349 100644 +index cbba91849..0e7b4f8a2 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -102,6 +102,8 @@ enum skippy_feature { @@ -1258,7 +1258,7 @@ index cbba9184990715d863c59a19fa68a3a08f72d591..0e7b4f8a2bd23f59f547d121309f79ac #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 0000000000000000000000000000000000000000..e9e57357c8c752581566e1cfa902f6c44b60eee3 +index 000000000..e9e57357c --- /dev/null +++ b/include/skippy/tracing.h @@ -0,0 +1,197 @@ @@ -1460,7 +1460,7 @@ index 0000000000000000000000000000000000000000..e9e57357c8c752581566e1cfa902f6c4 + +#endif // SKIPPY_TRACING_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index fb1c5b560dadc653821969f338d32bf0d5a51a15..9321a210276735bd66baaf3fac66c17aec3b47a9 100644 +index d48a6ebaf..552cc30e3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -64,6 +64,7 @@ add_library(llama @@ -1472,7 +1472,7 @@ index fb1c5b560dadc653821969f338d32bf0d5a51a15..9321a210276735bd66baaf3fac66c17a skippy/graph_dependencies.cpp skippy/graph_identity.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96d5b33624 100644 +index 768e14a25..d5ac1a638 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -17,6 +17,7 @@ @@ -1596,7 +1596,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 if (status != GGML_STATUS_SUCCESS) { LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status); ret = status; -@@ -2286,6 +2314,8 @@ int llama_context::decode( +@@ -2289,6 +2317,8 @@ int llama_context::decode( return encode(batch_inp, graph_build_inputs); } @@ -1605,7 +1605,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; -@@ -2352,12 +2382,14 @@ int llama_context::decode( +@@ -2355,12 +2385,14 @@ int llama_context::decode( } } @@ -1620,7 +1620,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 const uint32_t n_tokens_all = balloc->get_n_tokens(); const uint32_t n_outputs_all = balloc->get_n_outputs(); -@@ -2398,6 +2430,8 @@ int llama_context::decode( +@@ -2406,6 +2438,8 @@ int llama_context::decode( llama_memory_context_ptr mctx; @@ -1629,7 +1629,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 while (true) { mctx = memory->init_batch(*balloc, cparams.n_ubatch, embd_all); if (!mctx) { -@@ -2441,11 +2475,15 @@ int llama_context::decode( +@@ -2449,11 +2483,15 @@ int llama_context::decode( break; } @@ -1645,7 +1645,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 int64_t n_outputs_prev = 0; int64_t n_tokens_prev = 0; -@@ -2548,6 +2586,9 @@ int llama_context::decode( +@@ -2556,6 +2594,9 @@ int llama_context::decode( // ggml_graph_dump_dot(gf, NULL, "llama.dot"); //} @@ -1655,7 +1655,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 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; -@@ -2687,10 +2728,13 @@ int llama_context::decode( +@@ -2695,10 +2736,13 @@ int llama_context::decode( copy_tensor_async_rows(res->t_candidates, sampling.candidates, stride, n_outputs_prev, sched.get(), &sampling.candidates_count); } @@ -1669,7 +1669,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 ggml_backend_sched_synchronize(sched.get()); } } while (mctx->next()); -@@ -3242,6 +3286,8 @@ ggml_cgraph * llama_context::graph_reserve(uint32_t n_t +@@ -3250,6 +3294,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); @@ -1678,7 +1678,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 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); -@@ -4269,6 +4315,7 @@ size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_fl +@@ -4277,6 +4323,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) { @@ -1686,7 +1686,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 std::unique_ptr io; if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { io = std::make_unique(dst, size, mem_storage[seq_id]); -@@ -4288,6 +4335,7 @@ size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, siz +@@ -4296,6 +4343,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) { @@ -1695,7 +1695,7 @@ index 9b1c1a4df93182f4634e7c798f3ddc4fcd883c29..26e1a100cc67977e07f6cc0793ad1d96 try { diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index 8d1e65c6d13dda36a1ca3312400b556face77afc..da0994238f7aae8591bd9ad1e6098dbeb8a585d1 100644 +index 8d1e65c6d..da0994238 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1,4 +1,5 @@ @@ -1777,7 +1777,7 @@ index 8d1e65c6d13dda36a1ca3312400b556face77afc..da0994238f7aae8591bd9ad1e6098dbe } diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp -index 5c0e32e03749fade7af0bb042bd656e061b9d517..3f4e7a9d64d9b890ec585b45361dc2ce3025bdb5 100644 +index 5c0e32e03..3f4e7a9d6 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -1,4 +1,5 @@ @@ -1843,7 +1843,7 @@ index 5c0e32e03749fade7af0bb042bd656e061b9d517..3f4e7a9d64d9b890ec585b45361dc2ce uint32_t cell_count; diff --git a/src/llama-model.cpp b/src/llama-model.cpp -index 6fb12e12793b8d63e700a15fa48f0c1e9ddd3676..f522436951c2f5d15b97d2d0d268e461c85418a4 100644 +index 6fb12e127..f52243695 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1,4 +1,5 @@ @@ -1867,7 +1867,7 @@ index 6fb12e12793b8d63e700a15fa48f0c1e9ddd3676..f522436951c2f5d15b97d2d0d268e461 if (use_mmap_buffer) { for (auto & mapping : ml.mappings) { diff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp -index d8cd441a55838e9b5b53ecf23a0f2be901787504..e52a94cd385e78ece504140bed8ef07c4189146d 100644 +index d8cd441a5..e52a94cd3 100644 --- a/src/llama-sampler.cpp +++ b/src/llama-sampler.cpp @@ -1,4 +1,5 @@ @@ -1911,7 +1911,7 @@ index d8cd441a55838e9b5b53ecf23a0f2be901787504..e52a94cd385e78ece504140bed8ef07c } } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp -index 674daaa23fd7a78c06705d1e5f79ec2520083a6b..6f168fa5535c55014f8d5103ae37ec6a572f877a 100644 +index 674daaa23..6f168fa55 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -1,4 +1,5 @@ @@ -1929,7 +1929,7 @@ index 674daaa23fd7a78c06705d1e5f79ec2520083a6b..6f168fa5535c55014f8d5103ae37ec6a } diff --git a/src/llama.cpp b/src/llama.cpp -index 10beaeed437b806f70d4cf4382ef41a5b09334ee..bad9730ba0830c202cce3eb77225131aa8db4812 100644 +index 10beaeed4..bad9730ba 100644 --- a/src/llama.cpp +++ b/src/llama.cpp @@ -1,4 +1,5 @@ @@ -1980,7 +1980,7 @@ index 10beaeed437b806f70d4cf4382ef41a5b09334ee..bad9730ba0830c202cce3eb77225131a return {0, model_ptr.release()}; } catch (const std::exception & err) { diff --git a/src/skippy/abi.cpp b/src/skippy/abi.cpp -index ceed6e5d36ca9521bbba0d32a176defb2a425b3b..15c5c343bc42e295cb01a435d71b6d3b59096c3f 100644 +index ceed6e5d3..15c5c343b 100644 --- a/src/skippy/abi.cpp +++ b/src/skippy/abi.cpp @@ -43,6 +43,7 @@ uint64_t skippy_abi_features(void) { @@ -1992,7 +1992,7 @@ index ceed6e5d36ca9521bbba0d32a176defb2a425b3b..15c5c343bc42e295cb01a435d71b6d3b SKIPPY_FEATURE_UNLOAD_EVENTS | SKIPPY_FEATURE_NON_CHAT_WORKLOADS | diff --git a/src/skippy/activation.cpp b/src/skippy/activation.cpp -index 7167e5f7a49541628823aee6dd5a695ec183f4d4..885b602e99b087b474437767e086e536f819a2a5 100644 +index 7167e5f7a..885b602e9 100644 --- a/src/skippy/activation.cpp +++ b/src/skippy/activation.cpp @@ -7,6 +7,7 @@ @@ -2020,7 +2020,7 @@ index 7167e5f7a49541628823aee6dd5a695ec183f4d4..885b602e99b087b474437767e086e536 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 40faff815be00b44a316945bcf7d345cb008b9ce..a3154065215415d29def38414375bcb7dcc2ff05 100644 +index 7d7973520..2d34652b9 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -6,6 +6,7 @@ @@ -2048,17 +2048,17 @@ index 40faff815be00b44a316945bcf7d345cb008b9ce..a3154065215415d29def38414375bcb7 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 bbc1c2d4204ec72a331fab992a8abce333e5eeec..a4bf2a4756970f79ae7ea59680de0f49da59dd17 100644 +index bbc1c2d42..a4bf2a475 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -22,6 +22,7 @@ @@ -2153,7 +2153,7 @@ index bbc1c2d4204ec72a331fab992a8abce333e5eeec..a4bf2a4756970f79ae7ea59680de0f49 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 b688fce731da6af004ad3d6444cd9d679a890324..671ccbb3cc487caff8774de0420d26c5fb43063d 100644 +index b688fce73..671ccbb3c 100644 --- a/src/skippy/sampling.cpp +++ b/src/skippy/sampling.cpp @@ -7,6 +7,7 @@ @@ -2173,7 +2173,7 @@ index b688fce731da6af004ad3d6444cd9d679a890324..671ccbb3cc487caff8774de0420d26c5 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 7f55c0d88d493f9d9aae9245877dd208bbfcf54e..3fb86667d61e1c68748faa9133a7952ebd4af596 100644 +index 7f55c0d88..3fb86667d 100644 --- a/src/skippy/speculative_decoding.cpp +++ b/src/skippy/speculative_decoding.cpp @@ -6,6 +6,7 @@ @@ -2194,7 +2194,7 @@ index 7f55c0d88d493f9d9aae9245877dd208bbfcf54e..3fb86667d61e1c68748faa9133a7952e return SKIPPY_STATUS_INVALID_ARGUMENT; diff --git a/src/skippy/trace_scope.h b/src/skippy/trace_scope.h new file mode 100644 -index 0000000000000000000000000000000000000000..b64d9da37e7f08800fee12329d90e6835b7e7d43 +index 000000000..b64d9da37 --- /dev/null +++ b/src/skippy/trace_scope.h @@ -0,0 +1,61 @@ @@ -2261,7 +2261,7 @@ index 0000000000000000000000000000000000000000..b64d9da37e7f08800fee12329d90e683 +} // namespace skippy_trace diff --git a/src/skippy/tracing.cpp b/src/skippy/tracing.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..9aa48e08c0710174796a9bf7c1303810361a833d +index 000000000..9aa48e08c --- /dev/null +++ b/src/skippy/tracing.cpp @@ -0,0 +1,272 @@ @@ -2538,7 +2538,7 @@ index 0000000000000000000000000000000000000000..9aa48e08c0710174796a9bf7c1303810 + } +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 2e017268d51396c450c2d12b672f6ea29ff962db..c152c27d5de2d8a5f0ef291a14d7b04254004525 100644 +index 2e017268d..c152c27d5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -185,6 +185,9 @@ llama_build_and_test(test-skippy-rerank-template.cpp) @@ -2561,7 +2561,7 @@ index 2e017268d51396c450c2d12b672f6ea29ff962db..c152c27d5de2d8a5f0ef291a14d7b042 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 0000000000000000000000000000000000000000..365052e0ed4accc3789f38664163f2c90798d943 +index 000000000..365052e0e --- /dev/null +++ b/tests/test-skippy-tracing-metal.cpp @@ -0,0 +1,155 @@ @@ -2722,7 +2722,7 @@ index 0000000000000000000000000000000000000000..365052e0ed4accc3789f38664163f2c9 +} diff --git a/tests/test-skippy-tracing.cpp b/tests/test-skippy-tracing.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..804c2f7e0405196fc1f2bc665f0471335b90d6ae +index 000000000..804c2f7e0 --- /dev/null +++ b/tests/test-skippy-tracing.cpp @@ -0,0 +1,306 @@ @@ -3032,3 +3032,6 @@ index 0000000000000000000000000000000000000000..804c2f7e0405196fc1f2bc665f047133 + std::printf("ok\n"); + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0023-skippy-sample-a-batch-s-requests-concurrently.patch b/llama_cpp/patches/0023-skippy-sample-a-batch-s-requests-concurrently.patch index 01c0b80b..ab8e8ea1 100644 --- a/llama_cpp/patches/0023-skippy-sample-a-batch-s-requests-concurrently.patch +++ b/llama_cpp/patches/0023-skippy-sample-a-batch-s-requests-concurrently.patch @@ -1,4 +1,4 @@ -From 6c0921cf784408859f1be351a216a8f30b917b47 Mon Sep 17 00:00:00 2001 +From 8774fadb92fffa8e0023134427bae801044e2492 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 5 Nov 2026 01:00:00 +1100 Subject: [PATCH] skippy: sample a batch's requests concurrently @@ -47,7 +47,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 9321a210276735bd66baaf3fac66c17aec3b47a9..e17e72c3154184acc50b205442799487d1c2f6aa 100644 +index 552cc30e3..a7f3e7fbf 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -82,6 +82,7 @@ add_library(llama @@ -58,7 +58,7 @@ index 9321a210276735bd66baaf3fac66c17aec3b47a9..e17e72c3154184acc50b205442799487 skippy/sampling_config.cpp skippy/chat_sampling.cpp skippy/sampling_vocab.cpp -@@ -494,6 +495,17 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -503,6 +504,17 @@ if (LLAMA_STAGE_BUILD_TESTS) endfunction() add_skippy_sampling_history_state_tests(granitehybrid skippy-noalloc-granite-hybrid-fixture recurrent) @@ -77,7 +77,7 @@ index 9321a210276735bd66baaf3fac66c17aec3b47a9..e17e72c3154184acc50b205442799487 NAME skippy_generate_qwen3_fixture COMMAND skippy-model-fixture-generator diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 26e1a100cc67977e07f6cc0793ad1d96d5b33624..8e53a0d5f3e8b6fe91ee2d105954316df0c4ed07 100644 +index d5ac1a638..f3400263e 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1020,8 +1020,26 @@ void llama_context::sched_reserve(const skippy_graph_build_inputs & graph_build_ @@ -108,7 +108,7 @@ index 26e1a100cc67977e07f6cc0793ad1d96d5b33624..8e53a0d5f3e8b6fe91ee2d105954316d return; } -@@ -3022,6 +3040,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to +@@ -3030,6 +3048,9 @@ bool llama_context::extract_layer_inputs(const llm_graph_result * res, size_t to } void llama_context::output_reorder() { @@ -119,7 +119,7 @@ index 26e1a100cc67977e07f6cc0793ad1d96d5b33624..8e53a0d5f3e8b6fe91ee2d105954316d 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 75cea4e84b48484ab40020c4508219d9ee97acb3..e09428d41be74052aadb0b914977b376c7b3e6be 100644 +index 75cea4e84..e09428d41 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -66,6 +66,36 @@ struct llama_memory_buffer { @@ -171,7 +171,7 @@ index 75cea4e84b48484ab40020c4508219d9ee97acb3..e09428d41be74052aadb0b914977b376 const skippy_graph_build_inputs & get_graph_build_inputs() const; diff --git a/src/skippy/batch_sampling.cpp b/src/skippy/batch_sampling.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..e59c898575ea262476bad7c3719119d3f45d9440 +index 000000000..e59c89857 --- /dev/null +++ b/src/skippy/batch_sampling.cpp @@ -0,0 +1,91 @@ @@ -268,7 +268,7 @@ index 0000000000000000000000000000000000000000..e59c898575ea262476bad7c3719119d3 +} diff --git a/src/skippy/batch_sampling.h b/src/skippy/batch_sampling.h new file mode 100644 -index 0000000000000000000000000000000000000000..0c253ca71c614dffa4e31d6665c3d14336f7535e +index 000000000..0c253ca71 --- /dev/null +++ b/src/skippy/batch_sampling.h @@ -0,0 +1,20 @@ @@ -293,7 +293,7 @@ index 0000000000000000000000000000000000000000..0c253ca71c614dffa4e31d6665c3d143 +// 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 a3154065215415d29def38414375bcb7dcc2ff05..83c290ee273c9c104a67d9345404f10e485adee8 100644 +index 2d34652b9..46b0d1a27 100644 --- a/src/skippy/execution-batch.cpp +++ b/src/skippy/execution-batch.cpp @@ -1,5 +1,6 @@ @@ -303,7 +303,7 @@ index a3154065215415d29def38414375bcb7dcc2ff05..83c290ee273c9c104a67d9345404f10e #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)); @@ -312,10 +312,10 @@ index a3154065215415d29def38414375bcb7dcc2ff05..83c290ee273c9c104a67d9345404f10e + // 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. @@ -344,7 +344,7 @@ index a3154065215415d29def38414375bcb7dcc2ff05..83c290ee273c9c104a67d9345404f10e } diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp -index 671ccbb3cc487caff8774de0420d26c5fb43063d..d9f980c394c805284bc274f28ad940f723f6a255 100644 +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( @@ -407,7 +407,7 @@ index 671ccbb3cc487caff8774de0420d26c5fb43063d..d9f980c394c805284bc274f28ad940f7 } if (skippy_ensure_plain_sampling_chain(session, sampling)) { diff --git a/src/skippy/sampling_internal.h b/src/skippy/sampling_internal.h -index 7bbf160164aa3c25d33ab90dcad39d63f5250847..38621b6e923e0b588baa08ee486d9b86f0114d0d 100644 +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( @@ -423,7 +423,7 @@ index 7bbf160164aa3c25d33ab90dcad39d63f5250847..38621b6e923e0b588baa08ee486d9b86 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 0000000000000000000000000000000000000000..0e19dbce58746265b7ac566eb6a126f3c95e42fa +index 000000000..0e19dbce5 --- /dev/null +++ b/src/skippy/tests/concurrent_sampling.cpp @@ -0,0 +1,175 @@ @@ -602,3 +602,6 @@ index 0000000000000000000000000000000000000000..0e19dbce58746265b7ac566eb6a126f3 + std::printf("ok\n"); + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0024-skippy-trace-K-V-row-list-runs.patch b/llama_cpp/patches/0024-skippy-trace-K-V-row-list-runs.patch index 9c57362d..87ec0d91 100644 --- a/llama_cpp/patches/0024-skippy-trace-K-V-row-list-runs.patch +++ b/llama_cpp/patches/0024-skippy-trace-K-V-row-list-runs.patch @@ -1,4 +1,4 @@ -From 7c5c8a419219716fc1c0e1244380474d462c0f8f Mon Sep 17 00:00:00 2001 +From abc388e18575fa4a332bc5f804cffa163685be2e Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sat, 7 Nov 2026 19:12:33 +1100 Subject: [PATCH] skippy: trace K/V row-list runs @@ -26,7 +26,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 src/skippy/kv_rows_trace.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index e17e72c3154184acc50b205442799487d1c2f6aa..c6675d944001872c468294ca87bddb4f3b1d7a5b 100644 +index a7f3e7fbf..ef3526dee 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -65,6 +65,7 @@ add_library(llama @@ -38,7 +38,7 @@ index e17e72c3154184acc50b205442799487d1c2f6aa..c6675d944001872c468294ca87bddb4f skippy/graph_dependencies.cpp skippy/graph_identity.cpp diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index da0994238f7aae8591bd9ad1e6098dbeb8a585d1..389b920d860cbfa3717a974ef0730650be001c92 100644 +index da0994238..389b920d8 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1,4 +1,5 @@ @@ -57,7 +57,7 @@ index da0994238f7aae8591bd9ad1e6098dbeb8a585d1..389b920d860cbfa3717a974ef0730650 // 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 0000000000000000000000000000000000000000..e5f06b61424c05d1d396932737f36ff1f2dc8df8 +index 000000000..e5f06b614 --- /dev/null +++ b/src/skippy/kv_rows_trace.cpp @@ -0,0 +1,41 @@ @@ -104,7 +104,7 @@ index 0000000000000000000000000000000000000000..e5f06b61424c05d1d396932737f36ff1 +} diff --git a/src/skippy/kv_rows_trace.h b/src/skippy/kv_rows_trace.h new file mode 100644 -index 0000000000000000000000000000000000000000..537a4f4cd2a742b0268801eb0572c42cbfd73095 +index 000000000..537a4f4cd --- /dev/null +++ b/src/skippy/kv_rows_trace.h @@ -0,0 +1,7 @@ @@ -116,7 +116,7 @@ index 0000000000000000000000000000000000000000..537a4f4cd2a742b0268801eb0572c42c +// `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 b64d9da37e7f08800fee12329d90e6835b7e7d43..6e6641571bd6d7baa47e824b058b31ac75c1ad3c 100644 +index b64d9da37..6e6641571 100644 --- a/src/skippy/trace_scope.h +++ b/src/skippy/trace_scope.h @@ -44,6 +44,9 @@ class scope { @@ -130,7 +130,7 @@ index b64d9da37e7f08800fee12329d90e6835b7e7d43..6e6641571bd6d7baa47e824b058b31ac // 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 9aa48e08c0710174796a9bf7c1303810361a833d..29e9047b1efd97cd7087aa8953c5a50aff7661bf 100644 +index 9aa48e08c..29e9047b1 100644 --- a/src/skippy/tracing.cpp +++ b/src/skippy/tracing.cpp @@ -199,6 +199,10 @@ uint64_t current_parent() noexcept { @@ -144,3 +144,6 @@ index 9aa48e08c0710174796a9bf7c1303810361a833d..29e9047b1efd97cd7087aa8953c5a50a adopt::adopt(uint64_t parent) noexcept : previous_(t_current) { if (parent != 0) { t_current = parent; +-- +2.56.0 + diff --git a/llama_cpp/patches/0025-ggml-metal-read-consecutive-row-list-blocks-like-den.patch b/llama_cpp/patches/0025-ggml-metal-read-consecutive-row-list-blocks-like-den.patch index f4fea78e..e27acc20 100644 --- a/llama_cpp/patches/0025-ggml-metal-read-consecutive-row-list-blocks-like-den.patch +++ b/llama_cpp/patches/0025-ggml-metal-read-consecutive-row-list-blocks-like-den.patch @@ -1,4 +1,4 @@ -From 2b80360c802553d74f57ca63e5af60a859aad5c4 Mon Sep 17 00:00:00 2001 +From fb9178cc6b3c73f24001fa4e8b3fb8cf92f9c7af Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sat, 7 Nov 2026 21:19:15 +1100 Subject: [PATCH] ggml-metal: read consecutive row-list blocks like dense @@ -22,7 +22,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 cf37e492442b2088b41947c3692954fd94b6de6d..a67106b832d69820bb3ea350f06a61e92c15792a 100644 +index cf37e4924..a67106b83 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -237,8 +237,23 @@ kernel void kernel_flash_attn_ext_vec( @@ -107,3 +107,6 @@ index cf37e492442b2088b41947c3692954fd94b6de6d..a67106b832d69820bb3ea350f06a61e9 FOR_UNROLL (short ii = 0; ii < DV4/NL; ++ii) { const short i = ii*NL + tx; +-- +2.56.0 + diff --git a/llama_cpp/patches/0026-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch b/llama_cpp/patches/0026-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch index da3034fd..3b016285 100644 --- a/llama_cpp/patches/0026-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch +++ b/llama_cpp/patches/0026-llama-keep-a-sequence-s-unified-pool-cells-in-chunks.patch @@ -1,4 +1,4 @@ -From 0be2345ac17c5d59c486d753b77fc36aa5371a65 Mon Sep 17 00:00:00 2001 +From 468eddd74583c8eb773ef0ac1eaca9a212676d67 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sat, 7 Nov 2026 21:27:50 +1100 Subject: [PATCH] llama: keep a sequence's unified-pool cells in chunks @@ -20,7 +20,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 3 files changed, 115 insertions(+) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index 389b920d860cbfa3717a974ef0730650be001c92..fea9e839c997fe2af3ec8de6b98851ed0d59a93b 100644 +index 389b920d8..fea9e839c 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -9,6 +9,7 @@ @@ -129,7 +129,7 @@ index 389b920d860cbfa3717a974ef0730650be001c92..fea9e839c997fe2af3ec8de6b98851ed // 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 0d683ec3e0630c7e3f353837686216752ab7ee71..a6da0bf9b2064f5a1d27ec3344b3fcb64a1793d4 100644 +index 0d683ec3e..a6da0bf9b 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -275,6 +275,13 @@ public: @@ -147,7 +147,7 @@ index 0d683ec3e0630c7e3f353837686216752ab7ee71..a6da0bf9b2064f5a1d27ec3344b3fcb6 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 4fcb33d167cce985bd5d1a487578b8fc27f204ec..6b15791a4b42a7ac740be481a328382fe8295d4c 100644 +index 4fcb33d16..6b15791a4 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -42,6 +42,17 @@ static inline int ctz64(uint64_t x) { @@ -188,3 +188,6 @@ index 4fcb33d167cce985bd5d1a487578b8fc27f204ec..6b15791a4b42a7ac740be481a328382f // note: call only if the cell is not empty llama_pos pos_get(uint32_t i) const { assert(i < pos.size()); +-- +2.56.0 + diff --git a/llama_cpp/patches/0027-ggml-metal-compile-a-gather-free-row-list-attention-.patch b/llama_cpp/patches/0027-ggml-metal-compile-a-gather-free-row-list-attention-.patch index c690d7a8..4db671a3 100644 --- a/llama_cpp/patches/0027-ggml-metal-compile-a-gather-free-row-list-attention-.patch +++ b/llama_cpp/patches/0027-ggml-metal-compile-a-gather-free-row-list-attention-.patch @@ -1,4 +1,4 @@ -From 329a5234e153a812e9a18ec1c0799708f764f898 Mon Sep 17 00:00:00 2001 +From 39b4ed13be8fa504ccf4ebad86964529d782ef07 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 10:55:48 +1100 Subject: [PATCH] ggml-metal: compile a gather-free row-list attention variant @@ -23,7 +23,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 c3d4f8ef585a865b87a90c6a4c2744feb23440f2..77dbbe7a04cf21f354c8955a93bb5db979bb1526 100644 +index c3d4f8ef5..77dbbe7a0 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -2085,6 +2085,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v @@ -60,7 +60,7 @@ index c3d4f8ef585a865b87a90c6a4c2744feb23440f2..77dbbe7a04cf21f354c8955a93bb5db9 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 009b4ce2ef4dc9757a061d0e7784a2395c4a0a43..2bbead4b54ccde59ed531fff960277ec98244deb 100644 +index 009b4ce2e..2bbead4b5 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -241,6 +241,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att @@ -72,7 +72,7 @@ index 009b4ce2ef4dc9757a061d0e7784a2395c4a0a43..2bbead4b54ccde59ed531fff960277ec 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 81b6237acf5a98219017c764ce08a46e93ddcd8b..9d177288dc3f3657bfbe8b7193e1f7325628b1fc 100644 +index 81b6237ac..9d177288d 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3685,6 +3685,25 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { @@ -120,7 +120,7 @@ index 81b6237acf5a98219017c764ce08a46e93ddcd8b..9d177288dc3f3657bfbe8b7193e1f732 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 a67106b832d69820bb3ea350f06a61e92c15792a..adfe8d816940266332789bdd9e25aa11f8d780bf 100644 +index a67106b83..adfe8d816 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 @@ -156,3 +156,6 @@ index a67106b832d69820bb3ea350f06a61e92c15792a..adfe8d816940266332789bdd9e25aa11 const int icr = rows_base >= 0 ? rows_base : ic; // load the KV row indices of a gathered block into shared memory +-- +2.56.0 + diff --git a/llama_cpp/patches/0028-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch b/llama_cpp/patches/0028-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch index d19f6db4..edc9ad72 100644 --- a/llama_cpp/patches/0028-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch +++ b/llama_cpp/patches/0028-ggml-metal-let-GGML_METAL_CAPTURE_DIR-choose-where-a.patch @@ -1,4 +1,4 @@ -From 76a33df3f2aae5785ac0febe1b6545aa7eda36d8 Mon Sep 17 00:00:00 2001 +From cab7580b8b8255c57f97025f43259df1a37d083b Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 11:03:23 +1100 Subject: [PATCH] ggml-metal: let GGML_METAL_CAPTURE_DIR choose where a capture @@ -15,7 +15,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 539aca1614ccb4f4dc6d3cef94ffd8333765bf5a..fdaf0fc14d977c1e657720ad3d042dea2e643462 100644 +index 539aca161..fdaf0fc14 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 * @@ -30,3 +30,6 @@ index 539aca1614ccb4f4dc6d3cef94ffd8333765bf5a..fdaf0fc14d977c1e657720ad3d042dea GGML_LOG_WARN("%s: capturing graph in %s\n", __func__, [path UTF8String]); +-- +2.56.0 + diff --git a/llama_cpp/patches/0029-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch b/llama_cpp/patches/0029-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch index 2545506a..9ae2ad9a 100644 --- a/llama_cpp/patches/0029-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch +++ b/llama_cpp/patches/0029-tests-per-call-cost-of-ordinary-vs-row-list-decode-a.patch @@ -1,4 +1,4 @@ -From 4db755deb0237e0ededd0004ec0480bf67c40372 Mon Sep 17 00:00:00 2001 +From 217bec64254227dccbe34b1046ef3a1c63740617 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 11:52:39 +1100 Subject: [PATCH] tests: per-call cost of ordinary vs row-list decode attention @@ -18,7 +18,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 tests/test-flash-attn-rows-perf.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index c152c27d5de2d8a5f0ef291a14d7b04254004525..71349552962c849a6d496de7d6ddbc1cf3ab5a56 100644 +index c152c27d5..713495529 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -416,6 +416,8 @@ llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) @@ -32,7 +32,7 @@ index c152c27d5de2d8a5f0ef291a14d7b04254004525..71349552962c849a6d496de7d6ddbc1c llama_build_and_test(test-llama-mmap.cpp ${PROJECT_SOURCE_DIR}/src/llama-impl.cpp ${PROJECT_SOURCE_DIR}/src/llama-mmap.cpp LABEL behavior) diff --git a/tests/test-flash-attn-rows-perf.cpp b/tests/test-flash-attn-rows-perf.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..dbffc27e441d894f78b036194c52cf53b08cb8d1 +index 000000000..dbffc27e4 --- /dev/null +++ b/tests/test-flash-attn-rows-perf.cpp @@ -0,0 +1,294 @@ @@ -330,3 +330,6 @@ index 0000000000000000000000000000000000000000..dbffc27e441d894f78b036194c52cf53 + return 1; + } +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0030-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch b/llama_cpp/patches/0030-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch index 2b581529..90475071 100644 --- a/llama_cpp/patches/0030-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch +++ b/llama_cpp/patches/0030-llama-ggml-metal-start-every-row-list-run-on-an-atte.patch @@ -1,4 +1,4 @@ -From 6ae3a2ab4464a3f9478fb17607c3aa79919ea98e Mon Sep 17 00:00:00 2001 +From bc11fe2fa212afbb67dd9d6c26f38e9b2723635b Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 12:17:27 +1100 Subject: [PATCH] llama, ggml-metal: start every row-list run on an attention @@ -33,7 +33,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 9d177288dc3f3657bfbe8b7193e1f7325628b1fc..f1886e9722541e33363a38a810ac7d56d1fd9f39 100644 +index 9d177288d..f1886e972 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3685,19 +3685,29 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { @@ -73,7 +73,7 @@ index 9d177288dc3f3657bfbe8b7193e1f7325628b1fc..f1886e9722541e33363a38a810ac7d56 } } diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal -index adfe8d816940266332789bdd9e25aa11f8d780bf..f61b0b919a879b5f1a49d6e77fef3e742e65f131 100644 +index adfe8d816..f61b0b919 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -246,8 +246,12 @@ kernel void kernel_flash_attn_ext_vec( @@ -91,7 +91,7 @@ index adfe8d816940266332789bdd9e25aa11f8d780bf..f61b0b919a879b5f1a49d6e77fef3e74 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 fea9e839c997fe2af3ec8de6b98851ed0d59a93b..38215348adae1acaf466db01fd0ef68e35a237ca 100644 +index fea9e839c..38215348a 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 { @@ -132,7 +132,7 @@ index fea9e839c997fe2af3ec8de6b98851ed0d59a93b..38215348adae1acaf466db01fd0ef68e } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index a6da0bf9b2064f5a1d27ec3344b3fcb64a1793d4..631adf9d4b826ed1f0131d10b913bccca72e43ba 100644 +index a6da0bf9b..631adf9d4 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -278,6 +278,9 @@ public: @@ -146,7 +146,7 @@ index a6da0bf9b2064f5a1d27ec3344b3fcb64a1793d4..631adf9d4b826ed1f0131d10b913bccc 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 6b15791a4b42a7ac740be481a328382fe8295d4c..8775a4e6bb52842f4e2e8efd4c8728ae01697002 100644 +index 6b15791a4..8775a4e6b 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -511,6 +511,101 @@ public: @@ -252,7 +252,7 @@ index 6b15791a4b42a7ac740be481a328382fe8295d4c..8775a4e6bb52842f4e2e8efd4c8728ae // 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 71349552962c849a6d496de7d6ddbc1cf3ab5a56..26fe9aa16111bcb8d91f7bf0428fbd8a19650a24 100644 +index 713495529..26fe9aa16 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -193,6 +193,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) @@ -264,7 +264,7 @@ index 71349552962c849a6d496de7d6ddbc1cf3ab5a56..26fe9aa16111bcb8d91f7bf0428fbd8a # 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 dbffc27e441d894f78b036194c52cf53b08cb8d1..fd3179a06e78cc0b9fd9aeac4a08800f4777cb50 100644 +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; @@ -318,7 +318,7 @@ index dbffc27e441d894f78b036194c52cf53b08cb8d1..fd3179a06e78cc0b9fd9aeac4a08800f } diff --git a/tests/test-skippy-kv-rows-aligned.cpp b/tests/test-skippy-kv-rows-aligned.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..5cc440ab3bd5988faa6e460d224c3b621ea8ed81 +index 000000000..5cc440ab3 --- /dev/null +++ b/tests/test-skippy-kv-rows-aligned.cpp @@ -0,0 +1,106 @@ @@ -428,3 +428,6 @@ index 0000000000000000000000000000000000000000..5cc440ab3bd5988faa6e460d224c3b62 + std::printf("%s\n", failures ? "FAILED" : "aligned row lists: all checks passed"); + return failures != 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0031-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch b/llama_cpp/patches/0031-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch index 7ec81bbb..430e6a6c 100644 --- a/llama_cpp/patches/0031-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch +++ b/llama_cpp/patches/0031-ggml-metal-GGML_METAL_ROWS_DEBUG-counts-the-row-atte.patch @@ -1,4 +1,4 @@ -From 09c7a9f3078ac4770bf68506f1a6e7ecbf908dbe Mon Sep 17 00:00:00 2001 +From 5bfe73549577f9f3168599ff0089bd5460e7ebad Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 13:07:18 +1100 Subject: [PATCH] ggml-metal: GGML_METAL_ROWS_DEBUG counts the row-attention @@ -15,7 +15,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 f1886e9722541e33363a38a810ac7d56d1fd9f39..1ddc52ed6303a7c9ac46b9ced8d38762f1f7a704 100644 +index f1886e972..1ddc52ed6 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -12,6 +12,8 @@ @@ -72,3 +72,6 @@ index f1886e9722541e33363a38a810ac7d56d1fd9f39..1ddc52ed6303a7c9ac46b9ced8d38762 float scale; float max_bias; +-- +2.56.0 + diff --git a/llama_cpp/patches/0032-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch b/llama_cpp/patches/0032-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch index 78c5cfdb..88fbb6cb 100644 --- a/llama_cpp/patches/0032-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch +++ b/llama_cpp/patches/0032-ggml-skippy-report-every-backend-buffer-s-life-as-a-.patch @@ -1,4 +1,4 @@ -From 67c6ff50d5b6a241090fa3d1901e90c50fb5af71 Mon Sep 17 00:00:00 2001 +From 0075a9dc806e9043f5bfed23cb0e4e23e6f4682d Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 19:48:49 +1100 Subject: [PATCH] ggml, skippy: report every backend buffer's life as a trace @@ -19,7 +19,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 3 files changed, 132 insertions(+) diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h -index c73210ab5baa4c10e76e8e6ea330c83dd47cf6d5..83ad19bea934f83f6d9e2921475925986ae35b77 100644 +index c73210ab5..83ad19bea 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -375,6 +375,35 @@ extern "C" { @@ -59,7 +59,7 @@ index c73210ab5baa4c10e76e8e6ea330c83dd47cf6d5..83ad19bea934f83f6d9e292147592598 // Backend registry // diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp -index c8c05e442267e3b40d5afedefee364911fb82486..7b4d3a6d0da3fdc5435a8c9a52969256aa216dd0 100644 +index c8c05e442..7b4d3a6d0 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -20,6 +20,7 @@ @@ -165,7 +165,7 @@ index c8c05e442267e3b40d5afedefee364911fb82486..7b4d3a6d0da3fdc5435a8c9a52969256 } diff --git a/src/skippy/tracing.cpp b/src/skippy/tracing.cpp -index 29e9047b1efd97cd7087aa8953c5a50aff7661bf..48d827d34436ed1e2bb9515e3da7d34490137c5f 100644 +index 29e9047b1..48d827d34 100644 --- a/src/skippy/tracing.cpp +++ b/src/skippy/tracing.cpp @@ -6,6 +6,7 @@ @@ -225,3 +225,6 @@ index 29e9047b1efd97cd7087aa8953c5a50aff7661bf..48d827d34436ed1e2bb9515e3da7d344 // Skippy and llama report their own spans with or without a backend. return SKIPPY_STATUS_OK; +-- +2.56.0 + diff --git a/llama_cpp/patches/0033-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch b/llama_cpp/patches/0033-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch index 04ab211f..22cc9782 100644 --- a/llama_cpp/patches/0033-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch +++ b/llama_cpp/patches/0033-llama-zero-KV-pool-cells-as-the-high-water-mark-adva.patch @@ -1,4 +1,4 @@ -From 481d210cd4e86058bc8b8d0086e3793573603b15 Mon Sep 17 00:00:00 2001 +From 224131e6edbf4b1a06037441551184fdf30bdb23 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Sun, 8 Nov 2026 20:18:33 +1100 Subject: [PATCH] llama: zero KV pool cells as the high-water mark advances, @@ -34,7 +34,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 6 files changed, 103 insertions(+), 5 deletions(-) diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h -index 83ad19bea934f83f6d9e2921475925986ae35b77..968afd56cdce04506a7c80de360411de9e069117 100644 +index 83ad19bea..968afd56c 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -64,6 +64,8 @@ extern "C" { @@ -47,7 +47,7 @@ index 83ad19bea934f83f6d9e2921475925986ae35b77..968afd56cdce04506a7c80de360411de 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 7b4d3a6d0da3fdc5435a8c9a52969256aa216dd0..bf76ab6cce0c8da2daf3619bea0590d1b65bd27c 100644 +index 7b4d3a6d0..bf76ab6cc 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -386,6 +386,10 @@ size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const st @@ -62,7 +62,7 @@ index 7b4d3a6d0da3fdc5435a8c9a52969256aa216dd0..bf76ab6cce0c8da2daf3619bea0590d1 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 38215348adae1acaf466db01fd0ef68e35a237ca..569aa54b4d950ec6711af877fa1549a0861b080e 100644 +index 38215348a..569aa54b4 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) { @@ -187,7 +187,7 @@ index 38215348adae1acaf466db01fd0ef68e35a237ca..569aa54b4d950ec6711af877fa1549a0 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 631adf9d4b826ed1f0131d10b913bccca72e43ba..7f0ba31bac728c4d17e20c4ee232b109ce9299b1 100644 +index 631adf9d4..7f0ba31ba 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -285,6 +285,21 @@ public: @@ -213,7 +213,7 @@ index 631adf9d4b826ed1f0131d10b913bccca72e43ba..7f0ba31bac728c4d17e20c4ee232b109 void apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch); diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp -index 80099e76ac6c59a77a6ec9cc8741e9536ca764db..46f1697af42c5ef3a66a9eab40eb3b30b86105de 100644 +index 80099e76a..46f1697af 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 @@ -233,7 +233,7 @@ index 80099e76ac6c59a77a6ec9cc8741e9536ca764db..46f1697af42c5ef3a66a9eab40eb3b30 bufs.emplace_back(std::move(ctx), std::move(buf)); diff --git a/src/llama-memory.h b/src/llama-memory.h -index 37d01ed116d2162e0bf96e51e8487d7c059bf708..b6b84c3159d4e08ae54f6826501b24a454e02035 100644 +index 37d01ed11..b6b84c315 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -37,8 +37,9 @@ struct llama_memory_bufs { @@ -247,3 +247,6 @@ index 37d01ed116d2162e0bf96e51e8487d7c059bf708..b6b84c3159d4e08ae54f6826501b24a4 // the memory used by the tensors: the buffer sizes, or the simulated sizes if no_alloc is set std::map memory_breakdown() const; +-- +2.56.0 + diff --git a/llama_cpp/patches/0034-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch b/llama_cpp/patches/0034-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch index 72c0a393..6fffab96 100644 --- a/llama_cpp/patches/0034-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch +++ b/llama_cpp/patches/0034-llama-give-the-pages-of-freed-KV-chunks-back-to-the-.patch @@ -1,4 +1,4 @@ -From 61e0d42ee958d76a1129e1ddf7524651eaa3b8b0 Mon Sep 17 00:00:00 2001 +From f95a3f2882b6438bc7103dfe424657cc16e25c8a Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Mon, 9 Nov 2026 10:27:08 +1100 Subject: [PATCH] llama: give the pages of freed KV chunks back to the kernel @@ -28,7 +28,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 3 files changed, 177 insertions(+), 1 deletion(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index 569aa54b4d950ec6711af877fa1549a0861b080e..1053cebfe58bf82c484e90ca9518d6bfecf28bec 100644 +index 569aa54b4..1053cebfe 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -15,13 +15,66 @@ @@ -254,7 +254,7 @@ index 569aa54b4d950ec6711af877fa1549a0861b080e..1053cebfe58bf82c484e90ca9518d6bf 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 7f0ba31bac728c4d17e20c4ee232b109ce9299b1..21c2e18e5b84fa62bd271135567ce9a84a7d5f79 100644 +index 7f0ba31ba..21c2e18e5 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -5,6 +5,7 @@ @@ -289,7 +289,7 @@ index 7f0ba31bac728c4d17e20c4ee232b109ce9299b1..21c2e18e5b84fa62bd271135567ce9a8 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 8775a4e6bb52842f4e2e8efd4c8728ae01697002..94caf7c83d2f13b6e879905d3f0de2658a027362 100644 +index 8775a4e6b..94caf7c83 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -139,6 +139,13 @@ public: @@ -306,3 +306,6 @@ index 8775a4e6bb52842f4e2e8efd4c8728ae01697002..94caf7c83d2f13b6e879905d3f0de265 uint32_t get_used() const { return used.size(); } +-- +2.56.0 + diff --git a/llama_cpp/patches/0035-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch b/llama_cpp/patches/0035-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch index 80642c0d..bb3030ad 100644 --- a/llama_cpp/patches/0035-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch +++ b/llama_cpp/patches/0035-skippy-size-the-unified-KV-pool-and-choose-its-memor.patch @@ -1,4 +1,4 @@ -From 769b71543d74850115787774d7d239a186eea804 Mon Sep 17 00:00:00 2001 +From 812f1df3d909808cb5d566a18468090f82c8bdbd Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Tue, 10 Nov 2026 17:05:21 +1100 Subject: [PATCH] skippy: size the unified KV pool and choose its memory @@ -56,7 +56,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 9 files changed, 94 insertions(+), 6 deletions(-) diff --git a/include/skippy/common.h b/include/skippy/common.h -index 0e7b4f8a2bd23f59f547d121309f79ac66dee349..b16229b1b78c2df981ca9870f6e4c7357b885af9 100644 +index 0e7b4f8a2..b16229b1b 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -69,7 +69,7 @@ index 0e7b4f8a2bd23f59f547d121309f79ac66dee349..b16229b1b78c2df981ca9870f6e4c735 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index 10ea60e7c436c9483b821149f72b582da3733cc7..31ce347ea8fda1aec0c350c5d92341968ccfcb85 100644 +index 10ea60e7c..31ce347ea 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -101,6 +101,16 @@ struct skippy_runtime_config { @@ -90,7 +90,7 @@ index 10ea60e7c436c9483b821149f72b582da3733cc7..31ce347ea8fda1aec0c350c5d9234196 // 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 6d9028a18e72dc4c6b0ee19f5110e91afe837afb..fc5dcd3894938bfe35a9957d8295b95ba93a4910 100644 +index 6d9028a18..fc5dcd389 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h @@ -30,6 +30,9 @@ enum skippy_memory_cache_capability { @@ -104,7 +104,7 @@ index 6d9028a18e72dc4c6b0ee19f5110e91afe837afb..fc5dcd3894938bfe35a9957d8295b95b 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 8e53a0d5f3e8b6fe91ee2d105954316df0c4ed07..87cf979cf606f6e0fe2eb85efa7bdf52ddf41c14 100644 +index f3400263e..d3394ba9d 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -426,9 +426,11 @@ llama_context::llama_context( @@ -121,7 +121,7 @@ index 8e53a0d5f3e8b6fe91ee2d105954316df0c4ed07..87cf979cf606f6e0fe2eb85efa7bdf52 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 60ae9769df9cedf980d5f759045e631ac08d522f..7422c0e5bf3461c83cb96e7a0e68ef9010be5368 100644 +index 60ae9769d..7422c0e5b 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -102,6 +102,9 @@ struct skippy_graph_build_inputs { @@ -135,7 +135,7 @@ index 60ae9769df9cedf980d5f759045e631ac08d522f..7422c0e5bf3461c83cb96e7a0e68ef90 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 c08f2d510d27cd1ee0ec0bc022c1a34df305692c..d5f13eaf2373b9c85e03770c21fe530c4db227f1 100644 +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( @@ -147,7 +147,7 @@ index c08f2d510d27cd1ee0ec0bc022c1a34df305692c..d5f13eaf2373b9c85e03770c21fe530c 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 a4bf2a4756970f79ae7ea59680de0f49da59dd17..5f100aa461bc9b0f2dfd47e84d681b016c052551 100644 +index a4bf2a475..5f100aa46 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -22,6 +22,7 @@ @@ -238,7 +238,7 @@ index a4bf2a4756970f79ae7ea59680de0f49da59dd17..5f100aa461bc9b0f2dfd47e84d681b01 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 806e79d72ec960d12571d2acd2c5ecb22229c49b..c62b1e62991bbaf60386786c4538a49e8b1e28e6 100644 +index 806e79d72..c62b1e629 100644 --- a/src/skippy/state_memory.cpp +++ b/src/skippy/state_memory.cpp @@ -1,5 +1,6 @@ @@ -310,7 +310,7 @@ index 806e79d72ec960d12571d2acd2c5ecb22229c49b..c62b1e62991bbaf60386786c4538a49e 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 4875cf39855d72989869e0f492de01cdf5a320d3..84e5d9c61654dd2bc27d2606ef39a485e7709fb9 100644 +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); @@ -324,3 +324,6 @@ index 4875cf39855d72989869e0f492de01cdf5a320d3..84e5d9c61654dd2bc27d2606ef39a485 +// 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.56.0 + diff --git a/llama_cpp/patches/0036-llama-place-each-request-s-share-of-a-batch-together.patch b/llama_cpp/patches/0036-llama-place-each-request-s-share-of-a-batch-together.patch index 45d81a36..7fd103a3 100644 --- a/llama_cpp/patches/0036-llama-place-each-request-s-share-of-a-batch-together.patch +++ b/llama_cpp/patches/0036-llama-place-each-request-s-share-of-a-batch-together.patch @@ -1,4 +1,4 @@ -From 30dd8fb5e2529173c8c878fe58c05844e6eec51e Mon Sep 17 00:00:00 2001 +From 12f983a1e42cedfa40af0c436d46aee56f4b32b4 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 08:42:32 +1100 Subject: [PATCH] llama: place each request's share of a batch together in the @@ -31,7 +31,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y 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 1053cebfe58bf82c484e90ca9518d6bfecf28bec..cb016ab007eba72cf073c43a1ed5ce59d0b7a692 100644 +index 1053cebfe..cb016ab00 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1251,79 +1251,18 @@ bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_co @@ -125,7 +125,7 @@ index 1053cebfe58bf82c484e90ca9518d6bfecf28bec..cb016ab007eba72cf073c43a1ed5ce59 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 94caf7c83d2f13b6e879905d3f0de2658a027362..d30090efd63eb042f97f5dafd00d4870fd586b27 100644 +index 94caf7c83..d30090efd 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -4,12 +4,14 @@ @@ -266,7 +266,7 @@ index 94caf7c83d2f13b6e879905d3f0de2658a027362..d30090efd63eb042f97f5dafd00d4870 // note: call only if the cell is not empty diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 26fe9aa16111bcb8d91f7bf0428fbd8a19650a24..4189d102dead13cc2a14bf48e8d76d67ae1dc9ba 100644 +index 26fe9aa16..4189d102d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -194,6 +194,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) @@ -279,7 +279,7 @@ index 26fe9aa16111bcb8d91f7bf0428fbd8a19650a24..4189d102dead13cc2a14bf48e8d76d67 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 0000000000000000000000000000000000000000..b7c50f142b4007e2a5fe88373876c1952da40677 +index 000000000..b7c50f142 --- /dev/null +++ b/tests/test-skippy-kv-place-together.cpp @@ -0,0 +1,200 @@ @@ -483,3 +483,6 @@ index 0000000000000000000000000000000000000000..b7c50f142b4007e2a5fe88373876c195 + } + return failures == 0 ? 0 : 1; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0037-skippy-sample-a-wave-through-a-configurable-executor.patch b/llama_cpp/patches/0037-skippy-sample-a-wave-through-a-configurable-executor.patch index e6072f63..be071bb2 100644 --- a/llama_cpp/patches/0037-skippy-sample-a-wave-through-a-configurable-executor.patch +++ b/llama_cpp/patches/0037-skippy-sample-a-wave-through-a-configurable-executor.patch @@ -1,4 +1,4 @@ -From 9506f72ca424c0a5896d6791a824dfb38a07f0b8 Mon Sep 17 00:00:00 2001 +From 1c2baf00202d7a2414e5a96b8ec0a66292efa512 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 12:25:11 +1100 Subject: [PATCH] skippy: sample a wave through a configurable executor @@ -44,7 +44,7 @@ Claude-Session: https://claude.ai/code/session_01QA3dWey3RBtBgDz1Tery9Y create mode 100644 tests/test-skippy-task-pool.cpp diff --git a/include/skippy/common.h b/include/skippy/common.h -index b16229b1b78c2df981ca9870f6e4c7357b885af9..557ba51694839de1611ef2b33a7cce90437e8b84 100644 +index b16229b1b..557ba5169 100644 --- a/include/skippy/common.h +++ b/include/skippy/common.h @@ -46,7 +46,7 @@ extern "C" { @@ -57,7 +57,7 @@ index b16229b1b78c2df981ca9870f6e4c7357b885af9..557ba51694839de1611ef2b33a7cce90 #if defined(_MSC_VER) #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/include/skippy/runtime.h b/include/skippy/runtime.h -index 31ce347ea8fda1aec0c350c5d92341968ccfcb85..58b157319bd5fba131d5212bde7cc5810e4213ac 100644 +index 31ce347ea..58b157319 100644 --- a/include/skippy/runtime.h +++ b/include/skippy/runtime.h @@ -111,6 +111,9 @@ struct skippy_runtime_config { @@ -71,7 +71,7 @@ index 31ce347ea8fda1aec0c350c5d92341968ccfcb85..58b157319bd5fba131d5212bde7cc581 // 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 c6675d944001872c468294ca87bddb4f3b1d7a5b..cd6340976c2ef21c2972b2e0c77b4756f480c028 100644 +index ef3526dee..c89e0f21c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -84,6 +84,8 @@ add_library(llama @@ -84,7 +84,7 @@ index c6675d944001872c468294ca87bddb4f3b1d7a5b..cd6340976c2ef21c2972b2e0c77b4756 skippy/chat_sampling.cpp skippy/sampling_vocab.cpp diff --git a/src/skippy/batch_sampling.cpp b/src/skippy/batch_sampling.cpp -index e59c898575ea262476bad7c3719119d3f45d9440..0b01db542d9f6485db56ca4bfbe50951c15da7b2 100644 +index e59c89857..0b01db542 100644 --- a/src/skippy/batch_sampling.cpp +++ b/src/skippy/batch_sampling.cpp @@ -3,13 +3,12 @@ @@ -151,7 +151,7 @@ index e59c898575ea262476bad7c3719119d3f45d9440..0b01db542d9f6485db56ca4bfbe50951 bool share_context( diff --git a/src/skippy/sample_executor.cpp b/src/skippy/sample_executor.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..614074d522f3b55a8dd79138d63aad2cb6b5d484 +index 000000000..614074d52 --- /dev/null +++ b/src/skippy/sample_executor.cpp @@ -0,0 +1,17 @@ @@ -174,7 +174,7 @@ index 0000000000000000000000000000000000000000..614074d522f3b55a8dd79138d63aad2c +} diff --git a/src/skippy/sample_executor.h b/src/skippy/sample_executor.h new file mode 100644 -index 0000000000000000000000000000000000000000..7eeb5937c9453482a41009a70a39e396336e0726 +index 000000000..7eeb5937c --- /dev/null +++ b/src/skippy/sample_executor.h @@ -0,0 +1,50 @@ @@ -230,7 +230,7 @@ index 0000000000000000000000000000000000000000..7eeb5937c9453482a41009a70a39e396 +} diff --git a/src/skippy/task_pool.cpp b/src/skippy/task_pool.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..88f8d3b5990bd0410e92acd9b6f53e3b35e69894 +index 000000000..88f8d3b59 --- /dev/null +++ b/src/skippy/task_pool.cpp @@ -0,0 +1,97 @@ @@ -333,7 +333,7 @@ index 0000000000000000000000000000000000000000..88f8d3b5990bd0410e92acd9b6f53e3b +} diff --git a/src/skippy/task_pool.h b/src/skippy/task_pool.h new file mode 100644 -index 0000000000000000000000000000000000000000..e33523ea799a63f4278b88af650d5c9b2fe72cb1 +index 000000000..e33523ea7 --- /dev/null +++ b/src/skippy/task_pool.h @@ -0,0 +1,59 @@ @@ -397,7 +397,7 @@ index 0000000000000000000000000000000000000000..e33523ea799a63f4278b88af650d5c9b + std::vector threads; // grown by run() under `turn` +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index 4189d102dead13cc2a14bf48e8d76d67ae1dc9ba..18134816d471fad63570f3140ebeeb952065a0b3 100644 +index 4189d102d..18134816d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -195,6 +195,8 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) @@ -411,7 +411,7 @@ index 4189d102dead13cc2a14bf48e8d76d67ae1dc9ba..18134816d471fad63570f3140ebeeb95 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 0000000000000000000000000000000000000000..e9b9284e0ab5b403f5dee0e2fb19920b8aa75b53 +index 000000000..e9b9284e0 --- /dev/null +++ b/tests/test-skippy-task-pool.cpp @@ -0,0 +1,171 @@ @@ -586,3 +586,6 @@ index 0000000000000000000000000000000000000000..e9b9284e0ab5b403f5dee0e2fb19920b + } + return failures == 0 ? 0 : 1; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0038-tests-check-row-list-attention-over-the-lists-a-unif.patch b/llama_cpp/patches/0038-tests-check-row-list-attention-over-the-lists-a-unif.patch index 50bd5f51..1115b440 100644 --- a/llama_cpp/patches/0038-tests-check-row-list-attention-over-the-lists-a-unif.patch +++ b/llama_cpp/patches/0038-tests-check-row-list-attention-over-the-lists-a-unif.patch @@ -1,4 +1,4 @@ -From fc9cea0f543b86882868b3c4b5df7d3f8d63e38a Mon Sep 17 00:00:00 2001 +From 221ef138881d1d1b463d08ddd7c5131235a0d4d9 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Thu, 12 Nov 2026 15:55:33 +1100 Subject: [PATCH] tests: check row-list attention over the lists a unified KV @@ -31,7 +31,7 @@ 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 18134816d471fad63570f3140ebeeb952065a0b3..b3f0cce27e22cf9cf3db64db19f2fb69c3f36499 100644 +index 18134816d..b3f0cce27 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -416,6 +416,11 @@ if (GGML_METAL AND NOT GGML_BACKEND_DL) @@ -47,7 +47,7 @@ index 18134816d471fad63570f3140ebeeb952065a0b3..b3f0cce27e22cf9cf3db64db19f2fb69 llama_build_and_test(test-backend-tensor.cpp LINK ggml) llama_build_and_test(test-sleep.cpp LINK ggml) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp -index 0d0d020feec0c62c08016e3cec59ffb44fc6cf9b..4830797213db7a017712d882ab9cf5487250c90f 100644 +index 0d0d020fe..483079721 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10485,11 +10485,8 @@ struct test_flash_attn_ext_kv_rows : public test_case { @@ -191,3 +191,6 @@ index 0d0d020feec0c62c08016e3cec59ffb44fc6cf9b..4830797213db7a017712d882ab9cf548 // 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.56.0 + diff --git a/llama_cpp/patches/0039-llama-reclaim-released-chunks-before-compaction-copi.patch b/llama_cpp/patches/0039-llama-reclaim-released-chunks-before-compaction-copi.patch index 81fb53c3..3dc2b480 100644 --- a/llama_cpp/patches/0039-llama-reclaim-released-chunks-before-compaction-copi.patch +++ b/llama_cpp/patches/0039-llama-reclaim-released-chunks-before-compaction-copi.patch @@ -1,4 +1,4 @@ -From 7f43bd2ba1539a76c30d790f410aea336a11707c Mon Sep 17 00:00:00 2001 +From ba740bc1a824440bf26b992359537427bdece529 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:03:10 +1100 Subject: [PATCH] llama: reclaim released chunks before compaction copies rows @@ -26,7 +26,7 @@ moved rows. 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 cb016ab007eba72cf073c43a1ed5ce59d0b7a692..1962d3a7ab74342658ea406fd901189e03c6853e 100644 +index cb016ab00..1962d3a7a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -675,6 +675,20 @@ void llama_kv_cache::reclaim_chunks(uint32_t stream, const std::vector @@ -60,7 +60,7 @@ index cb016ab007eba72cf073c43a1ed5ce59d0b7a692..1962d3a7ab74342658ea406fd901189e 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 21c2e18e5b84fa62bd271135567ce9a84a7d5f79..6d5eccaf72a510e8b42f67bc7f20f646b2b8c8b3 100644 +index 21c2e18e5..6d5eccaf7 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -313,6 +313,7 @@ public: @@ -72,7 +72,7 @@ index 21c2e18e5b84fa62bd271135567ce9a84a7d5f79..6d5eccaf72a510e8b42f67bc7f20f646 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 b3f0cce27e22cf9cf3db64db19f2fb69c3f36499..d79157d7f77ff6a82835efa8ad9627c0762ee343 100644 +index b3f0cce27..d79157d7f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -195,6 +195,7 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) @@ -85,7 +85,7 @@ index b3f0cce27e22cf9cf3db64db19f2fb69c3f36499..d79157d7f77ff6a82835efa8ad9627c0 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 0000000000000000000000000000000000000000..9ea25b89fc5a28c566969bd33bdecb08c67bc67e +index 000000000..9ea25b89f --- /dev/null +++ b/tests/test-skippy-kv-release-compact.cpp @@ -0,0 +1,120 @@ @@ -209,3 +209,6 @@ index 0000000000000000000000000000000000000000..9ea25b89fc5a28c566969bd33bdecb08 + std::printf("OK\n"); + return 0; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0040-ggml-metal-check-every-row-list-entry-before-reading.patch b/llama_cpp/patches/0040-ggml-metal-check-every-row-list-entry-before-reading.patch index a6f9d710..6a5e9852 100644 --- a/llama_cpp/patches/0040-ggml-metal-check-every-row-list-entry-before-reading.patch +++ b/llama_cpp/patches/0040-ggml-metal-check-every-row-list-entry-before-reading.patch @@ -1,4 +1,4 @@ -From 57b4757ec79dd1abe6baf8b1a838388df4701dd6 Mon Sep 17 00:00:00 2001 +From 229e9387a6f1e0a7c4c04fb1838fc95850ce8384 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:04:35 +1100 Subject: [PATCH] ggml-metal: check every row-list entry before reading a block @@ -29,7 +29,7 @@ well as on the gather-free variant. 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 1ddc52ed6303a7c9ac46b9ced8d38762f1f7a704..e853e57d65fe396c155b3f8089521e223e59334c 100644 +index 1ddc52ed6..e853e57d6 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -16,6 +16,7 @@ @@ -151,7 +151,7 @@ index 1ddc52ed6303a7c9ac46b9ced8d38762f1f7a704..e853e57d65fe396c155b3f8089521e22 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 f61b0b919a879b5f1a49d6e77fef3e742e65f131..4535bc4d6731ffaeb0cf233e0050c3e413c8b20c 100644 +index f61b0b919..4535bc4d6 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -240,9 +240,9 @@ kernel void kernel_flash_attn_ext_vec( @@ -186,7 +186,7 @@ index f61b0b919a879b5f1a49d6e77fef3e742e65f131..4535bc4d6731ffaeb0cf233e0050c3e4 } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp -index 4830797213db7a017712d882ab9cf5487250c90f..3b73bb057d2914439459bc034f1b4ac2e29dcea5 100644 +index 483079721..3b73bb057 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10699,6 +10699,10 @@ struct test_flash_attn_ext_kv_rows_runs : public test_flash_attn_ext_kv_rows { @@ -234,3 +234,6 @@ index 4830797213db7a017712d882ab9cf5487250c90f..3b73bb057d2914439459bc034f1b4ac2 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.56.0 + diff --git a/llama_cpp/patches/0041-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch b/llama_cpp/patches/0041-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch index f68cdaeb..7ddd9e49 100644 --- a/llama_cpp/patches/0041-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch +++ b/llama_cpp/patches/0041-skippy-a-helper-takes-a-run-s-tasks-only-while-that-.patch @@ -1,4 +1,4 @@ -From 8d4d3df2392f37c7edaf5afee206ed824022bfbd Mon Sep 17 00:00:00 2001 +From fe6671fdbfea003eaf79dc00e5c8828d717ea3b1 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:05:26 +1100 Subject: [PATCH] skippy: a helper takes a run's tasks only while that run @@ -24,7 +24,7 @@ likely, not certain, to occur in one pass. 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/skippy/task_pool.cpp b/src/skippy/task_pool.cpp -index 88f8d3b5990bd0410e92acd9b6f53e3b35e69894..c1e1bf5174acd91dc88678ccc32753b6e974cf36 100644 +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) { @@ -68,7 +68,7 @@ index 88f8d3b5990bd0410e92acd9b6f53e3b35e69894..c1e1bf5174acd91dc88678ccc32753b6 } } diff --git a/src/skippy/task_pool.h b/src/skippy/task_pool.h -index e33523ea799a63f4278b88af650d5c9b2fe72cb1..efc147f01792e4a1cee67013a53358a3ea6dac2b 100644 +index e33523ea7..efc147f01 100644 --- a/src/skippy/task_pool.h +++ b/src/skippy/task_pool.h @@ -9,6 +9,7 @@ @@ -90,7 +90,7 @@ index e33523ea799a63f4278b88af650d5c9b2fe72cb1..efc147f01792e4a1cee67013a53358a3 const size_t limit; diff --git a/tests/test-skippy-task-pool.cpp b/tests/test-skippy-task-pool.cpp -index e9b9284e0ab5b403f5dee0e2fb19920b8aa75b53..677658b967b99082ebde44b35ca14345cf5272cb 100644 +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() { @@ -132,3 +132,6 @@ index e9b9284e0ab5b403f5dee0e2fb19920b8aa75b53..677658b967b99082ebde44b35ca14345 sample_threads_select_the_executor(); CHECK(skippy_task_pool::shared().helpers() <= skippy_task_pool::shared().ceiling()); if (failures == 0) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0042-skippy-apply-the-KV-memory-options-to-every-attentio.patch b/llama_cpp/patches/0042-skippy-apply-the-KV-memory-options-to-every-attentio.patch index 8a9a84f1..e91368aa 100644 --- a/llama_cpp/patches/0042-skippy-apply-the-KV-memory-options-to-every-attentio.patch +++ b/llama_cpp/patches/0042-skippy-apply-the-KV-memory-options-to-every-attentio.patch @@ -1,4 +1,4 @@ -From 1cdcf1d2baeac5bc0f90ecc96663ed5ee655beb7 Mon Sep 17 00:00:00 2001 +From 627ec71a6052ebec7dac6f5ac51d9f8f3fe472a8 Mon Sep 17 00:00:00 2001 From: Jared Wyles Date: Wed, 18 Nov 2026 20:05:54 +1100 Subject: [PATCH] skippy: apply the KV memory options to every attention cache @@ -17,7 +17,7 @@ CSA, HCA and indexer caches. 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp -index c62b1e62991bbaf60386786c4538a49e8b1e28e6..a8a3757cadb42e1afdca0e996961b15b00dbec71 100644 +index c62b1e629..a8a3757ca 100644 --- a/src/skippy/state_memory.cpp +++ b/src/skippy/state_memory.cpp @@ -5,6 +5,9 @@ @@ -55,3 +55,6 @@ index c62b1e62991bbaf60386786c4538a49e8b1e28e6..a8a3757cadb42e1afdca0e996961b15b if (auto * iswa = skippy_memory_iswa_adapter(memory)) { return { iswa->get_base(), iswa->get_swa() }; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0043-test-skippy-restore-hybrid-checkpoint-components.patch b/llama_cpp/patches/0043-test-skippy-restore-hybrid-checkpoint-components.patch index 514f1742..a516d5a6 100644 --- a/llama_cpp/patches/0043-test-skippy-restore-hybrid-checkpoint-components.patch +++ b/llama_cpp/patches/0043-test-skippy-restore-hybrid-checkpoint-components.patch @@ -1,4 +1,4 @@ -From ea652a16b320fdf5f2f562986b2d1876ad9c30b6 Mon Sep 17 00:00:00 2001 +From e83d9b99c3c008da0d70edff254623b09694cc4c Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Fri, 20 Nov 2026 07:55:59 +1100 Subject: [PATCH] test-skippy: restore both hybrid checkpoint components @@ -8,7 +8,7 @@ Subject: [PATCH] test-skippy: restore both hybrid checkpoint components 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 4c7c891e168e59765050bdb322b0bd425b30767f..1e636d0f3d17323962140fec935f3bfa6841d88d 100644 +index 4c7c891e1..1e636d0f3 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -568,6 +568,10 @@ std::vector export_page(skippy_session * session, size_t token_count) { @@ -88,3 +88,6 @@ index 4c7c891e168e59765050bdb322b0bd425b30767f..1e636d0f3d17323962140fec935f3bfa prefill(warm, suffix); const auto warm_logits = decode_logits(warm, suffix.back()); release(warm); +-- +2.56.0 + diff --git a/llama_cpp/patches/0044-test-skippy-admit-separate-resident-capability-components.patch b/llama_cpp/patches/0044-test-skippy-admit-separate-resident-capability-components.patch index b99d02cf..af0a20bb 100644 --- a/llama_cpp/patches/0044-test-skippy-admit-separate-resident-capability-components.patch +++ b/llama_cpp/patches/0044-test-skippy-admit-separate-resident-capability-components.patch @@ -1,4 +1,4 @@ -From f762cb766cba9251128094e26767c9ef75d18318 Mon Sep 17 00:00:00 2001 +From 97d10a69255624f9f65e58fbb2e57f3a3df72f4d Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Fri, 20 Nov 2026 08:08:55 +1100 Subject: [PATCH] test-skippy: admit separate resident capability components @@ -8,7 +8,7 @@ Subject: [PATCH] test-skippy: admit separate resident capability components 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/test-skippy-kv-page-export.cpp b/tests/test-skippy-kv-page-export.cpp -index 30c88b49028395dea438ab6697a578463457d1b8..d5e26d9849a985ae6ae29a1c7011bf7ab61ec0a2 100644 +index 30c88b490..d5e26d984 100644 --- a/tests/test-skippy-kv-page-export.cpp +++ b/tests/test-skippy-kv-page-export.cpp @@ -38,12 +38,15 @@ static bool graph_cache_capabilities_cover_complete_state() { @@ -51,3 +51,6 @@ index 30c88b49028395dea438ab6697a578463457d1b8..d5e26d9849a985ae6ae29a1c7011bf7a skippy_model_memory_cache_capabilities(nullptr) != 0) { return 1; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0045-ggml-metal-classify-empty-command-buffers-as-other-work.patch b/llama_cpp/patches/0045-ggml-metal-classify-empty-command-buffers-as-other-work.patch index 150ee435..aabe0eda 100644 --- a/llama_cpp/patches/0045-ggml-metal-classify-empty-command-buffers-as-other-work.patch +++ b/llama_cpp/patches/0045-ggml-metal-classify-empty-command-buffers-as-other-work.patch @@ -1,4 +1,4 @@ -From 77a959357abc2486fac607529ba8a1ca115c075e Mon Sep 17 00:00:00 2001 +From fb52b9b81c5fefdc6d587d084ac1c37a5cdb29a5 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Fri, 20 Nov 2026 08:08:56 +1100 Subject: [PATCH] ggml-metal: classify empty command buffers as other work @@ -9,7 +9,7 @@ Subject: [PATCH] ggml-metal: classify empty command buffers as other work 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-timing.cpp b/ggml/src/ggml-metal/ggml-metal-timing.cpp -index 8bf274932ded2425d57ff2ffc503a52f11d50d1f..477058b20450bb922f72d502181a5bfecfd2d373 100644 +index 8bf274932..477058b20 100644 --- a/ggml/src/ggml-metal/ggml-metal-timing.cpp +++ b/ggml/src/ggml-metal/ggml-metal-timing.cpp @@ -314,11 +314,17 @@ void ggml_metal_timing_account( @@ -32,7 +32,7 @@ index 8bf274932ded2425d57ff2ffc503a52f11d50d1f..477058b20450bb922f72d502181a5bfe ggml_tensor ** first = gf->nodes + start; ggml_tensor ** last = gf->nodes + std::min(end, gf->n_nodes); diff --git a/tests/test-skippy-tracing-metal.cpp b/tests/test-skippy-tracing-metal.cpp -index 365052e0ed4accc3789f38664163f2c90798d943..dc9cacbcc2a022c6005a6cb1dbb15c207da96d9c 100644 +index 365052e0e..dc9cacbcc 100644 --- a/tests/test-skippy-tracing-metal.cpp +++ b/tests/test-skippy-tracing-metal.cpp @@ -122,9 +122,12 @@ int main() { @@ -49,3 +49,6 @@ index 365052e0ed4accc3789f38664163f2c90798d943..dc9cacbcc2a022c6005a6cb1dbb15c20 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); +-- +2.56.0 + diff --git a/llama_cpp/patches/0046-skip-clearing-fully-overwritten-kv-import-chunks.patch b/llama_cpp/patches/0046-skip-clearing-fully-overwritten-kv-import-chunks.patch index 9aaece1e..bd507798 100644 --- a/llama_cpp/patches/0046-skip-clearing-fully-overwritten-kv-import-chunks.patch +++ b/llama_cpp/patches/0046-skip-clearing-fully-overwritten-kv-import-chunks.patch @@ -1,4 +1,4 @@ -From 0bd715e4b351b6a11c4e156281714f490323be3c Mon Sep 17 00:00:00 2001 +From c67f3e8c0601ba6a9029628889e8ed4552cd00eb Mon Sep 17 00:00:00 2001 From: Skippy contributors Date: Mon, 23 Nov 2026 13:51:35 +1100 Subject: [PATCH] Skip clearing reclaimed KV chunks fully overwritten by raw @@ -12,10 +12,10 @@ Subject: [PATCH] Skip clearing reclaimed KV chunks fully overwritten by raw 4 files changed, 88 insertions(+), 14 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index cd6340976c2ef21c2972b2e0c77b4756f480c028..86e25d60fa8197e71399745e012a6b13b61ab38d 100644 +index c89e0f21c..b452ec36e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -486,6 +486,12 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -495,6 +495,12 @@ if (LLAMA_STAGE_BUILD_TESTS) endforeach() endfunction() add_skippy_sampling_history_tests(gemma skippy-model-loader-fixtures dense) @@ -29,7 +29,7 @@ index cd6340976c2ef21c2972b2e0c77b4756f480c028..86e25d60fa8197e71399745e012a6b13 add_skippy_sampling_history_tests(granitehybrid skippy-noalloc-granite-hybrid-fixture recurrent) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index 1962d3a7ab74342658ea406fd901189e03c6853e..e4ea262935b2f644aea7c79afd1646f205cb31d6 100644 +index 1962d3a7a..e4ea26293 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -645,7 +645,7 @@ void llama_kv_cache::release_free_chunks(uint32_t stream) { @@ -123,7 +123,7 @@ index 1962d3a7ab74342658ea406fd901189e03c6853e..e4ea262935b2f644aea7c79afd1646f2 const auto cell_runs = llama_kv_cache_cell_runs(sinfo.idxs[0]); const char * src = static_cast(input); diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index 6d5eccaf72a510e8b42f67bc7f20f646b2b8c8b3..1343a605fd045875eafcba8e032ecc06836252ed 100644 +index 6d5eccaf7..1343a605f 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -304,7 +304,7 @@ public: @@ -153,7 +153,7 @@ index 6d5eccaf72a510e8b42f67bc7f20f646b2b8c8b3..1343a605fd045875eafcba8e032ecc06 // move used cells toward the beginning of each stream and copy the backing KV rows std::vector compact_cells(); diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index 1e636d0f3d17323962140fec935f3bfa6841d88d..db4a27bd227e6b84c29ae9b5628ab3dcc356f391 100644 +index 1e636d0f3..db4a27bd2 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -623,6 +623,37 @@ std::vector decode_logits(skippy_session * session, llama_token token) { @@ -226,3 +226,6 @@ index 1e636d0f3d17323962140fec935f3bfa6841d88d..db4a27bd227e6b84c29ae9b5628ab3dc } else { for (const bool full : {false, true}) { if (grammar) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0047-test-align-fused-operation-diagnostics-with-upstream.patch b/llama_cpp/patches/0047-test-align-fused-operation-diagnostics-with-upstream.patch index 85bcc794..fef3d1e1 100644 --- a/llama_cpp/patches/0047-test-align-fused-operation-diagnostics-with-upstream.patch +++ b/llama_cpp/patches/0047-test-align-fused-operation-diagnostics-with-upstream.patch @@ -1,4 +1,4 @@ -From 993302ec6d0676abe353bf51835e13f1395b192b Mon Sep 17 00:00:00 2001 +From a54afa75ddde8773b6e586ee8ab52fac05dbd606 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:18:03 +1100 Subject: [PATCH] test: align fused operation diagnostics with upstream @@ -8,7 +8,7 @@ Subject: [PATCH] test: align fused operation diagnostics with upstream 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/skippy/tests/graph_build_inputs.cpp b/src/skippy/tests/graph_build_inputs.cpp -index f1a028195e12723dc09efd6b2dcdddaebd4251a4..5aab920cd04436d65dbfa384c325f04ed8ea0806 100644 +index f1a028195..5aab920cd 100644 --- a/src/skippy/tests/graph_build_inputs.cpp +++ b/src/skippy/tests/graph_build_inputs.cpp @@ -569,7 +569,8 @@ static int check_sched_reserve_and_memory_update(const char * model_path) { @@ -21,3 +21,6 @@ index f1a028195e12723dc09efd6b2dcdddaebd4251a4..5aab920cd04436d65dbfa384c325f04e case LLM_FUSED_OP_DSV4_HC_PRE: return "DeepSeek V4 HC pre"; case LLM_FUSED_OP_DSV4_HC_COMB: return "DeepSeek V4 HC comb"; case LLM_FUSED_OP_DSV4_HC_POST: return "DeepSeek V4 HC post"; +-- +2.56.0 + diff --git a/llama_cpp/patches/0048-cuda-initialize-devices-without-optional-nvml-headers.patch b/llama_cpp/patches/0048-cuda-initialize-devices-without-optional-nvml-headers.patch index da3d8f73..ea28aef4 100644 --- a/llama_cpp/patches/0048-cuda-initialize-devices-without-optional-nvml-headers.patch +++ b/llama_cpp/patches/0048-cuda-initialize-devices-without-optional-nvml-headers.patch @@ -1,4 +1,4 @@ -From 082c5d62dad41bfe4baf7e9788ec91fc9c3c79c4 Mon Sep 17 00:00:00 2001 +From 2170ee054c3f63688f782dfe2ccbbc36b2938cce Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:18:03 +1100 Subject: [PATCH] cuda: retain device initialization without optional NVML @@ -9,7 +9,7 @@ Subject: [PATCH] cuda: retain device initialization without optional NVML 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu -index c35b4a1db70556643cdc607d049ac6be78ecc5fc..c7f2e5dd79037ff9b809ed6e868ae20c839b619f 100644 +index c35b4a1db..c7f2e5dd7 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -97,8 +97,11 @@ @@ -69,3 +69,6 @@ index c35b4a1db70556643cdc607d049ac6be78ecc5fc..c7f2e5dd79037ff9b809ed6e868ae20c if (nvml_initialized) { (void) shutdown(); } +-- +2.56.0 + diff --git a/llama_cpp/patches/0049-skippy-track-upstream-in-place-state-fill-effects.patch b/llama_cpp/patches/0049-skippy-track-upstream-in-place-state-fill-effects.patch index 84f9c00a..4a40a5a9 100644 --- a/llama_cpp/patches/0049-skippy-track-upstream-in-place-state-fill-effects.patch +++ b/llama_cpp/patches/0049-skippy-track-upstream-in-place-state-fill-effects.patch @@ -1,4 +1,4 @@ -From fc16088634df1efe3f781968167faa462e657521 Mon Sep 17 00:00:00 2001 +From 9dd75f585589191071cf38c7cfbbf445505f6c0c Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:22:58 +1100 Subject: [PATCH] skippy: track upstream in-place state fill effects @@ -11,7 +11,7 @@ Subject: [PATCH] skippy: track upstream in-place state fill effects create mode 100644 src/skippy/tests/fill_state_regression.h diff --git a/src/skippy/state_effects.cpp b/src/skippy/state_effects.cpp -index b33ed2d5d881faa7aaff49767c907944c83069c8..3b5690fc348052f6282c5c90082bf04978a67180 100644 +index b33ed2d5d..3b5690fc3 100644 --- a/src/skippy/state_effects.cpp +++ b/src/skippy/state_effects.cpp @@ -150,6 +150,7 @@ static const ggml_tensor * write_destination(const ggml_tensor * node) { @@ -44,7 +44,7 @@ index b33ed2d5d881faa7aaff49767c907944c83069c8..3b5690fc348052f6282c5c90082bf049 const ggml_tensor * storage = skippy_state_canonical_storage(write_destination(node)); diff --git a/src/skippy/tests/fill_state_regression.h b/src/skippy/tests/fill_state_regression.h new file mode 100644 -index 0000000000000000000000000000000000000000..460e175a5a3c7f4b87b72983b48fe8a9cf961c26 +index 000000000..460e175a5 --- /dev/null +++ b/src/skippy/tests/fill_state_regression.h @@ -0,0 +1,56 @@ @@ -105,7 +105,7 @@ index 0000000000000000000000000000000000000000..460e175a5a3c7f4b87b72983b48fe8a9 + return 0; +} diff --git a/src/skippy/tests/stage_slice_plan.cpp b/src/skippy/tests/stage_slice_plan.cpp -index 21f659cbd3ba2c14ae0cbf24417334da3d32a791..ec3878c1a18ba3978656eda3b0a5da489c032412 100644 +index 21f659cbd..ec3878c1a 100644 --- a/src/skippy/tests/stage_slice_plan.cpp +++ b/src/skippy/tests/stage_slice_plan.cpp @@ -1177,9 +1177,11 @@ static int check_auxiliary_graph_parameter_closure() { @@ -120,3 +120,6 @@ index 21f659cbd3ba2c14ae0cbf24417334da3d32a791..ec3878c1a18ba3978656eda3b0a5da48 if (!result) { result = check_input_leaf_state_inference(); } if (!result) { result = check_raw_embedding_checkpoint(); } if (!result) { result = check_semantic_identities(); } +-- +2.56.0 + diff --git a/llama_cpp/patches/0050-sampling-begin-each-logical-batch-transaction.patch b/llama_cpp/patches/0050-sampling-begin-each-logical-batch-transaction.patch index 33c6339a..634dc1ca 100644 --- a/llama_cpp/patches/0050-sampling-begin-each-logical-batch-transaction.patch +++ b/llama_cpp/patches/0050-sampling-begin-each-logical-batch-transaction.patch @@ -1,4 +1,4 @@ -From d1d1be7b94cf8d62c7b73bb79f6c1badc36212a2 Mon Sep 17 00:00:00 2001 +From 47cf2fe86c4fa6cf00b3f87cf58b60a07e526ac6 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:49:52 +1100 Subject: [PATCH] sampling: begin each logical batch transaction @@ -11,10 +11,10 @@ Subject: [PATCH] sampling: begin each logical batch transaction create mode 100644 src/skippy/tests/backend_transaction_regression.h diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 87cf979cf606f6e0fe2eb85efa7bdf52ddf41c14..706b35ce07d944745076181e4ceee66ddb186b63 100644 +index d3394ba9d..ca18b3090 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -2505,6 +2505,12 @@ int llama_context::decode( +@@ -2513,6 +2513,12 @@ int llama_context::decode( }; output_trace.end(); @@ -28,7 +28,7 @@ index 87cf979cf606f6e0fe2eb85efa7bdf52ddf41c14..706b35ce07d944745076181e4ceee66d int64_t n_tokens_prev = 0; diff --git a/src/skippy/tests/backend_sample_capacity.cpp b/src/skippy/tests/backend_sample_capacity.cpp -index b234872a70e8e97d211ecd317fbb3c317d77a1f9..f0341b7b02fd8db2ed61102dbb66f67b89002bc5 100644 +index b234872a7..f0341b7b0 100644 --- a/src/skippy/tests/backend_sample_capacity.cpp +++ b/src/skippy/tests/backend_sample_capacity.cpp @@ -211,6 +211,8 @@ void readout_detaches_only_its_lane(skippy_session * a, skippy_session * b) { @@ -50,7 +50,7 @@ index b234872a70e8e97d211ecd317fbb3c317d77a1f9..f0341b7b02fd8db2ed61102dbb66f67b auto * a = create(model); diff --git a/src/skippy/tests/backend_transaction_regression.h b/src/skippy/tests/backend_transaction_regression.h new file mode 100644 -index 0000000000000000000000000000000000000000..7f4e8fce706e026d78d8965726a487055c7d8180 +index 000000000..7f4e8fce7 --- /dev/null +++ b/src/skippy/tests/backend_transaction_regression.h @@ -0,0 +1,61 @@ @@ -115,3 +115,6 @@ index 0000000000000000000000000000000000000000..7f4e8fce706e026d78d8965726a48705 + llama_sampler_sample(b_sampler.get(), b.get(), 0)); + } +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0051-lora-retain-the-primal-activation-for-adapter-deltas.patch b/llama_cpp/patches/0051-lora-retain-the-primal-activation-for-adapter-deltas.patch index c1bd0111..92199560 100644 --- a/llama_cpp/patches/0051-lora-retain-the-primal-activation-for-adapter-deltas.patch +++ b/llama_cpp/patches/0051-lora-retain-the-primal-activation-for-adapter-deltas.patch @@ -1,4 +1,4 @@ -From c0930d2cd7dda529a6637551ee13f4f67b44e0e6 Mon Sep 17 00:00:00 2001 +From 2e7d06b26689fe8ccdd3c37c0fec99059862a095 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:49:52 +1100 Subject: [PATCH] lora: retain the primal activation for adapter deltas @@ -8,7 +8,7 @@ Subject: [PATCH] lora: retain the primal activation for adapter deltas 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 4b4f73e2f9c6962a98f3e52aa6a5556a468efb03..4d55697185aae35ea4cb0183deb23b913b94f43f 100644 +index 4b4f73e2f..4d5569718 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2357,8 +2357,8 @@ ggml_tensor * llm_graph_context::build_lora_mm( @@ -22,3 +22,6 @@ index 4b4f73e2f9c6962a98f3e52aa6a5556a468efb03..4d55697185aae35ea4cb0183deb23b91 if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); +-- +2.56.0 + diff --git a/llama_cpp/patches/0052-cachegen-import-only-into-empty-kv-cells.patch b/llama_cpp/patches/0052-cachegen-import-only-into-empty-kv-cells.patch index c9b2d1bb..e2b76f97 100644 --- a/llama_cpp/patches/0052-cachegen-import-only-into-empty-kv-cells.patch +++ b/llama_cpp/patches/0052-cachegen-import-only-into-empty-kv-cells.patch @@ -1,4 +1,4 @@ -From 7be24198f8fd0bcc7be6e64c086a86ac55aac644 Mon Sep 17 00:00:00 2001 +From 01541c09bcf3405728f23b628fc117293ee8905d Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:49:52 +1100 Subject: [PATCH] cachegen: import only into empty KV cells @@ -10,7 +10,7 @@ Subject: [PATCH] cachegen: import only into empty KV cells 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index e4ea262935b2f644aea7c79afd1646f205cb31d6..e86784f5ac618bfc895c919118bf01ad412d2dd2 100644 +index e4ea26293..e86784f5a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1298,7 +1298,7 @@ std::vector llama_kv_cache::find_chunked_cells( @@ -43,7 +43,7 @@ index e4ea262935b2f644aea7c79afd1646f205cb31d6..e86784f5ac618bfc895c919118bf01ad error = "failed to allocate KV cache cells for CacheGen page"; return false; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h -index 1343a605fd045875eafcba8e032ecc06836252ed..52c06ffa44be8c62c2eab7b3671006d33a0702b6 100644 +index 1343a605f..52c06ffa4 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -274,7 +274,7 @@ public: @@ -56,7 +56,7 @@ index 1343a605fd045875eafcba8e032ecc06836252ed..52c06ffa44be8c62c2eab7b3671006d3 // cells a sequence claims at a time in the unified pool; a multiple of the // row-attention kernels' 32-row block diff --git a/tests/test-skippy-cachegen-import.cpp b/tests/test-skippy-cachegen-import.cpp -index 43cc3f7d6b6c06ffda668a68544d7585db66b32c..f0d28e15c1f714cc9e772a8a53de24071ce49be6 100644 +index 43cc3f7d6..f0d28e15c 100644 --- a/tests/test-skippy-cachegen-import.cpp +++ b/tests/test-skippy-cachegen-import.cpp @@ -121,7 +121,7 @@ llama_hparams make_hparams(bool mla) { @@ -124,3 +124,6 @@ index 43cc3f7d6b6c06ffda668a68544d7585db66b32c..f0d28e15c1f714cc9e772a8a53de2407 const llama_hparams mla_hparams = make_hparams(true); std::unique_ptr mla_kv = make_cache(*model, mla_hparams); if (!populate(*mla_kv, page_token_count)) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0053-cache-restore-composite-attention-occupancy-reporting.patch b/llama_cpp/patches/0053-cache-restore-composite-attention-occupancy-reporting.patch index dc0741b7..f61b4b58 100644 --- a/llama_cpp/patches/0053-cache-restore-composite-attention-occupancy-reporting.patch +++ b/llama_cpp/patches/0053-cache-restore-composite-attention-occupancy-reporting.patch @@ -1,4 +1,4 @@ -From d0ddc98f2aa5523ffa03f396dae8ad48cf0c11cd Mon Sep 17 00:00:00 2001 +From 5c65f719fd29e029e546ea79aeb65d5de2997b35 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 07:49:52 +1100 Subject: [PATCH] cache: restore composite attention occupancy reporting @@ -8,7 +8,7 @@ Subject: [PATCH] cache: restore composite attention occupancy reporting 1 file changed, 26 insertions(+) diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp -index 317c96b46e2670cfaab9b5460d258b28f7b1abb9..57b1d78acff050502af87b8a49bb9c15482f15ab 100644 +index 317c96b46..57b1d78ac 100644 --- a/src/skippy/resident_prefix.cpp +++ b/src/skippy/resident_prefix.cpp @@ -7,6 +7,10 @@ @@ -51,3 +51,6 @@ index 317c96b46e2670cfaab9b5460d258b28f7b1abb9..57b1d78acff050502af87b8a49bb9c15 if (auto * kv = dynamic_cast(memory)) { *cells = kv->get_used_cells(); return true; +-- +2.56.0 + diff --git a/llama_cpp/patches/0054-test-expect-fill-in-recurrent-planning-proofs.patch b/llama_cpp/patches/0054-test-expect-fill-in-recurrent-planning-proofs.patch index 359392f6..09931c68 100644 --- a/llama_cpp/patches/0054-test-expect-fill-in-recurrent-planning-proofs.patch +++ b/llama_cpp/patches/0054-test-expect-fill-in-recurrent-planning-proofs.patch @@ -1,4 +1,4 @@ -From 502b82e9197f810cbb86e16fd8a76dc929b2a014 Mon Sep 17 00:00:00 2001 +From 5ce6e33ec609e120f46cbb78a280cd4750e45255 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 08:16:42 +1100 Subject: [PATCH] test: expect native fill operations in recurrent planning @@ -10,7 +10,7 @@ Subject: [PATCH] test: expect native fill operations in recurrent planning 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/skippy/tests/noalloc_graph_planning.cpp b/src/skippy/tests/noalloc_graph_planning.cpp -index 7470f33093c372d6ba12826d1f45500d0a527ea0..19c998e6a9aa71d8d3146620e7943e08fdee98de 100644 +index 7470f3309..19c998e6a 100644 --- a/src/skippy/tests/noalloc_graph_planning.cpp +++ b/src/skippy/tests/noalloc_graph_planning.cpp @@ -731,7 +731,7 @@ static bool check_state_effects( @@ -23,7 +23,7 @@ index 7470f33093c372d6ba12826d1f45500d0a527ea0..19c998e6a9aa71d8d3146620e7943e08 if (node->op != expected) { std::fprintf(stderr, "metadata-only %s state write uses op %d, expected %d\n", diff --git a/src/skippy/tests/renamed_multishard_planning.cpp b/src/skippy/tests/renamed_multishard_planning.cpp -index 720ba457a714f33af14b6a234f6b563da5e5846d..9dbebc7b3c148cdb328ddd0a0782c1f9817bb8cc 100644 +index 720ba457a..9dbebc7b3 100644 --- a/src/skippy/tests/renamed_multishard_planning.cpp +++ b/src/skippy/tests/renamed_multishard_planning.cpp @@ -726,7 +726,7 @@ bool build_profile( @@ -44,3 +44,6 @@ index 720ba457a714f33af14b6a234f6b563da5e5846d..9dbebc7b3c148cdb328ddd0a0782c1f9 rollback_conv ? GGML_OP_SET_ROWS : GGML_OP_CPY; if (node->op != expect) { error = "delta-net state write at layer " + std::to_string(il) + +-- +2.56.0 + diff --git a/llama_cpp/patches/0055-skippy-preserve-loader-progress-and-position-contracts.patch b/llama_cpp/patches/0055-skippy-preserve-loader-progress-and-position-contracts.patch index c1c5e0b2..be9d6760 100644 --- a/llama_cpp/patches/0055-skippy-preserve-loader-progress-and-position-contracts.patch +++ b/llama_cpp/patches/0055-skippy-preserve-loader-progress-and-position-contracts.patch @@ -1,4 +1,4 @@ -From 312d12aebbb0d73645ca3c87234e204237b5bdb6 Mon Sep 17 00:00:00 2001 +From a10c7ac57956d9a6a12996eca354966c07277e72 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 11:11:17 +1100 Subject: [PATCH] skippy: preserve loader, sampling and position contracts @@ -18,7 +18,7 @@ Subject: [PATCH] skippy: preserve loader, sampling and position contracts 11 files changed, 182 insertions(+), 13 deletions(-) diff --git a/include/skippy/state.h b/include/skippy/state.h -index fc5dcd3894938bfe35a9957d8295b95ba93a4910..6f8a934844112295a656a7bd33f7326d2ae1cc2e 100644 +index fc5dcd389..6f8a93484 100644 --- a/include/skippy/state.h +++ b/include/skippy/state.h @@ -36,6 +36,8 @@ LLAMA_API uint32_t skippy_model_kv_pool_cells(const struct skippy_model * model) @@ -31,10 +31,10 @@ index fc5dcd3894938bfe35a9957d8295b95ba93a4910..6f8a934844112295a656a7bd33f7326d enum skippy_kv_page_codec { diff --git a/src/llama-context.cpp b/src/llama-context.cpp -index 706b35ce07d944745076181e4ceee66ddb186b63..5d106837bf2cd451fa5f2339ebb7dcf128577a8d 100644 +index ca18b3090..011055a63 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp -@@ -2427,11 +2427,6 @@ int llama_context::decode( +@@ -2430,11 +2430,6 @@ int llama_context::decode( GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); @@ -46,7 +46,7 @@ index 706b35ce07d944745076181e4ceee66ddb186b63..5d106837bf2cd451fa5f2339ebb7dcf1 // 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()) { -@@ -2441,6 +2436,12 @@ int llama_context::decode( +@@ -2444,6 +2439,12 @@ int llama_context::decode( output_swaps.clear(); embd_batch_idxs.clear(); @@ -58,8 +58,8 @@ index 706b35ce07d944745076181e4ceee66ddb186b63..5d106837bf2cd451fa5f2339ebb7dcf1 + sched_reserve(graph_build_inputs); - bool did_optimize = false; -@@ -5076,7 +5077,7 @@ llama_context * llama_init_from_model_with_graph_inputs( + if (t_compute_start_us == 0) { +@@ -5084,7 +5085,7 @@ llama_context * llama_init_from_model_with_graph_inputs( } if (params.ctx_type == LLAMA_CONTEXT_TYPE_MTP && @@ -69,7 +69,7 @@ index 706b35ce07d944745076181e4ceee66ddb186b63..5d106837bf2cd451fa5f2339ebb7dcf1 return nullptr; } diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp -index e86784f5ac618bfc895c919118bf01ad412d2dd2..c030afcfe3822f9baf928f957f71cb88f20e7df2 100644 +index e86784f5a..c030afcfe 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2000,6 +2000,18 @@ bool llama_kv_cache::stage_export_kv_page( @@ -113,7 +113,7 @@ index e86784f5ac618bfc895c919118bf01ad412d2dd2..c030afcfe3822f9baf928f957f71cb88 desc.layer_end <= desc.layer_start || static_cast(desc.layer_end) > hparams.n_layer_all || diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp -index 783705c0e3533c7284d60c806ddd0f942be37e2d..4da8cde42878f662f3472a84d9cfac374396a7f4 100644 +index 783705c0e..4da8cde42 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -1788,7 +1788,10 @@ void llama_model_loader::init_mappings(bool prefetch, llama_mlocks * mlock_mmaps @@ -129,7 +129,7 @@ index 783705c0e3533c7284d60c806ddd0f942be37e2d..4da8cde42878f662f3472a84d9cfac37 tensor != nullptr; tensor = ggml_get_next_tensor(ctx.get(), tensor)) { diff --git a/src/skippy/model_loading.cpp b/src/skippy/model_loading.cpp -index 5f100aa461bc9b0f2dfd47e84d681b016c052551..364ae850e8455830c3d9b12b5be119239d86b5ea 100644 +index 5f100aa46..364ae850e 100644 --- a/src/skippy/model_loading.cpp +++ b/src/skippy/model_loading.cpp @@ -534,7 +534,7 @@ static bool skippy_should_create_native_mtp_sidecar( @@ -142,7 +142,7 @@ index 5f100aa461bc9b0f2dfd47e84d681b016c052551..364ae850e8455830c3d9b12b5be11923 } diff --git a/src/skippy/sampling_config.cpp b/src/skippy/sampling_config.cpp -index 6be5559e23d9db28d07485eeefefd8d2af5891e4..32b36bdcd413a58b384e5e5dd483569b815452cc 100644 +index 6be5559e2..32b36bdcd 100644 --- a/src/skippy/sampling_config.cpp +++ b/src/skippy/sampling_config.cpp @@ -102,6 +102,11 @@ static common_params_sampling sampling_params(const skippy_sampling_config * con @@ -158,7 +158,7 @@ index 6be5559e23d9db28d07485eeefefd8d2af5891e4..32b36bdcd413a58b384e5e5dd483569b params.grammar = {COMMON_GRAMMAR_TYPE_TOOL_CALLS, grammar}; } diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp -index db4a27bd227e6b84c29ae9b5628ab3dcc356f391..9d465e25f0336754cd56a19bd3cc21a6eb116072 100644 +index db4a27bd2..9d465e25f 100644 --- a/src/skippy/tests/sampling_history.cpp +++ b/src/skippy/tests/sampling_history.cpp @@ -8,6 +8,7 @@ @@ -205,7 +205,7 @@ index db4a27bd227e6b84c29ae9b5628ab3dcc356f391..9d465e25f0336754cd56a19bd3cc21a6 if (grammar) { for (const bool lazy : {false, true}) { diff --git a/tests/test-batch-alloc.cpp b/tests/test-batch-alloc.cpp -index 93f8e4ef5ee64bec5fe9aff304cff8a9a56896bc..2636db5aed57d43b7d856b13a1809ce206d11810 100644 +index 93f8e4ef5..2636db5ae 100644 --- a/tests/test-batch-alloc.cpp +++ b/tests/test-batch-alloc.cpp @@ -926,6 +926,36 @@ static void test_mrope(testing & t) { @@ -246,7 +246,7 @@ index 93f8e4ef5ee64bec5fe9aff304cff8a9a56896bc..2636db5aed57d43b7d856b13a1809ce2 mock_memory mem; mem.ranges[0] = {0, 24}; diff --git a/tests/test-graph-contract-fixture.h b/tests/test-graph-contract-fixture.h -index 3a520bddaab136148b7734df7cf12f9826322b39..252811ec1bea4a60d618eb7c32fa2a03138ae225 100644 +index 3a520bdda..252811ec1 100644 --- a/tests/test-graph-contract-fixture.h +++ b/tests/test-graph-contract-fixture.h @@ -41,6 +41,10 @@ static int save_graph_contract_fixture(llm_arch arch, const std::string & out, u @@ -297,7 +297,7 @@ index 3a520bddaab136148b7734df7cf12f9826322b39..252811ec1bea4a60d618eb7c32fa2a03 } if (arch == LLM_ARCH_MIMO2 && mtp_layers) { diff --git a/tests/test-skippy-cachegen-import.cpp b/tests/test-skippy-cachegen-import.cpp -index f0d28e15c1f714cc9e772a8a53de24071ce49be6..3dcc05c647edd80e43483290ce45f8ab41798bc8 100644 +index f0d28e15c..3dcc05c64 100644 --- a/tests/test-skippy-cachegen-import.cpp +++ b/tests/test-skippy-cachegen-import.cpp @@ -143,8 +143,9 @@ std::unique_ptr make_cache(const llama_model & model, const llam @@ -383,7 +383,7 @@ index f0d28e15c1f714cc9e772a8a53de24071ce49be6..3dcc05c647edd80e43483290ce45f8ab std::unique_ptr mla_kv = make_cache(*model, mla_hparams); if (!populate(*mla_kv, page_token_count)) { diff --git a/tests/test-skippy-model-loader-accounting.cpp b/tests/test-skippy-model-loader-accounting.cpp -index 22b92c0a8513c9ea5c1983d942aba98dcd0acee0..4145b5b0bb8bbd9efed37b876f5d110bf9ba9687 100644 +index 22b92c0a8..4145b5b0b 100644 --- a/tests/test-skippy-model-loader-accounting.cpp +++ b/tests/test-skippy-model-loader-accounting.cpp @@ -1,5 +1,7 @@ @@ -437,3 +437,6 @@ index 22b92c0a8513c9ea5c1983d942aba98dcd0acee0..4145b5b0bb8bbd9efed37b876f5d110b !check_contextless_fallback(argv[1]) || !check_exact_resident_selection(argv[1]) || !check_multilane_context_capacity(argv[1])) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0056-skippy-preserve-text-chat-parser-contract.patch b/llama_cpp/patches/0056-skippy-preserve-text-chat-parser-contract.patch index ce84ec29..c3059321 100644 --- a/llama_cpp/patches/0056-skippy-preserve-text-chat-parser-contract.patch +++ b/llama_cpp/patches/0056-skippy-preserve-text-chat-parser-contract.patch @@ -1,4 +1,4 @@ -From ad5949bb6ae8a5e12078587bffb52d1d0021e549 Mon Sep 17 00:00:00 2001 +From cd14f0372b1f8f71572ef60d1b1a578038c0bd7a Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 13:04:07 +1100 Subject: [PATCH] skippy: keep the text chat bridge compatible with token-aware @@ -14,7 +14,7 @@ Subject: [PATCH] skippy: keep the text chat bridge compatible with token-aware create mode 100644 tests/test-skippy-chat.cpp diff --git a/common/chat.cpp b/common/chat.cpp -index c144697de6ee5b3485c7a60066bbbbec8bbd9e39..5a44cec445069f962c31b371ff6b7664512b32b9 100644 +index c144697de..5a44cec44 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -391,6 +391,19 @@ common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const common_jso @@ -38,7 +38,7 @@ index c144697de6ee5b3485c7a60066bbbbec8bbd9e39..5a44cec445069f962c31b371ff6b7664 common_chat_templates_inputs inputs; inputs.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK; diff --git a/common/chat.h b/common/chat.h -index c799a04ee0990f452c46923413b5933d89d69011..41875db07e4a7a0b610005d64fce4c4d414fef80 100644 +index c799a04ee..41875db07 100644 --- a/common/chat.h +++ b/common/chat.h @@ -486,6 +486,7 @@ const char * common_reasoning_format_name(common_reasoning_format for @@ -50,7 +50,7 @@ index c799a04ee0990f452c46923413b5933d89d69011..41875db07e4a7a0b610005d64fce4c4d bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates); diff --git a/common/stage-chat.cpp b/common/stage-chat.cpp -index c3362e2a7f9a1d233ae734dc0329bd79c560da6b..d357342da14572a16fa4f27e49aca5def7f5d40a 100644 +index c3362e2a7..d357342da 100644 --- a/common/stage-chat.cpp +++ b/common/stage-chat.cpp @@ -276,6 +276,8 @@ extern "C" SKIPPY_COMMON_API enum skippy_status skippy_apply_chat_template_json( @@ -63,7 +63,7 @@ index c3362e2a7f9a1d233ae734dc0329bd79c560da6b..d357342da14572a16fa4f27e49aca5de if (grammar != nullptr && grammar[0] != '\0') { params.grammar = grammar; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt -index d79157d7f77ff6a82835efa8ad9627c0762ee343..64e6f1cca01e06c50eafdff2bea7fe950f123079 100644 +index d79157d7f..64e6f1cca 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -355,6 +355,11 @@ llama_test_cmd(python3 @@ -80,7 +80,7 @@ index d79157d7f77ff6a82835efa8ad9627c0762ee343..64e6f1cca01e06c50eafdff2bea7fe95 llama_build_and_test(test-skippy-cachegen-metal.cpp) diff --git a/tests/test-skippy-chat.cpp b/tests/test-skippy-chat.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..62f23eb0982769bb74b59acbb7aead4604fe7522 +index 000000000..62f23eb09 --- /dev/null +++ b/tests/test-skippy-chat.cpp @@ -0,0 +1,101 @@ @@ -185,3 +185,6 @@ index 0000000000000000000000000000000000000000..62f23eb0982769bb74b59acbb7aead46 + return 1; + } +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0057-test-retain-cachegen-fixture-parameters.patch b/llama_cpp/patches/0057-test-retain-cachegen-fixture-parameters.patch index ce391293..bb0b7900 100644 --- a/llama_cpp/patches/0057-test-retain-cachegen-fixture-parameters.patch +++ b/llama_cpp/patches/0057-test-retain-cachegen-fixture-parameters.patch @@ -1,4 +1,4 @@ -From 49205b58f0f10cb9d1da3223ebeda8ad16a8c868 Mon Sep 17 00:00:00 2001 +From bfeb72c131a6cedbed12665c6794143beca44f69 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Wed, 25 Nov 2026 13:13:03 +1100 Subject: [PATCH] test: retain CacheGen fixture parameters through cache @@ -9,7 +9,7 @@ Subject: [PATCH] test: retain CacheGen fixture parameters through cache 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test-skippy-cachegen-import.cpp b/tests/test-skippy-cachegen-import.cpp -index 3dcc05c647edd80e43483290ce45f8ab41798bc8..094ec976915501394d10d665e3f034b4d61c1a8c 100644 +index 3dcc05c64..094ec9769 100644 --- a/tests/test-skippy-cachegen-import.cpp +++ b/tests/test-skippy-cachegen-import.cpp @@ -189,7 +189,8 @@ bool populate(llama_kv_cache & kv, uint32_t n_tokens, bool spatial = false, bool @@ -22,3 +22,6 @@ index 3dcc05c647edd80e43483290ce45f8ab41798bc8..094ec976915501394d10d665e3f034b4 if (!populate(*kv, kv_capacity)) { return false; } llama_pos pos = kv_capacity; llama_seq_id seq = 1; +-- +2.56.0 + diff --git a/llama_cpp/patches/0058-graph-preserve-registered-expert-scales.patch b/llama_cpp/patches/0058-graph-preserve-registered-expert-scales.patch index 70a94bfd..9a2542f0 100644 --- a/llama_cpp/patches/0058-graph-preserve-registered-expert-scales.patch +++ b/llama_cpp/patches/0058-graph-preserve-registered-expert-scales.patch @@ -1,4 +1,4 @@ -From 770a542ca72c2bb8a3277a75ad6d5e6859a195da Mon Sep 17 00:00:00 2001 +From 1e472a9fc2d2d4cbb92488a80328df6a7659be9c Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Thu, 26 Nov 2026 14:39:36 +1100 Subject: [PATCH] graph: preserve registered expert scales in explicit overload @@ -12,10 +12,10 @@ Subject: [PATCH] graph: preserve registered expert scales in explicit overload create mode 100644 src/skippy/tests/expert_scales.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 86e25d60fa8197e71399745e012a6b13b61ab38d..37542b3ce4202c5af3d0df2eef01f8f98cde1c13 100644 +index b452ec36e..b7dc9bda9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -384,12 +384,19 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -393,12 +393,19 @@ if (LLAMA_STAGE_BUILD_TESTS) NAME skippy_stage_slice_plan COMMAND skippy-stage-slice-plan) @@ -36,7 +36,7 @@ index 86e25d60fa8197e71399745e012a6b13b61ab38d..37542b3ce4202c5af3d0df2eef01f8f9 add_test(NAME skippy_decode_input_width COMMAND skippy-graph-build-inputs --input-width) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 4d55697185aae35ea4cb0183deb23b913b94f43f..2ff79debfbf52afb9404a8d4884bcfb90fff5bc6 100644 +index 4d5569718..2ff79debf 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2483,6 +2483,10 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( @@ -51,7 +51,7 @@ index 4d55697185aae35ea4cb0183deb23b913b94f43f..2ff79debfbf52afb9404a8d4884bcfb9 ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots diff --git a/src/llama-graph.h b/src/llama-graph.h -index 7422c0e5bf3461c83cb96e7a0e68ef9010be5368..8f2faf06cb6a6fb4690379156e40af0430bbdec3 100644 +index 7422c0e5b..8f2faf06c 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1412,6 +1412,7 @@ struct llm_graph_context { @@ -64,7 +64,7 @@ index 7422c0e5bf3461c83cb96e7a0e68ef9010be5368..8f2faf06cb6a6fb4690379156e40af04 ggml_tensor * cur, // ggml_tensor * b diff --git a/src/skippy/tests/expert_scales.cpp b/src/skippy/tests/expert_scales.cpp new file mode 100644 -index 0000000000000000000000000000000000000000..0d9a7ee8e4dcc1df6f8184dfd7d39302e2c18fdb +index 000000000..0d9a7ee8e --- /dev/null +++ b/src/skippy/tests/expert_scales.cpp @@ -0,0 +1,95 @@ @@ -163,3 +163,6 @@ index 0000000000000000000000000000000000000000..0d9a7ee8e4dcc1df6f8184dfd7d39302 +int main() { + return check_expert_scales(false) && check_expert_scales(true) ? 0 : 1; +} +-- +2.56.0 + diff --git a/llama_cpp/patches/0059-graph-share-moe-routing-with-scaled-projections.patch b/llama_cpp/patches/0059-graph-share-moe-routing-with-scaled-projections.patch index 0cb64d0f..304201ec 100644 --- a/llama_cpp/patches/0059-graph-share-moe-routing-with-scaled-projections.patch +++ b/llama_cpp/patches/0059-graph-share-moe-routing-with-scaled-projections.patch @@ -1,4 +1,4 @@ -From e8a2be8936858b0421e1c7121b477e7ca83ecdb3 Mon Sep 17 00:00:00 2001 +From ba26443654e77351001830506372d25c6f5b297c Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Thu, 26 Nov 2026 14:49:56 +1100 Subject: [PATCH] graph: share MoE routing across optional projection scales @@ -10,10 +10,10 @@ Subject: [PATCH] graph: share MoE routing across optional projection scales 3 files changed, 134 insertions(+), 396 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 37542b3ce4202c5af3d0df2eef01f8f98cde1c13..1985b193a40d2ab166dd58cf983c70a7ded75fe8 100644 +index b7dc9bda9..592c690a9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -389,6 +389,7 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -398,6 +398,7 @@ if (LLAMA_STAGE_BUILD_TESTS) target_compile_features(skippy-expert-scales PRIVATE cxx_std_17) target_link_libraries(skippy-expert-scales PRIVATE llama) add_test(NAME skippy_expert_scales COMMAND skippy-expert-scales) @@ -22,7 +22,7 @@ index 37542b3ce4202c5af3d0df2eef01f8f98cde1c13..1985b193a40d2ab166dd58cf983c70a7 add_executable(skippy-graph-build-inputs skippy/tests/graph_build_inputs.cpp) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 2ff79debfbf52afb9404a8d4884bcfb90fff5bc6..4bb2489eb84cfddc7f78bba201fee272f31a3b74 100644 +index 2ff79debf..4bb2489eb 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2939,394 +2939,23 @@ ggml_tensor * llm_graph_context::build_moe_ffn( @@ -507,7 +507,7 @@ index 2ff79debfbf52afb9404a8d4884bcfb90fff5bc6..4bb2489eb84cfddc7f78bba201fee272 if (amax_src1.scale_s) { diff --git a/src/skippy/tests/expert_scales.cpp b/src/skippy/tests/expert_scales.cpp -index 0d9a7ee8e4dcc1df6f8184dfd7d39302e2c18fdb..c268725c802f8940a755c4036b041cc763db96cf 100644 +index 0d9a7ee8e..c268725c8 100644 --- a/src/skippy/tests/expert_scales.cpp +++ b/src/skippy/tests/expert_scales.cpp @@ -8,6 +8,7 @@ @@ -620,3 +620,6 @@ index 0d9a7ee8e4dcc1df6f8184dfd7d39302e2c18fdb..c268725c802f8940a755c4036b041cc7 + if (argc != 1) return 2; return check_expert_scales(false) && check_expert_scales(true) ? 0 : 1; } +-- +2.56.0 + diff --git a/llama_cpp/patches/0060-metal-trace-chunked-graph-submission.patch b/llama_cpp/patches/0060-metal-trace-chunked-graph-submission.patch index 23938d2d..61231c98 100644 --- a/llama_cpp/patches/0060-metal-trace-chunked-graph-submission.patch +++ b/llama_cpp/patches/0060-metal-trace-chunked-graph-submission.patch @@ -1,4 +1,4 @@ -From 50b85fcd4fdb39b4ad84bdc20ec683361e6956d4 Mon Sep 17 00:00:00 2001 +From c592f5bb8f8d61f973e210621f8f2d39a59004cb Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Sat, 28 Nov 2026 03:43:53 +1100 Subject: [PATCH] metal: trace command buffers in chunked graph submission @@ -11,7 +11,7 @@ Subject: [PATCH] metal: trace command buffers in chunked graph submission 4 files changed, 60 insertions(+), 21 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-context.m b/ggml/src/ggml-metal/ggml-metal-context.m -index fdaf0fc14d977c1e657720ad3d042dea2e643462..423606e34ea44139753f4503e6ad4773e5945899 100644 +index fdaf0fc14..423606e34 100644 --- a/ggml/src/ggml-metal/ggml-metal-context.m +++ b/ggml/src/ggml-metal/ggml-metal-context.m @@ -579,6 +579,15 @@ static enum ggml_status ggml_metal_graph_compute_by_class(ggml_metal_t ctx, stru @@ -74,7 +74,7 @@ index fdaf0fc14d977c1e657720ad3d042dea2e643462..423606e34ea44139753f4503e6ad4773 // checked and released by ggml_metal_synchronize diff --git a/ggml/src/ggml-metal/ggml-metal-timing.cpp b/ggml/src/ggml-metal/ggml-metal-timing.cpp -index 477058b20450bb922f72d502181a5bfecfd2d373..89e7db442c1e97f7fd82aaa1c017b24a005732fa 100644 +index 477058b20..89e7db442 100644 --- a/ggml/src/ggml-metal/ggml-metal-timing.cpp +++ b/ggml/src/ggml-metal/ggml-metal-timing.cpp @@ -280,14 +280,18 @@ uint32_t ggml_metal_timing_next_context_id(void) { @@ -99,7 +99,7 @@ index 477058b20450bb922f72d502181a5bfecfd2d373..89e7db442c1e97f7fd82aaa1c017b24a } diff --git a/ggml/src/ggml-metal/ggml-metal-timing.h b/ggml/src/ggml-metal/ggml-metal-timing.h -index 3cbe29099d2d332bdaf4fdac4d0192b8eb64eeae..d370b42dc7eeae066930c25fc211f9b95c49de71 100644 +index 3cbe29099..d370b42dc 100644 --- a/ggml/src/ggml-metal/ggml-metal-timing.h +++ b/ggml/src/ggml-metal/ggml-metal-timing.h @@ -20,6 +20,8 @@ typedef struct ggml_metal_timing_record * ggml_metal_timing_record_t; @@ -112,7 +112,7 @@ index 3cbe29099d2d332bdaf4fdac4d0192b8eb64eeae..d370b42dc7eeae066930c25fc211f9b9 // captures the calling thread's tag ggml_metal_timing_record_t ggml_metal_timing_begin( diff --git a/tests/test-skippy-tracing-metal.cpp b/tests/test-skippy-tracing-metal.cpp -index dc9cacbcc2a022c6005a6cb1dbb15c207da96d9c..9806a373d267cb0258a59432bae6e6a832bd9e2a 100644 +index dc9cacbcc..9806a373d 100644 --- a/tests/test-skippy-tracing-metal.cpp +++ b/tests/test-skippy-tracing-metal.cpp @@ -13,6 +13,7 @@ @@ -214,3 +214,6 @@ index dc9cacbcc2a022c6005a6cb1dbb15c207da96d9c..9806a373d267cb0258a59432bae6e6a8 for (const auto & t : received) { CHECK(t.tag == TAG); CHECK(std::strcmp(t.backend_name, backend_name) == 0); +-- +2.56.0 + diff --git a/llama_cpp/patches/0061-test-pass-recurrent-replay-policy.patch b/llama_cpp/patches/0061-test-pass-recurrent-replay-policy.patch index 05ed18c2..7e2115e1 100644 --- a/llama_cpp/patches/0061-test-pass-recurrent-replay-policy.patch +++ b/llama_cpp/patches/0061-test-pass-recurrent-replay-policy.patch @@ -1,4 +1,4 @@ -From 2f48a26b7404a3f6c23b30161d9a338cb85e10d8 Mon Sep 17 00:00:00 2001 +From a2f6138ad396ea9e707ac8aa309fd05f07277d60 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Sat, 28 Nov 2026 09:10:53 +1100 Subject: [PATCH] test: pass recurrent replay policy in state round trip @@ -8,7 +8,7 @@ Subject: [PATCH] test: pass recurrent replay policy in state round trip 1 file changed, 1 insertion(+) diff --git a/tests/test-skippy-recurrent-state-roundtrip.cpp b/tests/test-skippy-recurrent-state-roundtrip.cpp -index 0fae7bbd4efbd65e862972e7bbed24e41a378753..a8a52c17bfd351440a2412a341bba6c0afb3fea9 100644 +index 0fae7bbd4..a8a52c17b 100644 --- a/tests/test-skippy-recurrent-state-roundtrip.cpp +++ b/tests/test-skippy-recurrent-state-roundtrip.cpp @@ -72,6 +72,7 @@ static llama_memory_recurrent make_memory(const llama_model & model) { @@ -19,3 +19,6 @@ index 0fae7bbd4efbd65e862972e7bbed24e41a378753..a8a52c17bfd351440a2412a341bba6c0 {}); } +-- +2.56.0 + diff --git a/llama_cpp/patches/0062-build-shorten-vulkan-shader-generator-paths.patch b/llama_cpp/patches/0062-build-shorten-vulkan-shader-generator-paths.patch index f52bdead..92525f44 100644 --- a/llama_cpp/patches/0062-build-shorten-vulkan-shader-generator-paths.patch +++ b/llama_cpp/patches/0062-build-shorten-vulkan-shader-generator-paths.patch @@ -1,4 +1,4 @@ -From 0878d7b339f79126240145a6e17099b5f7460ae0 Mon Sep 17 00:00:00 2001 +From 868373d14a2292a65309b48774c29f805821db5a Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Sat, 28 Nov 2026 09:44:05 +1100 Subject: [PATCH] build: shorten Vulkan shader-generator build paths @@ -8,7 +8,7 @@ Subject: [PATCH] build: shorten Vulkan shader-generator build paths 1 file changed, 3 insertions(+) diff --git a/ggml/src/ggml-vulkan/CMakeLists.txt b/ggml/src/ggml-vulkan/CMakeLists.txt -index d8fa6ef409bbd5b4eef71ad599d1ec128d434d74..84b236a5ca065610330ef0a778a2148949db1c60 100644 +index d8fa6ef40..84b236a5c 100644 --- a/ggml/src/ggml-vulkan/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/CMakeLists.txt @@ -199,6 +199,9 @@ if (Vulkan_FOUND) @@ -21,3 +21,6 @@ index d8fa6ef409bbd5b4eef71ad599d1ec128d434d74..84b236a5ca065610330ef0a778a21489 CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/$ -DCMAKE_INSTALL_BINDIR=. -DCMAKE_BUILD_TYPE=$ +-- +2.56.0 + diff --git a/llama_cpp/patches/0063-graph-preserve-lora-and-scaled-expert-projections.patch b/llama_cpp/patches/0063-graph-preserve-lora-and-scaled-expert-projections.patch index c04dd63f..391dbac1 100644 --- a/llama_cpp/patches/0063-graph-preserve-lora-and-scaled-expert-projections.patch +++ b/llama_cpp/patches/0063-graph-preserve-lora-and-scaled-expert-projections.patch @@ -1,4 +1,4 @@ -From 19b9e086a5ba804892a5611206c327ebe2f30622 Mon Sep 17 00:00:00 2001 +From bf0623b58e25aa57a3ae60dd161b97951ee25b16 Mon Sep 17 00:00:00 2001 From: Skippy CI Date: Mon, 30 Nov 2026 10:05:49 +1100 Subject: [PATCH] skippy: preserve LoRA and expert-scale layouts across b12843 @@ -12,10 +12,10 @@ Subject: [PATCH] skippy: preserve LoRA and expert-scale layouts across b12843 4 files changed, 257 insertions(+), 15 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt -index 1985b193a40d2ab166dd58cf983c70a7ded75fe8..3ef703016283a8a3d0806019c4e9584a590ec380 100644 +index 592c690a9..5e6dcdfc1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt -@@ -390,6 +390,9 @@ if (LLAMA_STAGE_BUILD_TESTS) +@@ -399,6 +399,9 @@ if (LLAMA_STAGE_BUILD_TESTS) target_link_libraries(skippy-expert-scales PRIVATE llama) add_test(NAME skippy_expert_scales COMMAND skippy-expert-scales) add_test(NAME skippy_moe_scale_routing COMMAND skippy-expert-scales --routing) @@ -26,7 +26,7 @@ index 1985b193a40d2ab166dd58cf983c70a7ded75fe8..3ef703016283a8a3d0806019c4e9584a add_executable(skippy-graph-build-inputs skippy/tests/graph_build_inputs.cpp) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp -index 4bb2489eb84cfddc7f78bba201fee272f31a3b74..49229263a58c6fe971a451e4fca257a3fa77ebd4 100644 +index 4bb2489eb..49229263a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2483,31 +2483,51 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( @@ -95,7 +95,7 @@ index 4bb2489eb84cfddc7f78bba201fee272f31a3b74..49229263a58c6fe971a451e4fca257a3 for (const auto & lora : *loras) { llama_adapter_lora_weight * lw = lora.first->get_weight(w); diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp -index 06295e71b6fad4e07c6599e1205a3dedbcc4004a..e1c9c3c146e9332652e82e2310a4b08c7f9b9121 100644 +index 06295e71b..e1c9c3c14 100644 --- a/src/models/bailingmoe3.cpp +++ b/src/models/bailingmoe3.cpp @@ -324,7 +324,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) : @@ -117,7 +117,7 @@ index 06295e71b6fad4e07c6599e1205a3dedbcc4004a..e1c9c3c146e9332652e82e2310a4b08c ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); diff --git a/src/skippy/tests/expert_scales.cpp b/src/skippy/tests/expert_scales.cpp -index c268725c802f8940a755c4036b041cc763db96cf..71d2f11748b6e1cdb51315f1950c95c861fb5553 100644 +index c268725c8..71d2f1174 100644 --- a/src/skippy/tests/expert_scales.cpp +++ b/src/skippy/tests/expert_scales.cpp @@ -10,6 +10,8 @@ @@ -354,3 +354,6 @@ index c268725c802f8940a755c4036b041cc763db96cf..71d2f11748b6e1cdb51315f1950c95c8 if (argc == 2 && std::strcmp(argv[1], "--routing") == 0) { bool passed = true; for (bool random : {false, true}) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0064--feat-skippy-declare-auxiliary-device-capture-outputs.patch b/llama_cpp/patches/0064--feat-skippy-declare-auxiliary-device-capture-outputs.patch new file mode 100644 index 00000000..77659647 --- /dev/null +++ b/llama_cpp/patches/0064--feat-skippy-declare-auxiliary-device-capture-outputs.patch @@ -0,0 +1,128 @@ +From f947961bc600d0400211b57218c5154fbe4221f8 Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 15:16:21 +1100 +Subject: [PATCH] feat(skippy): declare auxiliary device capture outputs + +--- + src/llama-graph.cpp | 9 ++++++++- + src/skippy/state_effects.cpp | 1 + + src/skippy/state_effects.h | 4 ++++ + src/skippy/state_memory.cpp | 1 + + tests/test-skippy-kv-page-export.cpp | 18 ++++++++++++++++-- + 5 files changed, 30 insertions(+), 3 deletions(-) + +diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp +index 49229263a..31974c7a5 100644 +--- a/src/llama-graph.cpp ++++ b/src/llama-graph.cpp +@@ -5543,6 +5543,11 @@ void llm_graph_context::build_layer_inp_dev() const { + + // row layout: [layer_0 | layer_1 | ...] in ascending layer id order + int64_t col = 0; ++ // These rows are auxiliary outputs for a separate speculative context, ++ // not inputs or authoritative recurrent state of this target context. ++ // Declare their storage and exact writes rather than hiding them from ++ // graph admission by tensor name or weakening unknown-state validation. ++ state_read(skippy_state_kind::auxiliary_output, layer_inp_dev, n_layer); + for (size_t il = 0; il < cparams.embeddings_layer_inp.size(); ++il) { + if (!cparams.embeddings_layer_inp[il]) { + continue; +@@ -5553,7 +5558,9 @@ void llm_graph_context::build_layer_inp_dev() const { + GGML_ASSERT(src->ne[0] == n_embd); + + ggml_tensor * dst = ggml_view_2d(ctx0, layer_inp_dev, n_embd, layer_inp_dev->ne[1], layer_inp_dev->nb[1], col*n_embd*ggml_element_size(layer_inp_dev)); +- ggml_build_forward_expand(gf, ggml_set_rows(ctx0, dst, ggml_reshape_2d(ctx0, src, n_embd, n_tokens), inp->idxs)); ++ ggml_tensor * write = ggml_set_rows(ctx0, dst, ggml_reshape_2d(ctx0, src, n_embd, n_tokens), inp->idxs); ++ state_write(skippy_state_kind::auxiliary_output, layer_inp_dev, write, n_layer); ++ ggml_build_forward_expand(gf, write); + col++; + } + GGML_ASSERT(col*n_embd == layer_inp_dev->ne[0]); +diff --git a/src/skippy/state_effects.cpp b/src/skippy/state_effects.cpp +index 3b5690fc3..cfb4c7e15 100644 +--- a/src/skippy/state_effects.cpp ++++ b/src/skippy/state_effects.cpp +@@ -44,6 +44,7 @@ static bool state_kind_known(skippy_state_kind kind) { + case skippy_state_kind::recurrent_conv: + case skippy_state_kind::recurrent_ssm: + case skippy_state_kind::derived_persistent: ++ case skippy_state_kind::auxiliary_output: + return true; + } + return false; +diff --git a/src/skippy/state_effects.h b/src/skippy/state_effects.h +index 5bb6b779b..a051e5dbd 100644 +--- a/src/skippy/state_effects.h ++++ b/src/skippy/state_effects.h +@@ -24,6 +24,10 @@ enum class skippy_state_kind : int32_t { + recurrent_conv = 2, + recurrent_ssm = 3, + derived_persistent = 4, ++ // Caller-visible output scratch, never an input to a later forward of ++ // this context. It is not authoritative model/cache state. Writes still ++ // require exact-graph destination and ordering validation. ++ auxiliary_output = 5, + }; + + enum class skippy_state_access : int32_t { +diff --git a/src/skippy/state_memory.cpp b/src/skippy/state_memory.cpp +index a8a3757ca..3e80de96f 100644 +--- a/src/skippy/state_memory.cpp ++++ b/src/skippy/state_memory.cpp +@@ -146,6 +146,7 @@ uint32_t skippy_graph_cache_capabilities(const llm_graph_result & result) { + switch (effect.kind) { + case skippy_state_kind::kv_key: + case skippy_state_kind::kv_value: ++ case skippy_state_kind::auxiliary_output: + break; + case skippy_state_kind::recurrent_conv: + case skippy_state_kind::recurrent_ssm: +diff --git a/tests/test-skippy-kv-page-export.cpp b/tests/test-skippy-kv-page-export.cpp +index d5e26d984..fcadb119e 100644 +--- a/tests/test-skippy-kv-page-export.cpp ++++ b/tests/test-skippy-kv-page-export.cpp +@@ -23,13 +23,18 @@ static bool graph_cache_capabilities_cover_complete_state() { + auto * input = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_F32, 4); + auto * state = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_F32, 4); + ggml_set_input(input); +- auto * output = ggml_cpy(ctx.get(), input, state); ++ auto * block_output = ggml_scale(ctx.get(), input, 2.0f); ++ auto * output = ggml_cpy(ctx.get(), block_output, state); + auto * graph = ggml_new_graph_custom(ctx.get(), 32, false); + ggml_build_forward_expand(graph, output); ++ std::unique_ptr buffer( ++ ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), ggml_backend_cpu_buffer_type()), ++ ggml_backend_buffer_free); ++ if (!buffer) { return false; } + llm_graph_result result(32); + result.block_boundaries = { + {skippy_block_boundary_kind::entry, 0, input}, +- {skippy_block_boundary_kind::exit, 0, output}, ++ {skippy_block_boundary_kind::exit, 0, block_output}, + }; + const auto capabilities = [&](skippy_state_kind kind) { + result.replace_with_stage_graph(graph, {}, {}, { +@@ -45,11 +50,20 @@ static bool graph_cache_capabilities_cover_complete_state() { + SKIPPY_MEMORY_CACHE_FULL_STATE; + if (capabilities(skippy_state_kind::kv_key) != admitted || + capabilities(skippy_state_kind::kv_value) != admitted || ++ capabilities(skippy_state_kind::auxiliary_output) != admitted || + capabilities(skippy_state_kind::recurrent_conv) != admitted || + capabilities(skippy_state_kind::recurrent_ssm) != admitted || + capabilities(skippy_state_kind::derived_persistent) != SKIPPY_MEMORY_CACHE_FULL_STATE) { + return false; + } ++ // Declared auxiliary outputs still validate their exact write target. ++ capabilities(skippy_state_kind::auxiliary_output); ++ result.state_effects.back().storage = input; ++ if (skippy_graph_cache_capabilities(result) != 0) { return false; } ++ // An unregistered external write cannot become cache-safe merely because ++ // it looks like output scratch. Outside a block it remains inadmissible. ++ result.replace_with_stage_graph(graph, {}, {}, {}); ++ if (skippy_graph_cache_capabilities(result) != 0) { return false; } + capabilities(skippy_state_kind::kv_key); + // Malformed ownership and missing graph admission must never advertise a + // partial exporter, even when the underlying memory supports KV pages. +-- +2.56.0 + diff --git a/llama_cpp/patches/0065--feat-skippy-share-target-forwards-across-speculative.patch b/llama_cpp/patches/0065--feat-skippy-share-target-forwards-across-speculative.patch new file mode 100644 index 00000000..9595a8b2 --- /dev/null +++ b/llama_cpp/patches/0065--feat-skippy-share-target-forwards-across-speculative.patch @@ -0,0 +1,440 @@ +From 5f60b97548f64d345850c5ea7ec4a578f6354429 Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 15:48:34 +1100 +Subject: [PATCH] feat(skippy): share target forwards across speculative lanes + +--- + include/skippy/execution.h | 24 +++++ + src/skippy/execution-batch.cpp | 121 ++++++++++++++++++++++++-- + src/skippy/tests/sampling_history.cpp | 43 +++++++++ + src/skippy/tests/verify_rollback.cpp | 77 +++++++++++++++- + 4 files changed, 252 insertions(+), 13 deletions(-) + +diff --git a/include/skippy/execution.h b/include/skippy/execution.h +index bf9fb497c..5acc63909 100644 +--- a/include/skippy/execution.h ++++ b/include/skippy/execution.h +@@ -100,6 +100,30 @@ struct skippy_iteration_request { + const struct skippy_token_score_request * readout; + }; + ++/** @brief One independently sampled speculative window in a shared forward. */ ++struct skippy_verify_request { ++ struct skippy_session * session; ++ const llama_token * token_ids; ++ size_t token_count; ++ const struct skippy_sampling_config * sampling; ++ llama_token * output_tokens; ++ size_t output_capacity; ++ size_t * out_token_count; ++}; ++ ++/** ++ * @brief Verify equal-length windows on independent lanes of one terminal model. ++ * ++ * Every window retains its own rollback checkpoint and sampler history. Sampling ++ * stops at the first rejected proposal in each lane. The caller must trim or ++ * retire every window before reusing that lane. The combined windows must fit ++ * one native microbatch. Activation-frontier stages are not supported here. ++ */ ++LLAMA_API enum skippy_status skippy_verify_batch_sampled( ++ const struct skippy_verify_request * requests, ++ size_t request_count, ++ struct skippy_error ** out_error); ++ + /** + * @brief Executes mixed prefill chunks and decode tokens in one model iteration. + * +diff --git a/src/skippy/execution-batch.cpp b/src/skippy/execution-batch.cpp +index 46b0d1a27..4f1dfa21a 100644 +--- a/src/skippy/execution-batch.cpp ++++ b/src/skippy/execution-batch.cpp +@@ -244,7 +244,7 @@ bool skippy_model_supports_causal_readout(const struct skippy_model * model) { + model->model->hparams.causal_attn && !llama_model_is_diffusion(model->model); + } + +-enum skippy_status skippy_iteration_batch_sampled( ++static enum skippy_status skippy_iteration_batch_impl( + const struct skippy_iteration_request * requests, + size_t request_count, + struct skippy_activation_desc * output_descs, +@@ -255,7 +255,9 @@ enum skippy_status skippy_iteration_batch_sampled( + llama_token * out_predicted_tokens, + size_t sampled_output_capacity, + size_t * out_sampled_output_count, +- struct skippy_error ** out_error) { ++ struct skippy_error ** out_error, ++ bool verify_all, ++ bool * execution_started = nullptr) { + // 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) { +@@ -345,7 +347,11 @@ enum skippy_status skippy_iteration_batch_sampled( + return SKIPPY_STATUS_INVALID_ARGUMENT; + } + offsets[index + 1] = offsets[index] + request.token_count; +- if (request.sample_last && request_logits) ++sampled_count; ++ if (request.sample_last && request_logits) sampled_count += verify_all ? request.token_count : 1; ++ } ++ if (offsets.back() > first->ctx->n_batch()) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "iteration exceeds native batch capacity"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; + } + // Batched exports are sliced by request offset, which is the microbatch row + // order only when llama decodes the batch with split_simple, so a stage that +@@ -390,22 +396,26 @@ enum skippy_status skippy_iteration_batch_sampled( + // preserves sampler history and does not accept or generate a token. + for (size_t index = 0; index < request_count; ++index) { + auto * session = requests[index].session; +- if (requests[index].readout != nullptr && session->sampling_backend_enabled) { ++ if (verify_all || (requests[index].readout != nullptr && session->sampling_backend_enabled)) { + if (!skippy_retire_backend_sampling(session, out_error)) { + return SKIPPY_STATUS_RUNTIME_ERROR; + } + } ++ if (verify_all) session->sampling_backend_verifying = true; + } + + // This decode overwrites any pending verify window's rollback snapshots. + for (size_t index = 0; index < request_count; ++index) { +- const enum skippy_status settle_status = +- skippy_settle_inplace_verify_window(requests[index].session, out_error); ++ const auto & request = requests[index]; ++ const enum skippy_status settle_status = verify_all ++ ? skippy_checkpoint_verify_window(request.session, request.token_ids, ++ request.token_count, nullptr, nullptr, out_error) ++ : skippy_settle_inplace_verify_window(request.session, out_error); + if (settle_status != SKIPPY_STATUS_OK) return settle_status; + } + + skippy_graph_build_inputs graph_inputs = skippy_graph_build_inputs_from_config( +- &first->stage_model->config, SKIPPY_GLM_DSA_PHASE_HINT_AUTO); ++ &first->stage_model->config, verify_all ? SKIPPY_GLM_DSA_PHASE_HINT_VERIFY : SKIPPY_GLM_DSA_PHASE_HINT_AUTO); + std::vector> frontier_storage; + enum skippy_status status = skippy_build_batched_frontier( + requests, request_count, offsets, graph_inputs, frontier_storage, out_error); +@@ -428,7 +438,7 @@ enum skippy_status skippy_iteration_batch_sampled( + seq_ids[flat] = &seq_values[flat]; + logits[flat] = request_exports || + (request_logits && (request.sample_last || request.readout != nullptr) && +- token + 1 == request.token_count); ++ (verify_all || token + 1 == request.token_count)); + 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) { +@@ -454,6 +464,7 @@ enum skippy_status skippy_iteration_batch_sampled( + }; + prepare_trace.end(); + int32_t decode_rc = 0; ++ if (execution_started != nullptr) *execution_started = true; + if (!skippy_contain_native_failure( + out_error, [&] { decode_rc = first->ctx->decode(batch, graph_inputs); })) { + return SKIPPY_STATUS_RUNTIME_ERROR; +@@ -488,6 +499,7 @@ enum skippy_status skippy_iteration_batch_sampled( + if (consumes_gpu_results) { + skippy_synchronize_context_if_pending(first->stage_model); + } ++ size_t sampled_index = 0; + for (size_t request_index = 0; request_index < request_count; ++request_index) { + const auto & request = requests[request_index]; + status = skippy_copy_batched_exports( +@@ -501,7 +513,7 @@ 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); ++ if (!verify_all) skippy_record_tokens(request.session, request.token_ids, request.token_count); + if (request.readout != nullptr && request_logits) { + const auto & readout = *request.readout; + const int32_t row = static_cast(offsets[request_index + 1] - 1); +@@ -513,6 +525,20 @@ enum skippy_status skippy_iteration_batch_sampled( + } + } + if (request.sample_last && request_logits) { ++ if (verify_all) { ++ for (size_t token = 0; token < request.token_count; ++token) { ++ skippy_record_tokens(request.session, &request.token_ids[token], 1); ++ status = skippy_store_sampled_token(skippy_sample_token_ith( ++ request.session, request.sampling, ++ static_cast(offsets[request_index] + token)), ++ &out_predicted_tokens[sampled_index], out_error); ++ if (status != SKIPPY_STATUS_OK) return status; ++ out_sampled_request_indexes[sampled_index] = request_index; ++ const auto predicted = out_predicted_tokens[sampled_index++]; ++ if (token + 1 < request.token_count && predicted != request.token_ids[token + 1]) break; ++ } ++ continue; ++ } + // Logits are indexed by the original batch row; llama.cpp handles + // sparse output-row translation internally. + samples.push_back({ request.session, request.sampling, +@@ -520,6 +546,10 @@ enum skippy_status skippy_iteration_batch_sampled( + sample_request_indexes.push_back(request_index); + } + } ++ if (verify_all) { ++ *out_sampled_output_count = sampled_index; ++ return skippy_success(out_error); ++ } + 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()) { +@@ -531,6 +561,79 @@ enum skippy_status skippy_iteration_batch_sampled( + return skippy_success(out_error); + } + ++enum skippy_status skippy_iteration_batch_sampled( ++ const struct skippy_iteration_request * requests, size_t request_count, ++ struct skippy_activation_desc * output_descs, void * const * output_payloads, ++ const size_t * output_payload_capacities, size_t * out_output_payload_bytes, ++ size_t * out_sampled_request_indexes, llama_token * out_predicted_tokens, ++ size_t sampled_output_capacity, size_t * out_sampled_output_count, ++ struct skippy_error ** out_error) { ++ return skippy_iteration_batch_impl(requests, request_count, output_descs, output_payloads, ++ output_payload_capacities, out_output_payload_bytes, out_sampled_request_indexes, ++ out_predicted_tokens, sampled_output_capacity, out_sampled_output_count, out_error, false); ++} ++ ++enum skippy_status skippy_verify_batch_sampled( ++ const struct skippy_verify_request * requests, size_t request_count, ++ struct skippy_error ** out_error) { ++ if (requests == nullptr || request_count == 0 || requests[0].session == nullptr || ++ requests[0].session->ctx == nullptr || requests[0].session->stage_model == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "active verification requests are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto * first = requests[0].session; ++ const auto * model = first->stage_model; ++ if (!skippy_model_supports_causal_readout(model) || skippy_emits_activation_frame(first) || ++ (skippy_runtime_has_stage_plan(&model->config) && ++ (model->config.layer_start != 0 || model->config.layer_end < llama_model_n_layer(model->model)))) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "shared verification requires a complete terminal model"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ const size_t width = requests[0].token_count; ++ const size_t capacity = std::min(first->ctx->n_batch(), first->ctx->n_ubatch()); ++ if (width == 0 || request_count > capacity / width) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "verification must fit one native microbatch"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ std::vector iteration(request_count); ++ for (size_t index = 0; index < request_count; ++index) { ++ const auto & request = requests[index]; ++ if (request.token_count != width || request.output_tokens == nullptr || ++ request.output_capacity < width || request.out_token_count == nullptr || ++ request.session == nullptr || request.session->n_past < 0 || ++ width > static_cast(std::numeric_limits::max() - request.session->n_past)) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "invalid equal-length verification window"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto status = skippy_require_usable_session(request.session, out_error); ++ if (status != SKIPPY_STATUS_OK) return status; ++ iteration[index] = {request.session, request.token_ids, width, nullptr, 0, ++ request.sampling, nullptr, nullptr, true, nullptr}; ++ } ++ const size_t total = width * request_count; ++ std::vector indexes(total); ++ std::vector predictions(total); ++ for (size_t index = 0; index < request_count; ++index) *requests[index].out_token_count = 0; ++ size_t count = 0; ++ bool execution_started = false; ++ const auto status = skippy_iteration_batch_impl(iteration.data(), request_count, ++ nullptr, nullptr, nullptr, nullptr, indexes.data(), predictions.data(), total, &count, ++ out_error, true, &execution_started); ++ if (status != SKIPPY_STATUS_OK) { ++ // A partial forward or sampling failure may have changed every lane's ++ // native state. None may continue from a stale Rust/scheduler position. ++ if (execution_started) { ++ for (size_t index = 0; index < request_count; ++index) requests[index].session->reset_required = true; ++ } ++ return status; ++ } ++ for (size_t index = 0; index < count; ++index) { ++ const auto & request = requests[indexes[index]]; ++ request.output_tokens[(*request.out_token_count)++] = predictions[index]; ++ } ++ return skippy_success(out_error); ++} ++ + enum skippy_status skippy_decode_step_frame_batch_sampled( + struct skippy_session * const * sessions, + const llama_token * token_ids, +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index 9d465e25f..ee555231f 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -1001,6 +1001,48 @@ void dense_resident_configuration(const char * path, skippy_runtime_config confi + } + } + ++void shared_verify_preserves_independent_grammars(const char * path) { ++ auto config = skippy_runtime_config_default(); ++ config.selected_backend_device = "CPU"; ++ config.ctx_size = 512; ++ config.lane_count = 2; ++ skippy_model * model = nullptr; ++ skippy_error * error = nullptr; ++ ok(skippy_model_open(path, &config, &model, &error), error); ++ auto * first = create(model); ++ auto * second = create(model); ++ const auto sampling = sampling_config(); ++ const std::vector prefix[2] = {{1, 2, 3, 4}, {1, 4, 3, 2, 5}}; ++ configure(first, sampling, false, prefix[0].size() + 1); ++ configure(second, sampling, false, prefix[1].size() + 1); ++ prefill(first, prefix[0]); ++ prefill(second, prefix[1]); ++ auto * second_sampler = second->sampler; ++ const llama_token inputs[2][3] = {{2, 42, 43}, {3, 42, 0}}; ++ llama_token outputs[2][3] = {}; ++ size_t counts[2] = {}; ++ const skippy_verify_request requests[2] = { ++ {first, inputs[0], 3, &sampling, outputs[0], 3, &counts[0]}, ++ {second, inputs[1], 3, &sampling, outputs[1], 3, &counts[1]}, ++ }; ++ error = nullptr; ++ ok(skippy_verify_batch_sampled(requests, 2, &error), error); ++ CHECK(counts[0] == 3 && counts[1] == 2); ++ CHECK(outputs[0][0] == 42 && outputs[0][1] == 43 && outputs[0][2] == 44); ++ CHECK(outputs[1][0] == 42 && outputs[1][1] == 43); ++ error = nullptr; ++ ok(skippy_retire_verify_checkpoint(first, prefix[0].size(), 3, &error), error); ++ error = nullptr; ++ ok(skippy_trim_session(second, prefix[1].size() + 2, &error), error); ++ CHECK(second->sampler == second_sampler && second->sampling_has_grammar); ++ CHECK(second->sampling_accepted_token_count == prefix[1].size() + 2); ++ CHECK(decode(second, sampling, 43) == 44); ++ release(first); ++ release(second); ++ error = nullptr; ++ ok(skippy_model_free(model, &error), error); ++} ++ + } // namespace + + int main(int argc, char ** argv) { +@@ -1101,5 +1143,6 @@ int main(int argc, char ** argv) { + if (resident && !require_recurrent) { + dense_resident_configuration(argv[1], config); + } ++ if (grammar) shared_verify_preserves_independent_grammars(argv[1]); + return 0; + } +diff --git a/src/skippy/tests/verify_rollback.cpp b/src/skippy/tests/verify_rollback.cpp +index f479a8e4e..08439cd22 100644 +--- a/src/skippy/tests/verify_rollback.cpp ++++ b/src/skippy/tests/verify_rollback.cpp +@@ -32,11 +32,12 @@ void ok(skippy_status status, skippy_error * error) { + skippy_error_free(error); + } + +-skippy_model * open(const char * path, uint32_t rollback_tokens) { ++skippy_model * open(const char * path, uint32_t rollback_tokens, uint32_t lanes = 1) { + auto config = skippy_runtime_config_default(); + config.selected_backend_device = "CPU"; + config.ctx_size = 256; + config.recurrent_rollback_tokens = rollback_tokens; ++ config.lane_count = lanes; + skippy_model * model = nullptr; + skippy_error * error = nullptr; + ok(skippy_model_open(path, &config, &model, &error), error); +@@ -78,13 +79,13 @@ struct Reference { + std::vector state_sizes; + }; + +-Reference reference(skippy_model * model) { ++Reference reference(skippy_model * model, const std::vector & prompt = PROMPT) { + skippy_session * session = create(model); +- prefill(session, std::vector(PROMPT.begin(), PROMPT.end() - 1)); ++ prefill(session, std::vector(prompt.begin(), prompt.end() - 1)); + Reference result; + result.state_sizes.assign(static_cast(session->n_past) + 1, 0); + result.state_sizes[static_cast(session->n_past)] = partial_state_size(session); +- llama_token current = PROMPT.back(); ++ llama_token current = prompt.back(); + while (result.tokens.size() < GENERATED + 2 * WINDOW) { + current = decode(session, current); + result.tokens.push_back(current); +@@ -354,6 +355,70 @@ void release(skippy_model * model) { + ok(skippy_model_free(model, &error), error); + } + ++// Different prompts and rejection points must leave both lanes independent. ++void speculate_shared(const char * path, uint32_t depth) { ++ auto * model = open(path, depth, 2); ++ const std::vector prompts[2] = {PROMPT, {1, 6, 10, 2, 8, 11, 3, 13}}; ++ const Reference expected[2] = {reference(model, prompts[0]), reference(model, prompts[1])}; ++ skippy_session * sessions[2] = {create(model), create(model)}; ++ size_t committed[2] = {}; ++ llama_token current[2] = {prompts[0].back(), prompts[1].back()}; ++ for (size_t lane = 0; lane < 2; ++lane) { ++ prefill(sessions[lane], std::vector(prompts[lane].begin(), prompts[lane].end() - 1)); ++ } ++ for (size_t step = 0; step < 8; ++step) { ++ std::vector inputs[2]; ++ std::vector outputs[2] = {std::vector(WINDOW), std::vector(WINDOW)}; ++ size_t counts[2] = {}; ++ skippy_verify_request requests[2]; ++ for (size_t lane = 0; lane < 2; ++lane) { ++ const auto reject = REJECTIONS[(step + lane) % (sizeof(REJECTIONS) / sizeof(REJECTIONS[0]))]; ++ inputs[lane] = window_of(current[lane], expected[lane].tokens, committed[lane], WINDOW - 1, reject); ++ requests[lane] = {sessions[lane], inputs[lane].data(), WINDOW, nullptr, ++ outputs[lane].data(), WINDOW, &counts[lane]}; ++ } ++ if (step == 0) { ++ const int32_t before[2] = {sessions[0]->n_past, sessions[1]->n_past}; ++ const auto saved = requests[1].session; ++ requests[1].session = requests[0].session; ++ skippy_error * error = nullptr; ++ CHECK(skippy_verify_batch_sampled(requests, 2, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ requests[1].session = saved; ++ CHECK(sessions[0]->n_past == before[0] && sessions[1]->n_past == before[1]); ++ requests[1].token_count = WINDOW - 1; ++ error = nullptr; ++ CHECK(skippy_verify_batch_sampled(requests, 2, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ requests[1].token_count = WINDOW; ++ CHECK(sessions[0]->n_past == before[0] && sessions[1]->n_past == before[1]); ++ } ++ skippy_error * error = nullptr; ++ ok(skippy_verify_batch_sampled(requests, 2, &error), error); ++ for (size_t lane = 0; lane < 2; ++lane) { ++ CHECK(counts[lane] > 0 && counts[lane] <= WINDOW); ++ for (size_t row = 0; row < counts[lane]; ++row) { ++ CHECK(outputs[lane][row] == expected[lane].tokens[committed[lane] + row]); ++ } ++ const uint64_t base = prompts[lane].size() - 1 + committed[lane]; ++ error = nullptr; ++ if (counts[lane] == WINDOW) { ++ ok(skippy_retire_verify_checkpoint(sessions[lane], base, WINDOW, &error), error); ++ } else { ++ ok(skippy_trim_session(sessions[lane], base + counts[lane], &error), error); ++ } ++ committed[lane] += counts[lane]; ++ current[lane] = outputs[lane][counts[lane] - 1]; ++ } ++ } ++ for (size_t lane = 0; lane < 2; ++lane) { ++ CHECK(decode(sessions[lane], current[lane]) == expected[lane].tokens[committed[lane]]); ++ skippy_error * error = nullptr; ++ ok(skippy_session_free(sessions[lane], &error), error); ++ } ++ release(model); ++} ++ + } // namespace + + int main(int argc, char ** argv) { +@@ -388,5 +453,9 @@ int main(int argc, char ** argv) { + speculate_pipelined(shallow, shallow_reference); + } + release(shallow); ++ if (!native_rollback) { ++ speculate_shared(argv[1], WINDOW + 2); ++ speculate_shared(argv[1], 1); ++ } + return 0; + } +-- +2.56.0 + diff --git a/llama_cpp/patches/0066--fix-skippy-reorder-sampling-outputs-by-buffer-lifeti.patch b/llama_cpp/patches/0066--fix-skippy-reorder-sampling-outputs-by-buffer-lifeti.patch new file mode 100644 index 00000000..a6a5b08e --- /dev/null +++ b/llama_cpp/patches/0066--fix-skippy-reorder-sampling-outputs-by-buffer-lifeti.patch @@ -0,0 +1,139 @@ +From be1f96cdc640e96f113d145b6cda5c78c7b9491b Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 16:40:17 +1100 +Subject: [PATCH] fix(skippy): reorder sampling outputs by buffer lifetime + +--- + src/CMakeLists.txt | 2 + + src/llama-context.cpp | 4 +- + src/llama-context.h | 3 + + src/skippy/tests/output_reorder_fixture.cpp | 61 +++++++++++++++++++++ + src/skippy/tests/sampling_history.cpp | 1 + + 5 files changed, 70 insertions(+), 1 deletion(-) + create mode 100644 src/skippy/tests/output_reorder_fixture.cpp + +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 5e6dcdfc1..b6e0fa6dc 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -496,6 +496,8 @@ if (LLAMA_STAGE_BUILD_TESTS) + 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) ++ target_compile_definitions(skippy-sampling-history PRIVATE LLAMA_STAGE_BUILD_TESTS) ++ target_sources(llama PRIVATE skippy/tests/output_reorder_fixture.cpp) + function(add_skippy_sampling_history_tests family fixture state) + foreach(mode grammar penalty resident argmax) + add_test(NAME skippy_sampling_history_${family}_${mode} +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index 011055a63..f2a65001e 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -3087,7 +3087,9 @@ void llama_context::output_reorder() { + } + } + +- if (!sampling.samplers.empty()) { ++ // Samplers may attach or detach after this forward. Permute the ++ // buffers it produced, independently of the current sampler map. ++ if (sampling.sampled.has_data()) { + assert(sampling.logits.size > 0); + assert(sampling.probs.size > 0); + assert(sampling.candidates.size > 0); +diff --git a/src/llama-context.h b/src/llama-context.h +index e09428d41..3f7b1a0fa 100644 +--- a/src/llama-context.h ++++ b/src/llama-context.h +@@ -123,6 +123,9 @@ struct llama_context { + 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 ++ bool output_reorder_sampler_lifecycle_for_test(); ++#endif + + ggml_backend_sched_t get_sched() const; + +diff --git a/src/skippy/tests/output_reorder_fixture.cpp b/src/skippy/tests/output_reorder_fixture.cpp +new file mode 100644 +index 000000000..4dd53a83d +--- /dev/null ++++ b/src/skippy/tests/output_reorder_fixture.cpp +@@ -0,0 +1,61 @@ ++#include "llama-context.h" ++#include "llama-model.h" ++ ++#include ++#include ++ ++bool llama_context::output_reorder_sampler_lifecycle_for_test() { ++ synchronize(); ++ auto previous_sampling = std::move(sampling); ++ auto previous_swaps = std::move(output_swaps); ++ auto previous_idxs = std::move(embd_batch_idxs); ++ const auto previous_logits = logits; ++ const auto previous_embd = embd; ++ const auto previous_nextn = embd_nextn; ++ logits = {nullptr, 0}; ++ embd = {nullptr, 0}; ++ embd_nextn = {nullptr, 0}; ++ sampling = {}; ++ output_swaps.clear(); ++ embd_batch_idxs.clear(); ++ ++ // A sampler attached after a raw-output forward has no sampling views. ++ // Its presence must not make an already pending row permutation read null. ++ auto * sampler = llama_sampler_init_greedy(); ++ sampling.samplers.emplace(0, sampler); ++ output_swaps.push_back({0, 1}); ++ output_reorder(); ++ bool valid = output_swaps.empty(); ++ sampling.samplers.clear(); ++ llama_sampler_free(sampler); ++ ++ // Conversely, detaching the last sampler must not suppress permutation of ++ // the sampling views that the completed forward actually produced. ++ const size_t width = model.vocab.n_tokens(); ++ std::vector scores(2 * width, 0.0f), probs(2 * width, 0.0f); ++ std::vector candidates(2 * width, 0), sampled = {1, 2}; ++ scores[0] = 3.0f; scores[width] = 4.0f; ++ probs[0] = 0.25f; probs[width] = 0.75f; ++ candidates[0] = 1; candidates[width] = 2; ++ sampling.logits = {scores.data(), scores.size()}; ++ sampling.probs = {probs.data(), probs.size()}; ++ sampling.candidates = {candidates.data(), candidates.size()}; ++ sampling.sampled = {sampled.data(), sampled.size()}; ++ sampling.logits_count = {1, 2}; ++ sampling.probs_count = {3, 4}; ++ sampling.candidates_count = {5, 6}; ++ output_swaps.push_back({0, 1}); ++ output_reorder(); ++ valid = valid && sampled[0] == 2 && sampled[1] == 1 && ++ scores[0] == 4.0f && probs[0] == 0.75f && candidates[0] == 2 && ++ sampling.logits_count[0] == 2 && sampling.probs_count[0] == 4 && ++ sampling.candidates_count[0] == 6; ++ ++ sampling = std::move(previous_sampling); ++ output_swaps = std::move(previous_swaps); ++ embd_batch_idxs = std::move(previous_idxs); ++ logits = previous_logits; ++ embd = previous_embd; ++ embd_nextn = previous_nextn; ++ return valid; ++} +\ No newline at end of file +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index ee555231f..fea240bea 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -1090,6 +1090,7 @@ int main(int argc, char ** argv) { + skippy_error * error = nullptr; + const auto status = skippy_model_open(argv[1], &config, &model, &error); + ok(status, error); ++ CHECK(model->ctx->output_reorder_sampler_lifecycle_for_test()); + if (automatic) { + const auto capabilities = skippy_model_memory_cache_capabilities(model); + CHECK(capabilities & SKIPPY_MEMORY_CACHE_RESIDENT_ATTENTION); +-- +2.56.0 + diff --git a/llama_cpp/patches/0067--metal-fuse-contiguous-float32-gated-activations.patch b/llama_cpp/patches/0067--metal-fuse-contiguous-float32-gated-activations.patch new file mode 100644 index 00000000..ab2fb8ea --- /dev/null +++ b/llama_cpp/patches/0067--metal-fuse-contiguous-float32-gated-activations.patch @@ -0,0 +1,314 @@ +From 5c2f864d3864cc17440649da703b1e7074f2ef09 Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 19:12:07 +1100 +Subject: [PATCH] metal: fuse contiguous float32 gated activations + +--- + ggml/src/ggml-metal/ggml-metal-device.cpp | 10 ++++ + ggml/src/ggml-metal/ggml-metal-device.h | 1 + + ggml/src/ggml-metal/ggml-metal-fusion.cpp | 51 +++++++++++++++++ + ggml/src/ggml-metal/ggml-metal-fusion.h | 1 + + ggml/src/ggml-metal/ggml-metal-impl.h | 7 +++ + ggml/src/ggml-metal/ggml-metal-ops.cpp | 23 ++++++++ + ggml/src/ggml-metal/kernels/unary.metal | 24 ++++++++ + tests/test-metal-graph-optimize.cpp | 70 ++++++++++++++++++++++- + 8 files changed, 186 insertions(+), 1 deletion(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index 77dbbe7a0..e4a467436 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -314,6 +314,16 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary(ggml_metal + return res; + } + ++ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary_mul(ggml_metal_library_t lib, const ggml_tensor * op) { ++ const char * name = ggml_get_unary_op(op) == GGML_UNARY_OP_SILU ? ++ "kernel_unary_mul_silu_f32" : "kernel_unary_mul_sigmoid_f32"; ++ auto res = ggml_metal_library_get_pipeline(lib, name); ++ if (!res.pipeline) { ++ res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr); ++ } ++ return res; ++} ++ + ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_glu(ggml_metal_library_t lib, const ggml_tensor * op) { + GGML_ASSERT(ggml_is_contiguous_1(op->src[0])); + +diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h +index 2bbead4b5..492aafd34 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.h ++++ b/ggml/src/ggml-metal/ggml-metal-device.h +@@ -119,6 +119,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_diag + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_repeat (ggml_metal_library_t lib, enum ggml_type tsrc); + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_concat (ggml_metal_library_t lib, enum ggml_type tsrc); + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary (ggml_metal_library_t lib, const struct ggml_tensor * op); ++struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_unary_mul (ggml_metal_library_t lib, const struct ggml_tensor * op); + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_silu_back (ggml_metal_library_t lib, const struct ggml_tensor * op); + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_glu (ggml_metal_library_t lib, const struct ggml_tensor * op); + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_sum (ggml_metal_library_t lib, const struct ggml_tensor * op); +diff --git a/ggml/src/ggml-metal/ggml-metal-fusion.cpp b/ggml/src/ggml-metal/ggml-metal-fusion.cpp +index f5e18f25d..1546621a7 100644 +--- a/ggml/src/ggml-metal/ggml-metal-fusion.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-fusion.cpp +@@ -823,6 +823,55 @@ static bool ggml_metal_fusion_check_mul_mat_add( + + // ---- patterns ------------------------------------------------------------ + ++static bool ggml_metal_fusion_check_unary_mul( ++ const ggml_metal_fusion *, ++ const ggml_tensor * const * nodes, ++ const ggml_cgraph * gf, const int * node_idxs, int idx, ++ ggml_metal_fusion_mode mode) { ++ const ggml_tensor * unary = nodes[0]; ++ const ggml_tensor * mul = nodes[1]; ++ const auto op = ggml_get_unary_op(unary); ++ if (op != GGML_UNARY_OP_SILU && op != GGML_UNARY_OP_SIGMOID) { ++ return false; ++ } ++ const ggml_tensor * other = mul->src[0] == unary ? mul->src[1] : ++ mul->src[1] == unary ? mul->src[0] : nullptr; ++ if (!other || !unary->src[0] || ggml_nelements(mul) > INT32_MAX - 255) { ++ return false; ++ } ++ // This pattern permits a scalar gate, unlike the generic equal-shape ++ // chain. Retain its elision and view checks explicitly. ++ const ggml_op ops[] = { GGML_OP_UNARY, GGML_OP_MUL }; ++ const int output = node_idxs[idx + 1]; ++ if (!ggml_can_fuse_subgraph_ext(gf, node_idxs + idx, 2, ops, &output, 1)) { ++ return false; ++ } ++ const ggml_tensor * tensors[] = { unary->src[0], unary, other, mul }; ++ for (const ggml_tensor * tensor : tensors) { ++ if (tensor->type != GGML_TYPE_F32 || !ggml_is_contiguous(tensor) || ++ (tensor->ne[0] != 1 && tensor->ne[0] != mul->ne[0])) { ++ return false; ++ } ++ for (int d = 1; d < GGML_MAX_DIMS; ++d) { ++ if (tensor->ne[d] != mul->ne[d]) { ++ return false; ++ } ++ } ++ } ++ if (mode == GGML_METAL_FUSION_FULL) { ++ // Equal-shape in-place writes are safe. Partial overlaps and broadcast ++ // inputs aliased with the output could destroy another thread's input. ++ const ggml_tensor * inputs[] = { unary->src[0], other }; ++ for (const ggml_tensor * input : inputs) { ++ if (ggml_metal_fusion_overlap(mul, input) && ++ (mul->data != input->data || !ggml_are_same_shape(mul, input))) { ++ return false; ++ } ++ } ++ } ++ return true; ++} ++ + static const std::vector ops_norm_mul = { GGML_OP_NORM, GGML_OP_MUL }; + static const std::vector ops_norm_mul_add = { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD }; + static const std::vector ops_norm_scale = { GGML_OP_NORM, GGML_OP_SCALE }; +@@ -871,6 +920,7 @@ static const std::vector ops_moe_reduce_8 = { + }; + + static const std::vector ops_mul_mat_add = { GGML_OP_MUL_MAT, GGML_OP_ADD }; ++static const std::vector ops_unary_mul = { GGML_OP_UNARY, GGML_OP_MUL }; + + static const std::vector ggml_metal_fusions = { + { GGML_METAL_FUSION_NORM_MUL, ops_norm_mul, {}, false, ggml_metal_fusion_check_norm }, +@@ -921,6 +971,7 @@ static const std::vector ggml_metal_fusions = { + { GGML_METAL_FUSION_SSM_CONV_SILU, ops_ssm_conv_silu, {}, false, ggml_metal_fusion_check_ssm_conv_silu }, + + { GGML_METAL_FUSION_MUL_MAT_ADD, ops_mul_mat_add, {}, false, ggml_metal_fusion_check_mul_mat_add }, ++ { GGML_METAL_FUSION_UNARY_MUL, ops_unary_mul, {}, true, ggml_metal_fusion_check_unary_mul }, + }; + + // ---- alloc deps ----------------------------------------------------------- +diff --git a/ggml/src/ggml-metal/ggml-metal-fusion.h b/ggml/src/ggml-metal/ggml-metal-fusion.h +index 5d994c249..f49f02b7e 100644 +--- a/ggml/src/ggml-metal/ggml-metal-fusion.h ++++ b/ggml/src/ggml-metal/ggml-metal-fusion.h +@@ -43,6 +43,7 @@ typedef enum ggml_metal_fusion_id { + GGML_METAL_FUSION_MOE_REDUCE, // MUL + expert VIEWs + ADD chain (MoE output reduction) + GGML_METAL_FUSION_SSM_CONV_SILU, // SSM_CONV + UNARY (silu) + GGML_METAL_FUSION_MUL_MAT_ADD, // MUL_MAT + ADD (residual added in the few-row MMA store) ++ GGML_METAL_FUSION_UNARY_MUL, // contiguous f32 SiLU/sigmoid + MUL, including scalar gates + } ggml_metal_fusion_id; + + struct ggml_metal_fusion; // defined in ggml-metal-fusion.cpp +diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h +index a8de8f7f6..6ed51e8bc 100644 +--- a/ggml/src/ggml-metal/ggml-metal-impl.h ++++ b/ggml/src/ggml-metal/ggml-metal-impl.h +@@ -252,6 +252,13 @@ typedef struct { + float max; + } ggml_metal_kargs_unary; + ++typedef struct { ++ uint64_t n; ++ int32_t width; ++ int32_t unary_width; ++ int32_t other_width; ++} ggml_metal_kargs_unary_mul; ++ + typedef struct { + int32_t ne00; + int32_t ne01; +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index e853e57d6..a8e346280 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -869,6 +869,29 @@ int ggml_metal_op_acc(ggml_metal_op_t ctx, int idx) { + int ggml_metal_op_unary(ggml_metal_op_t ctx, int idx) { + ggml_tensor * op = ctx->node(idx); + ++ if (op->op == GGML_OP_UNARY && ctx->use_fusion()) { ++ int n = 1; ++ const auto * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n); ++ if (fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_UNARY_MUL) { ++ ggml_tensor * mul = ctx->node(idx + n - 1); ++ ggml_tensor * other = mul->src[0] == op ? mul->src[1] : mul->src[0]; ++ ggml_metal_kargs_unary_mul args = { ++ (uint64_t) ggml_nelements(mul), (int32_t) mul->ne[0], ++ (int32_t) op->src[0]->ne[0], (int32_t) other->ne[0], ++ }; ++ const auto pipeline = ggml_metal_library_get_pipeline_unary_mul(ctx->lib, op); ++ const int nth = std::min(256, ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); ++ ggml_metal_encoder_set_pipeline(ctx->enc, pipeline); ++ ggml_metal_encoder_set_bytes(ctx->enc, &args, sizeof(args), 0); ++ ggml_metal_encoder_set_buffer(ctx->enc, ggml_metal_get_buffer_id(op->src[0]), 1); ++ ggml_metal_encoder_set_buffer(ctx->enc, ggml_metal_get_buffer_id(other), 2); ++ ggml_metal_encoder_set_buffer(ctx->enc, ggml_metal_get_buffer_id(mul), 3); ++ ggml_metal_encoder_dispatch_threadgroups(ctx->enc, (args.n + nth - 1)/nth, 1, 1, nth, 1, 1); ++ ctx->count_fusions(fusion); ++ return n; ++ } ++ } ++ + // the sigmoid and sqrt(softplus) TOPK_MOE fusions anchor at the gating unary node + if (op->op == GGML_OP_UNARY && ctx->use_fusion() && + (ggml_get_unary_op(op) == GGML_UNARY_OP_SOFTPLUS || ggml_get_unary_op(op) == GGML_UNARY_OP_SIGMOID)) { +diff --git a/ggml/src/ggml-metal/kernels/unary.metal b/ggml/src/ggml-metal/kernels/unary.metal +index c8a441609..56c6e3b7d 100644 +--- a/ggml/src/ggml-metal/kernels/unary.metal ++++ b/ggml/src/ggml-metal/kernels/unary.metal +@@ -3,6 +3,30 @@ + constant short FC_unary_op [[function_constant(FC_UNARY + 0)]]; + constant bool FC_unary_cnt[[function_constant(FC_UNARY + 1)]]; + ++// Keep the unary result as f32 before multiplying, just as the two unfused ++// kernels do. Only dim 0 can broadcast; all other dimensions share row order. ++template ++kernel void kernel_unary_mul_f32( ++ constant ggml_metal_kargs_unary_mul & args, ++ device const float * src0, ++ device const float * src1, ++ device float * dst, ++ uint i [[thread_position_in_grid]]) { ++ if (i >= args.n) { ++ return; ++ } ++ const uint row = i / args.width; ++ const uint col = i % args.width; ++ const float x = src0[row * args.unary_width + (args.unary_width == 1 ? 0 : col)]; ++ const float y = src1[row * args.other_width + (args.other_width == 1 ? 0 : col)]; ++ const float activated = (silu ? x : 1.0f) / (1.0f + exp(-x)); ++ dst[i] = activated * y; ++} ++ ++typedef decltype(kernel_unary_mul_f32) kernel_unary_mul_f32_t; ++template [[host_name("kernel_unary_mul_silu_f32")]] kernel kernel_unary_mul_f32_t kernel_unary_mul_f32; ++template [[host_name("kernel_unary_mul_sigmoid_f32")]] kernel kernel_unary_mul_f32_t kernel_unary_mul_f32; ++ + template + inline constexpr T ggml_metal_unary_cast(U x) { + return (T) x; +diff --git a/tests/test-metal-graph-optimize.cpp b/tests/test-metal-graph-optimize.cpp +index c46987b12..29e700cd8 100644 +--- a/tests/test-metal-graph-optimize.cpp ++++ b/tests/test-metal-graph-optimize.cpp +@@ -273,13 +273,81 @@ static bool check_chained_pack_reader() { + return report_reader("reader of a chained MUL_MAT+ADD sum", packed, after); + } + ++static bool check_unary_mul(ggml_unary_op op, bool gate, bool swap, bool reuse, bool capture, bool strided, ++ ggml_type type = GGML_TYPE_F32, int alias = 0) { ++ ggml_init_params params = { n_tensors*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true }; ++ ggml_context * ctx = ggml_init(params); ++ ggml_tensor * input = ggml_new_tensor_2d(ctx, type, gate ? 1 : 32, 4); ++ if (strided) { ++ ggml_tensor * padded = ggml_new_tensor_2d(ctx, type, 64, 4); ++ input = ggml_view_2d(ctx, padded, 32, 4, padded->nb[1], 0); ++ } ++ ggml_tensor * unary = ggml_unary(ctx, input, op); ++ if (capture) { ++ ggml_set_output(unary); ++ } ++ ggml_tensor * other = ggml_new_tensor_2d(ctx, type, gate ? 32 : input->ne[0], input->ne[1]); ++ ggml_tensor * mul = gate || swap ? ggml_mul(ctx, other, unary) : ggml_mul(ctx, unary, other); ++ ggml_cgraph * graph = ggml_new_graph(ctx); ++ ggml_build_forward_expand(graph, mul); ++ if (reuse) { ++ ggml_build_forward_expand(graph, ggml_add(ctx, unary, unary)); ++ } ++ const auto buft = ggml_backend_dev_buffer_type(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU)); ++ auto buffer = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); ++ if (alias) { ++ // Structural checks only: overlapping storage must not turn a scalar ++ // broadcast or a shifted vector into an unsafe in-place kernel. ++ mul->data = (char *) input->data + (alias == 2 ? sizeof(float) : 0); ++ } ++ std::vector idxs; ++ for (int i = 0; i < ggml_graph_n_nodes(graph); ++i) { ++ if (!ggml_op_is_empty(ggml_graph_node(graph, i)->op)) { ++ idxs.push_back(i); ++ } ++ } ++ int count = 1; ++ const auto * fusion = ggml_metal_fusion_next(graph, idxs.data(), idxs.size(), 0, ++ GGML_METAL_FUSION_FULL, &count); ++ const bool fused = fusion && ggml_metal_fusion_get_id(fusion) == GGML_METAL_FUSION_UNARY_MUL; ++ const bool expected = (op == GGML_UNARY_OP_SILU || op == GGML_UNARY_OP_SIGMOID) && ++ !reuse && !capture && !strided && type == GGML_TYPE_F32 && ++ alias != 2 && !(gate && alias); ++ const bool ok = fused == expected && (!fused || count == 2); ++ std::printf("unary mul: op=%s gate=%d swap=%d reuse=%d capture=%d strided=%d type=%s alias=%d fused=%d expected=%d: %s\n", ++ ggml_unary_op_name(op), gate, swap, reuse, capture, strided, ggml_type_name(type), ++ alias, fused, expected, ok ? "OK" : "FAIL"); ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++ return ok; ++} ++ ++static int run_unary_mul_cases() { ++ int failures = 0; ++ for (auto op : { GGML_UNARY_OP_SILU, GGML_UNARY_OP_SIGMOID }) { ++ for (bool swap : { false, true }) { ++ failures += !check_unary_mul(op, false, swap, false, false, false); ++ } ++ failures += !check_unary_mul(op, true, true, false, false, false); ++ failures += !check_unary_mul(op, false, false, true, false, false); ++ failures += !check_unary_mul(op, false, false, false, true, false); ++ failures += !check_unary_mul(op, false, false, false, false, true); ++ failures += !check_unary_mul(op, false, false, false, false, false, GGML_TYPE_F16); ++ failures += !check_unary_mul(op, false, false, false, false, false, GGML_TYPE_F32, 1); ++ failures += !check_unary_mul(op, false, false, false, false, false, GGML_TYPE_F32, 2); ++ failures += !check_unary_mul(op, true, true, false, false, false, GGML_TYPE_F32, 1); ++ } ++ failures += !check_unary_mul(GGML_UNARY_OP_RELU, false, false, false, false, false); ++ return failures; ++} ++ + int main() { + const std::vector devices = { + { "native simdgroup matrices", true, true }, + { "probed or no simdgroup matrices", false, true }, + }; + const int failures = run_pack_cases(devices) + (check_chained_pack_reader() ? 0 : 1) + run_row_independent_pack_cases() + +- (check_encoder_skips_weight_residual() ? 0 : 1); ++ (check_encoder_skips_weight_residual() ? 0 : 1) + run_unary_mul_cases(); + + return failures == 0 ? 0 : 1; + } +-- +2.56.0 + diff --git a/llama_cpp/patches/0068--metal-prefer-host-greedy-sampling-on-qualified-share.patch b/llama_cpp/patches/0068--metal-prefer-host-greedy-sampling-on-qualified-share.patch new file mode 100644 index 00000000..ef13007c --- /dev/null +++ b/llama_cpp/patches/0068--metal-prefer-host-greedy-sampling-on-qualified-share.patch @@ -0,0 +1,154 @@ +From e7cfa983de7ae5d19b1f8e352fb317e6625502bb Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 20:05:07 +1100 +Subject: [PATCH] metal: prefer host greedy sampling on qualified shared-memory + devices + +--- + ggml/src/ggml-metal/ggml-metal-tuning.cpp | 4 ++++ + ggml/src/ggml-metal/ggml-metal-tuning.h | 5 +++++ + ggml/src/ggml-metal/ggml-metal.cpp | 8 ++++++++ + src/skippy/sampling.cpp | 19 +++++++++++++++++++ + tests/test-metal-graph-optimize.cpp | 13 ++++++++++++- + 5 files changed, 48 insertions(+), 1 deletion(-) + +diff --git a/ggml/src/ggml-metal/ggml-metal-tuning.cpp b/ggml/src/ggml-metal/ggml-metal-tuning.cpp +index 0fe50277e..f8ff94114 100644 +--- a/ggml/src/ggml-metal/ggml-metal-tuning.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-tuning.cpp +@@ -6,6 +6,10 @@ + + namespace ggml_metal_tuning { + ++bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers) { ++ return device == GGML_METAL_DEVICE_M5_MAX && shared_buffers; ++} ++ + int fa_vec_ne11_bucket(int64_t ne11) { + for (int i = 0; i < (int) std::size(FA_VEC_NE11_BUCKETS); ++i) { + if (ne11 < FA_VEC_NE11_BUCKETS[i]) { +diff --git a/ggml/src/ggml-metal/ggml-metal-tuning.h b/ggml/src/ggml-metal/ggml-metal-tuning.h +index d36a0b639..3d858b56f 100644 +--- a/ggml/src/ggml-metal/ggml-metal-tuning.h ++++ b/ggml/src/ggml-metal/ggml-metal-tuning.h +@@ -1,12 +1,17 @@ + #pragma once + + #include "ggml.h" ++#include "ggml-metal-device.h" + + #include + #include + + namespace ggml_metal_tuning { + ++// Qualified on M5 Max with shared graph buffers; leave other devices and ++// private-buffer configurations on their existing sampling path. ++bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers); ++ + // FA vec selection buckets. ne01 (query rows) splits decode (==1) from batch (>=2), the + // batch side refined into {2,3,4,5}: Q>1 reuses one K/V load across rows, so it only pays + // off once ne01 aligns with Q. ne11 (KV length) is bucketed too, as the Q>1 crossover is +diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp +index c54e571c8..1e3b5e1c7 100644 +--- a/ggml/src/ggml-metal/ggml-metal.cpp ++++ b/ggml/src/ggml-metal/ggml-metal.cpp +@@ -1018,7 +1018,15 @@ static void ggml_backend_metal_fusion_set_enabled(ggml_backend_fusion_t finfo, b + ggml_metal_fusion_info_set_enabled((struct ggml_metal_fusion_info *) finfo, enabled); + } + ++static bool ggml_backend_metal_prefers_host_greedy(ggml_backend_dev_t dev) { ++ const auto * props = ggml_metal_device_get_props((ggml_metal_device_t) dev->context); ++ return ggml_metal_tuning::prefer_host_greedy(props->device_id, props->use_shared_buffers); ++} ++ + static void * ggml_backend_metal_get_proc_address(ggml_backend_reg_t reg, const char * name) { ++ if (strcmp(name, "ggml_backend_dev_prefers_host_greedy") == 0) { ++ return (void *) ggml_backend_metal_prefers_host_greedy; ++ } + if (strcmp(name, "ggml_backend_get_features") == 0) { + return (void *)ggml_backend_metal_get_features; + } +diff --git a/src/skippy/sampling.cpp b/src/skippy/sampling.cpp +index d9f980c39..06f9a4735 100644 +--- a/src/skippy/sampling.cpp ++++ b/src/skippy/sampling.cpp +@@ -10,6 +10,7 @@ + #include "skippy/trace_scope.h" + + #include "llama-impl.h" ++#include "llama-model.h" + #include "../vendor/nlohmann/json.hpp" + + #include +@@ -579,6 +580,21 @@ bool skippy_prepare_concurrent_sample( + return session->sampler != nullptr && !session->sampling_backend_enabled; + } + ++static bool skippy_backend_prefers_host_greedy(const skippy_session * session) { ++ if (!session->stage_model || !session->stage_model->model) { ++ return false; ++ } ++ auto * dev = session->stage_model->model->dev_output(); ++ auto * reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; ++ if (!reg) { ++ return false; ++ } ++ using preference_fn = bool (*)(ggml_backend_dev_t); ++ auto preference = (preference_fn) ggml_backend_reg_get_proc_address( ++ reg, "ggml_backend_dev_prefers_host_greedy"); ++ return preference && preference(dev); ++} ++ + void skippy_refresh_backend_sampling( + skippy_session * session, + const skippy_sampling_config * sampling) { +@@ -592,6 +608,9 @@ void skippy_refresh_backend_sampling( + // must likewise never be re-attached. + return; + } ++ if (session->ctx && skippy_backend_prefers_host_greedy(session)) { ++ return; ++ } + session->sampling_backend_enabled = false; + if (session->ctx != nullptr && + // Activation-export and embedding contexts require every output +diff --git a/tests/test-metal-graph-optimize.cpp b/tests/test-metal-graph-optimize.cpp +index 29e700cd8..e9ebdb8df 100644 +--- a/tests/test-metal-graph-optimize.cpp ++++ b/tests/test-metal-graph-optimize.cpp +@@ -7,6 +7,7 @@ + #include "ggml-metal-common.h" + #include "ggml-metal-device.h" + #include "ggml-metal-fusion.h" ++#include "ggml-metal-tuning.h" + + #include + #include +@@ -342,12 +343,22 @@ static int run_unary_mul_cases() { + } + + int main() { ++ int preference_failures = 0; ++ for (auto device : { GGML_METAL_DEVICE_M5_MAX, GGML_METAL_DEVICE_M5_PRO, ++ GGML_METAL_DEVICE_M4_MAX, GGML_METAL_DEVICE_GENERIC }) { ++ for (bool shared : { false, true }) { ++ const bool expected = device == GGML_METAL_DEVICE_M5_MAX && shared; ++ const bool ok = ggml_metal_tuning::prefer_host_greedy(device, shared) == expected; ++ std::printf("host greedy preference: device=%d shared=%d: %s\n", device, shared, ok ? "OK" : "FAIL"); ++ preference_failures += !ok; ++ } ++ } + const std::vector devices = { + { "native simdgroup matrices", true, true }, + { "probed or no simdgroup matrices", false, true }, + }; + const int failures = run_pack_cases(devices) + (check_chained_pack_reader() ? 0 : 1) + run_row_independent_pack_cases() + +- (check_encoder_skips_weight_residual() ? 0 : 1) + run_unary_mul_cases(); ++ (check_encoder_skips_weight_residual() ? 0 : 1) + run_unary_mul_cases() + preference_failures; + + return failures == 0 ? 0 : 1; + } +-- +2.56.0 + diff --git a/llama_cpp/patches/0069--memory-preserve-peer-recurrent-rollback-history.patch b/llama_cpp/patches/0069--memory-preserve-peer-recurrent-rollback-history.patch new file mode 100644 index 00000000..196b27d8 --- /dev/null +++ b/llama_cpp/patches/0069--memory-preserve-peer-recurrent-rollback-history.patch @@ -0,0 +1,453 @@ +From 746f7958c47897f27f507b06482dc300ae59a8ab Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sat, 14 Nov 2026 22:15:39 +1100 +Subject: [PATCH] memory: preserve peer recurrent rollback history + +--- + src/CMakeLists.txt | 1 + + src/llama-memory-recurrent-copy.cpp | 96 ++++++++++++++++ + src/llama-memory-recurrent-copy.h | 20 ++++ + src/llama-memory-recurrent.cpp | 18 +-- + src/llama-memory-recurrent.h | 6 +- + src/skippy/tests/verify_rollback.cpp | 157 ++++++++++++++++++++++++++- + 6 files changed, 288 insertions(+), 10 deletions(-) + create mode 100644 src/llama-memory-recurrent-copy.cpp + create mode 100644 src/llama-memory-recurrent-copy.h + +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index b6e0fa6dc..829600868 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -34,6 +34,7 @@ set(LLAMA_CORE_SOURCES + llama-memory-hybrid-iswa.cpp + llama-memory-hybrid-idx.cpp + llama-memory-recurrent.cpp ++ llama-memory-recurrent-copy.cpp + llama-mmap.cpp + llama-model-loader.cpp + llama-model-saver.cpp +diff --git a/src/llama-memory-recurrent-copy.cpp b/src/llama-memory-recurrent-copy.cpp +new file mode 100644 +index 000000000..9c269200b +--- /dev/null ++++ b/src/llama-memory-recurrent-copy.cpp +@@ -0,0 +1,96 @@ ++#include "llama-memory-recurrent-copy.h" ++#include "llama-memory-recurrent.h" ++#include "ggml-backend.h" ++ ++#include ++ ++void llama_recurrent_copy_rows( ++ const std::vector & tensors, ++ const std::vector> & groups, ++ std::vector & scratch) { ++ for (auto * tensor : tensors) { ++ if (!tensor || !tensor->buffer) { ++ continue; ++ } ++ const size_t row_bytes = ggml_row_size(tensor->type, tensor->ne[0]); ++ for (const auto & rows : groups) { ++ if (rows.empty()) continue; ++ const size_t needed = rows.size() * row_bytes; ++ if (scratch.size() < needed) scratch.resize(needed); ++ for (size_t i = 0; i < rows.size(); ++i) { ++ const auto & row = rows[i]; ++ GGML_ASSERT(row.destination < tensor->ne[1]); ++ auto * output = scratch.data() + i * row_bytes; ++ if (row.zero) { ++ std::memset(output, 0, row_bytes); ++ } else { ++ GGML_ASSERT(row.source < tensor->ne[1]); ++ ggml_backend_tensor_get(tensor, output, row.source * tensor->nb[1], row_bytes); ++ } ++ } ++ for (size_t i = 0; i < rows.size(); ++i) { ++ ggml_backend_tensor_set(tensor, scratch.data() + i * row_bytes, ++ rows[i].destination * tensor->nb[1], row_bytes); ++ } ++ } ++ } ++} ++ ++void llama_memory_recurrent::preserve_peer_rollback(uint32_t first, uint32_t last, uint32_t n_seqs) { ++ std::vector pending(last - first + 1, 0); ++ bool preserve = false; ++ for (uint32_t i = first; i <= last; ++i) { ++ auto & cell = cells[i]; ++ if (cell.seq_id.empty()) { ++ cell.rs_max = 0; ++ } else { ++ const auto seq = *cell.seq_id.begin(); ++ if (seq >= 0 && (size_t) seq < rs_idx.size()) { ++ pending[i - first] = rs_idx[seq]; ++ } ++ } ++ if (i < first + n_seqs) { ++ continue; // the new forward replaces active lanes' snapshot history ++ } ++ const uint32_t consumed = pending[i - first]; ++ GGML_ASSERT(consumed <= cell.rs_max); ++ cell.rs_max -= consumed; ++ preserve |= cell.rs_max > 0 && (cell.src0 != (int32_t) i || consumed > 0); ++ } ++ if (!preserve) { ++ return; ++ } ++ ++ // Moving an inactive lane's current state alone loses its live snapshots. ++ // Materialize the whole working range first, including pending rollbacks, ++ // so a snapshot write cannot clobber an active lane's source state. ++ std::vector> groups(n_rs_seq + 1); ++ for (uint32_t i = first; i <= last; ++i) { ++ const auto & cell = cells[i]; ++ const uint32_t consumed = pending[i - first]; ++ groups[0].push_back({(uint32_t) cell.src0 + consumed * size, i, cell.src0 == rs_z}); ++ if (i < first + n_seqs || (cell.src0 == (int32_t) i && consumed == 0)) { ++ continue; ++ } ++ for (uint32_t plane = 1; plane <= cell.rs_max; ++plane) { ++ groups[plane].push_back({(uint32_t) cell.src0 + (consumed + plane) * size, i + plane * size}); ++ } ++ } ++ // Each plane is gathered before it is written. Pending rollback only ++ // shifts snapshots towards earlier planes, so ascending groups are safe. ++ llama_recurrent_copy_rows(r_l, groups, rollback_copy_scratch); ++ llama_recurrent_copy_rows(s_l, groups, rollback_copy_scratch); ++ llama_recurrent_copy_rows(p_l, groups, rollback_copy_scratch); ++ for (uint32_t i = first; i <= last; ++i) { ++ auto & cell = cells[i]; ++ cell.src0 = i; ++ for (const auto seq : cell.seq_id) { ++ if (seq >= 0 && (size_t) seq < rs_idx.size()) { ++ rs_idx[seq] = 0; ++ } ++ } ++ } ++ // New/empty rows were zero-filled above. The old zero source may now be ++ // a materialized destination and must not be cleared by the graph. ++ rs_z = -1; ++} +diff --git a/src/llama-memory-recurrent-copy.h b/src/llama-memory-recurrent-copy.h +new file mode 100644 +index 000000000..6577e206d +--- /dev/null ++++ b/src/llama-memory-recurrent-copy.h +@@ -0,0 +1,20 @@ ++#pragma once ++ ++#include ++#include ++#include ++ ++struct ggml_tensor; ++ ++struct llama_recurrent_copy_row { ++ uint32_t source; ++ uint32_t destination; ++ bool zero = false; ++}; ++ ++// Groups must be ordered by destination snapshot plane. Sources are from the ++// same or a later plane; gather each group before writing to preserve aliases. ++void llama_recurrent_copy_rows( ++ const std::vector & tensors, ++ const std::vector> & groups, ++ std::vector & scratch); +diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp +index 3f4e7a9d6..b13ebe1c7 100644 +--- a/src/llama-memory-recurrent.cpp ++++ b/src/llama-memory-recurrent.cpp +@@ -1,5 +1,6 @@ + #include "llama-memory-recurrent.h" + #include "skippy/trace_scope.h" ++#include "llama-memory-recurrent-copy.h" + + #include "ggml-backend.h" + #include "llama-impl.h" +@@ -304,9 +305,10 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos + const bool pending = rs_idx[seq_id] != 0; + if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) { + if (rs_replay) { +- // the next ubatch replays only the kept pending tokens ++ // The next ubatch replays only the kept pending tokens. ++ // Until then, another trim can shorten that same window. + cell.rs_pend -= rollback; +- cell.rs_max = 0; ++ cell.rs_max -= rollback; + } else { + set_rs_idx(seq_id, (uint32_t) rollback); + } +@@ -600,7 +602,7 @@ bool llama_memory_recurrent::prepare(const std::vector & ubatches) + bool success = true; + + for (const auto & ubatch : ubatches) { +- if (!find_slot(ubatch)) { ++ if (!find_slot(ubatch, true)) { + success = false; + break; + } +@@ -614,7 +616,7 @@ bool llama_memory_recurrent::prepare(const std::vector & ubatches) + return success; + } + +-bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { ++bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch, bool planning) { + const uint32_t n_seq_tokens = ubatch.n_seq_tokens; + const uint32_t n_seqs = ubatch.n_seqs; + +@@ -751,10 +753,6 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { + std::swap(dst_cell.rs_max, src_cell.rs_max); + std::swap(dst_cell.rs_pend, src_cell.rs_pend); + std::swap(dst_cell.seq_id, src_cell.seq_id); +- // the cell moved out only gets its final state copied, its rollback snapshots stay behind +- if (!rs_replay) { +- src_cell.rs_max = 0; +- } + + // swap tails + for (uint32_t j = 0; j < size; ++j) { +@@ -828,6 +826,10 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { + } + } + ++ if (!planning && !rs_replay && n_rs_seq > 0) { ++ preserve_peer_rollback(min, max, n_seqs); ++ } ++ + // allow getting the range of used cells, from head to head + n + head = min; + n = max - min + 1; +diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h +index 956abcd06..68da55818 100644 +--- a/src/llama-memory-recurrent.h ++++ b/src/llama-memory-recurrent.h +@@ -59,7 +59,7 @@ public: + bool prepare(const std::vector & ubatches); + + // find a contiguous slot of memory cells and emplace the ubatch there +- bool find_slot(const llama_ubatch & ubatch); ++ bool find_slot(const llama_ubatch & ubatch, bool planning = false); + + bool get_can_shift() const override; + +@@ -142,6 +142,10 @@ public: + std::vector graph_spgb_l; + + private: ++ // Reused only when a peer update relocates live rollback history. ++ std::vector rollback_copy_scratch; ++ void preserve_peer_rollback(uint32_t first, uint32_t last, uint32_t n_seqs); ++ + //const llama_model & model; + const llama_hparams & hparams; + +diff --git a/src/skippy/tests/verify_rollback.cpp b/src/skippy/tests/verify_rollback.cpp +index 08439cd22..1ec03f8b9 100644 +--- a/src/skippy/tests/verify_rollback.cpp ++++ b/src/skippy/tests/verify_rollback.cpp +@@ -7,6 +7,9 @@ + #include "log_gate.h" + static const skippy::log_gate::installer skippy_log_gate_installer{}; + #include "../runtime_types.h" ++#include "../state_memory.h" ++#include "llama-memory-recurrent.h" ++#include "ggml-backend.h" + + #include + #include +@@ -23,6 +26,7 @@ constexpr size_t WINDOW = 5; + constexpr size_t GENERATED = 48; + // Proposal index rejected in successive windows; -1 accepts every row. + constexpr int REJECTIONS[] = {-1, 0, 3, 1, -1, 2}; ++const char * test_device = "CPU"; + + void ok(skippy_status status, skippy_error * error) { + if (status != SKIPPY_STATUS_OK) { +@@ -34,7 +38,8 @@ void ok(skippy_status status, skippy_error * error) { + + skippy_model * open(const char * path, uint32_t rollback_tokens, uint32_t lanes = 1) { + auto config = skippy_runtime_config_default(); +- config.selected_backend_device = "CPU"; ++ config.selected_backend_device = test_device; ++ if (std::strcmp(test_device, "CPU") != 0) config.n_gpu_layers = 999; + config.ctx_size = 256; + config.recurrent_rollback_tokens = rollback_tokens; + config.lane_count = lanes; +@@ -52,6 +57,7 @@ skippy_session * create(skippy_model * model) { + } + + void prefill(skippy_session * session, const std::vector & tokens) { ++ if (tokens.empty()) return; + size_t bytes = 0; + skippy_error * error = nullptr; + ok(skippy_prefill_chunk(session, tokens.data(), tokens.size(), nullptr, 0, nullptr, 0, &bytes, &error), error); +@@ -419,9 +425,157 @@ void speculate_shared(const char * path, uint32_t depth) { + release(model); + } + ++std::vector recurrent_row(skippy_session * session, uint32_t plane) { ++ auto * memory = skippy_memory_recurrent_adapter(session->ctx->get_memory()); ++ CHECK(memory != nullptr); ++ const int32_t tail = memory->cells[session->seq_id].tail; ++ CHECK(tail >= 0); ++ const int32_t source = memory->cells[tail].src; ++ const size_t row = plane * memory->size + static_cast(source >= 0 ? source : tail); ++ std::vector bytes; ++ const auto append = [&](const std::vector * tensors) { ++ for (auto * tensor : *tensors) { ++ if (!tensor) continue; ++ CHECK(row < static_cast(tensor->ne[1])); ++ const size_t size = ggml_row_size(tensor->type, tensor->ne[0]); ++ const size_t offset = bytes.size(); ++ bytes.resize(offset + size); ++ ggml_backend_tensor_get(tensor, bytes.data() + offset, row * tensor->nb[1], size); ++ } ++ }; ++ for (const auto * tensors : {&memory->r_l, &memory->s_l, &memory->p_l}) { ++ append(tensors); ++ } ++ if (memory->rs_replay) { ++ for (const auto * tensors : {&memory->spk_l, &memory->spv_l, &memory->spgb_l}) { ++ append(tensors); ++ } ++ } ++ return bytes; ++} ++ ++// Repair of B is delayed while A+C decode and move C into B's previous cell. ++// Inactive recurrent state must retain its rollback history across that move. ++void delayed_peer_repair(const char * path, unsigned mode) { ++ auto * model = open(path, WINDOW + 2, 3); ++ const std::vector prompts[3] = { ++ PROMPT, {1, 6, 10, 2, 8, 11, 3, 13}, ++ (mode & 4) ? std::vector{7} : ++ std::vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7}, ++ }; ++ const Reference expected[3] = { ++ reference(model, prompts[0]), reference(model, prompts[1]), reference(model, prompts[2]), ++ }; ++ skippy_session * sessions[3] = {create(model), create(model), create(model)}; ++ if (std::strcmp(test_device, "CPU") != 0) { ++ auto * memory = skippy_memory_recurrent_adapter(sessions[0]->ctx->get_memory()); ++ bool gpu_state = false; ++ for (auto * tensor : memory->s_l) { ++ if (!tensor || !tensor->buffer) continue; ++ auto * device = ggml_backend_buft_get_device(ggml_backend_buffer_get_type(tensor->buffer)); ++ gpu_state |= device && ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_GPU; ++ } ++ CHECK(gpu_state); ++ } ++ for (size_t lane = 0; lane < 3; ++lane) { ++ prefill(sessions[lane], std::vector(prompts[lane].begin(), prompts[lane].end() - 1)); ++ } ++ std::vector inputs[2] = { ++ window_of(prompts[0].back(), expected[0].tokens, 0, WINDOW - 1, (mode & 1) ? 1 : -1), ++ window_of(prompts[1].back(), expected[1].tokens, 0, WINDOW - 1, (mode & 2) ? 3 : 0), ++ }; ++ llama_token outputs[2][WINDOW] = {}; ++ size_t counts[2] = {}; ++ skippy_verify_request requests[2] = { ++ {sessions[0], inputs[0].data(), WINDOW, nullptr, outputs[0], WINDOW, &counts[0]}, ++ {sessions[1], inputs[1].data(), WINDOW, nullptr, outputs[1], WINDOW, &counts[1]}, ++ }; ++ skippy_error * error = nullptr; ++ ok(skippy_verify_batch_sampled(requests, 2, &error), error); ++ CHECK(counts[0] == ((mode & 1) ? 2 : WINDOW) && counts[1] == ((mode & 2) ? WINDOW - 1 : 1)); ++ const bool in_place = sessions[1]->inplace_verify_window.valid; ++ auto * memory = skippy_memory_recurrent_adapter(sessions[1]->ctx->get_memory()); ++ const bool replay = memory->rs_replay; ++ const auto snapshot = in_place && !replay ? recurrent_row(sessions[1], WINDOW - 1) : std::vector{}; ++ error = nullptr; ++ if (counts[0] == WINDOW) { ++ ok(skippy_retire_verify_checkpoint(sessions[0], prompts[0].size() - 1, WINDOW, &error), error); ++ } else { ++ ok(skippy_trim_session(sessions[0], prompts[0].size() - 1 + counts[0], &error), error); ++ } ++ if ((mode & 2) && in_place) { ++ error = nullptr; ++ ok(skippy_trim_session(sessions[1], prompts[1].size() - 1 + counts[1], &error), error); ++ } ++ std::vector> history; ++ uint32_t replay_pending = 0; ++ if (in_place && replay) { ++ const auto & cell = memory->cells[memory->cells[sessions[1]->seq_id].tail]; ++ replay_pending = cell.rs_pend; ++ CHECK(replay_pending > 0); ++ history.push_back(recurrent_row(sessions[1], 0)); ++ } else if (in_place) { ++ const auto pending = memory->rs_idx[sessions[1]->seq_id]; ++ const auto depth = memory->cells[memory->cells[sessions[1]->seq_id].tail].rs_max; ++ for (uint32_t plane = pending; plane <= depth; ++plane) { ++ history.push_back(recurrent_row(sessions[1], plane)); ++ } ++ } ++ ++ llama_token current[2] = {outputs[0][counts[0] - 1], prompts[2].back()}; ++ skippy_iteration_request peers[2] = {}; ++ for (size_t i = 0; i < 2; ++i) { ++ peers[i].session = sessions[i == 0 ? 0 : 2]; ++ peers[i].token_ids = ¤t[i]; ++ peers[i].token_count = 1; ++ peers[i].sample_last = true; ++ } ++ size_t indexes[2] = {}, count = 0; ++ llama_token predictions[2] = {}; ++ error = nullptr; ++ ok(skippy_iteration_batch_sampled(peers, 2, nullptr, nullptr, nullptr, nullptr, ++ indexes, predictions, 2, &count, &error), error); ++ CHECK(count == 2 && predictions[0] == expected[0].tokens[counts[0]] && predictions[1] == expected[2].tokens[0]); ++ if (in_place && replay) { ++ const auto & cell = memory->cells[memory->cells[sessions[1]->seq_id].tail]; ++ CHECK(cell.rs_pend == replay_pending); ++ CHECK(recurrent_row(sessions[1], 0) == history.front()); ++ } else if (in_place) { ++ const auto pending = memory->rs_idx[sessions[1]->seq_id]; ++ for (size_t plane = 0; plane < history.size(); ++plane) { ++ CHECK(recurrent_row(sessions[1], pending + plane) == history[plane]); ++ } ++ } ++ ++ error = nullptr; ++ ok(skippy_trim_session(sessions[1], prompts[1].size(), &error), error); ++ if (in_place && !replay) { ++ CHECK(recurrent_row(sessions[1], memory->rs_idx[sessions[1]->seq_id]) == snapshot); ++ } ++ llama_token token = outputs[1][0]; ++ for (size_t i = 1; i < 16; ++i) { ++ token = decode(sessions[1], token); ++ CHECK(token == expected[1].tokens[i]); ++ } ++ for (auto * session : sessions) { ++ error = nullptr; ++ ok(skippy_session_free(session, &error), error); ++ } ++ release(model); ++ std::fprintf(stderr, "delayed peer repair: mode=%u independent recurrent rollback preserved\n", mode); ++} ++ + } // namespace + + int main(int argc, char ** argv) { ++ if (argc == 3 && std::strcmp(argv[2], "peer-gpu") == 0) { ++ ggml_backend_load_all(); ++ auto * device = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU); ++ CHECK(device != nullptr); ++ test_device = ggml_backend_dev_name(device); ++ for (unsigned mode : {0u, 1u, 2u, 7u}) delayed_peer_repair(argv[1], mode); ++ return 0; ++ } + // `sliding-window`: the fixture's attention slides, so no window may roll + // back in place and every one takes a host checkpoint. + // `native-rollback`: the memory rewinds through its own seq_rm. +@@ -456,6 +610,7 @@ int main(int argc, char ** argv) { + if (!native_rollback) { + speculate_shared(argv[1], WINDOW + 2); + speculate_shared(argv[1], 1); ++ for (unsigned mode : {0u, 1u, 2u, 7u}) delayed_peer_repair(argv[1], mode); + } + return 0; + } +-- +2.56.0 + diff --git a/llama_cpp/patches/0070--metal-reuse-routed-vector-activations-across-more-output-rows.patch b/llama_cpp/patches/0070--metal-reuse-routed-vector-activations-across-more-output-rows.patch new file mode 100644 index 00000000..ec1bc329 --- /dev/null +++ b/llama_cpp/patches/0070--metal-reuse-routed-vector-activations-across-more-output-rows.patch @@ -0,0 +1,1443 @@ +From 7178ecde894dda573a025c6c8c53fb3d99c9451f Mon Sep 17 00:00:00 2001 +From: Codex +Date: Mon, 16 Nov 2026 05:06:29 +1100 +Subject: [PATCH] metal: tune routed vector reuse and bounded offsets + +Retain the qualified output-row reuse specializations. Add checked uint32 +relative offsets for qualified shared-buffer R4 and R8 geometries. Enable R8 +by default on M1 Ultra and M5 Max, and R4 on M1 Ultra. Keep other devices on +the original default and preserve private diagnostic overrides. + +Share the existing quantized-vector arithmetic between both offset widths. +Preserve unsupported-shape, stride, byte-span and old-library fallbacks, with +cached positive and negative function discovery. Add CPU-only policy CTest +coverage and explicit native paired/FP64/masked/view/fallback qualification. +The public Skippy ABI and stored model bytes remain unchanged. +--- + ggml/src/ggml-metal/CMakeLists.txt | 13 +- + ggml/src/ggml-metal/ggml-metal-device.cpp | 28 ++ + ggml/src/ggml-metal/ggml-metal-device.h | 1 + + ggml/src/ggml-metal/ggml-metal-device.m | 30 ++ + .../ggml-metal/ggml-metal-routed-offsets.h | 70 +++++ + .../src/ggml-metal/ggml-metal-routed-tuning.h | 27 ++ + ggml/src/ggml-metal/kernels/mul_mv.metal | 264 +----------------- + ggml/src/ggml-metal/kernels/mul_mv_q_n.h | 262 +++++++++++++++++ + ggml/src/ggml-metal/kernels/routed_u32.metal | 75 +++++ + .../ggml-metal/kernels/routed_u32_r4.metal | 75 +++++ + tests/CMakeLists.txt | 4 + + tests/test-backend-ops.cpp | 5 + + tests/test-backend-portable-routed.h | 43 +++ + tests/test-metal-graph-optimize.cpp | 43 +++ + tests/test-metal-routed-u32.cpp | 237 ++++++++++++++++ + 15 files changed, 915 insertions(+), 262 deletions(-) + create mode 100644 ggml/src/ggml-metal/ggml-metal-routed-offsets.h + create mode 100644 ggml/src/ggml-metal/ggml-metal-routed-tuning.h + create mode 100644 ggml/src/ggml-metal/kernels/mul_mv_q_n.h + create mode 100644 ggml/src/ggml-metal/kernels/routed_u32.metal + create mode 100644 ggml/src/ggml-metal/kernels/routed_u32_r4.metal + create mode 100644 tests/test-backend-portable-routed.h + create mode 100644 tests/test-metal-routed-u32.cpp + +diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt +index bcd43abd6..462ff258b 100644 +--- a/ggml/src/ggml-metal/CMakeLists.txt ++++ b/ggml/src/ggml-metal/CMakeLists.txt +@@ -30,6 +30,7 @@ set(METALLIB_COMMON "${CMAKE_CURRENT_SOURCE_DIR}/../ggml-common.h") + set(METALLIB_KERNELS_COMMON "${CMAKE_CURRENT_SOURCE_DIR}/kernels/common.h") + set(METALLIB_KERNELS_DEQUANTIZE "${CMAKE_CURRENT_SOURCE_DIR}/kernels/dequantize.h") + set(METALLIB_KERNELS_QUANTIZE "${CMAKE_CURRENT_SOURCE_DIR}/kernels/quantize.h") ++set(METALLIB_KERNELS_MUL_MV_Q_N "${CMAKE_CURRENT_SOURCE_DIR}/kernels/mul_mv_q_n.h") + set(METALLIB_KERNELS_FA_COMMON "${CMAKE_CURRENT_SOURCE_DIR}/kernels/fa_common.metal") + set(METALLIB_KERNELS_FA_VEC_COMMON "${CMAKE_CURRENT_SOURCE_DIR}/kernels/fa_vec_common.metal") + set(METALLIB_KERNELS_FA_SHARED +@@ -56,6 +57,8 @@ set(METALLIB_KERNEL_SOURCES + kernels/fa_vec_q5_1.metal + kernels/fa_vec_q8_0.metal + kernels/mul_mv.metal ++ kernels/routed_u32.metal ++ kernels/routed_u32_r4.metal + kernels/mul_mv_mma.metal + kernels/mul_mm.metal + kernels/mul_mm_tensor.metal +@@ -116,12 +119,17 @@ if (GGML_METAL_EMBED_LIBRARY) + list(APPEND HEADERS_FOR_SRC ${METALLIB_KERNELS_FA_VEC_COMMON}) + endif() + ++ file(STRINGS ${SRC} _has_mv_q_n REGEX "#include \"mul_mv_q_n\\.h\"") ++ if(_has_mv_q_n) ++ list(APPEND HEADERS_FOR_SRC ${METALLIB_KERNELS_MUL_MV_Q_N}) ++ endif() ++ + add_custom_command( + OUTPUT "${ASM}" + # Step 1: concatenate shared headers + this kernel source + COMMAND cat ${HEADERS_FOR_SRC} ${SRC} > "${EMBED}.tmp1" + # Step 2: remove internal #include and #pragma once +- COMMAND sed -e "/\#include \"common.h\"/d" -e "/\#include \"dequantize.h\"/d" -e "/\#include \"quantize.h\"/d" -e "/\#include \"fa_common.metal\"/d" -e "/\#include \"fa_vec_common.metal\"/d" -e "/\#pragma once/d" < "${EMBED}.tmp1" > "${EMBED}.tmp2" ++ COMMAND sed -e "/\#include \"mul_mv_q_n.h\"/d" -e "/\#include \"common.h\"/d" -e "/\#include \"dequantize.h\"/d" -e "/\#include \"quantize.h\"/d" -e "/\#include \"fa_common.metal\"/d" -e "/\#include \"fa_vec_common.metal\"/d" -e "/\#pragma once/d" < "${EMBED}.tmp1" > "${EMBED}.tmp2" + # Step 3: inline ggml-common.h (replacing __embed_ggml-common.h__ sentinel) + COMMAND sed -e "/__embed_ggml-common.h__/r ${METALLIB_COMMON}" -e "/__embed_ggml-common.h__/d" < "${EMBED}.tmp2" > "${EMBED}.tmp3" + # Step 4: inline ggml-metal-impl.h +@@ -155,6 +163,7 @@ else() + configure_file(kernels/common.h ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/common.h COPYONLY) + configure_file(kernels/dequantize.h ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/dequantize.h COPYONLY) + configure_file(kernels/quantize.h ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/quantize.h COPYONLY) ++ configure_file(kernels/mul_mv_q_n.h ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mv_q_n.h COPYONLY) + foreach(hdr ${METALLIB_KERNELS_FA_SHARED}) + get_filename_component(hdr_name ${hdr} NAME) + configure_file(${hdr} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/${hdr_name} COPYONLY) +@@ -216,7 +225,7 @@ else() + add_custom_command( + OUTPUT ${AIR} + COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS} -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${src} -o ${AIR} +- DEPENDS ${src} ${METALLIB_KERNELS_FA_SHARED} kernels/common.h kernels/dequantize.h kernels/quantize.h ${METALLIB_COMMON} ggml-metal-impl.h ++ DEPENDS ${src} ${METALLIB_KERNELS_MUL_MV_Q_N} ${METALLIB_KERNELS_FA_SHARED} kernels/common.h kernels/dequantize.h kernels/quantize.h ${METALLIB_COMMON} ggml-metal-impl.h + COMMENT "Compiling ${src}" + VERBATIM + ) +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index e4a467436..f9bac503d 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -3,6 +3,10 @@ + + #include "ggml-metal-impl.h" + #include "ggml-metal-tuning.h" ++#include "ggml-metal-routed-tuning.h" ++#include "ggml-metal-routed-offsets.h" ++#include ++#include + + #include "ggml-impl.h" + +@@ -1588,10 +1592,34 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_m + } + }; + ++ const auto * props = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); ++ const int tuned_rows = ggml_metal_routed_tuning::rows( ++ props->device_id, props->use_shared_buffers, tsrc0, ne00, ne01, op->src[2]->ne[1], nsg, nr0, op->src[2]->ne[0]); ++ if (tuned_rows != nr0) { ++ nr0 = tuned_rows; ++ suffix = tsrc0 == GGML_TYPE_Q4_K ? "_r4" : tsrc0 == GGML_TYPE_Q4_1 ? "_r8" : "_r2"; ++ } ++ const char * enable_u32 = std::getenv("GGML_METAL_ROUTED_U32"); ++ const bool use_u32 = ggml_metal_routed_offsets::requested_r8(enable_u32, props->device_id) && ++ ggml_metal_routed_offsets::eligible(op, props->device_id, props->use_shared_buffers, nr0, nsg); ++ const char * enable_r4 = std::getenv("GGML_METAL_ROUTED_U32_R4"); ++ const bool use_r4 = ggml_metal_routed_offsets::requested(enable_r4, props->device_id) && ++ ggml_metal_routed_offsets::eligible_r4(op, props->device_id, props->use_shared_buffers, nr0, nsg); ++ const char * fallback_suffix = suffix; ++ ++ if (use_u32) suffix = "_r8_u32"; ++ if (use_r4) suffix = "_r4_u32"; + snprintf(base, 256, "kernel_mul_mv_id_%s_%s%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix); + snprintf(name, 256, "%s_nsg=%d_split=%d", base, nsg, split); + + ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); ++ // Availability is checked only on a cold candidate-pipeline lookup. An ++ // old combined or override library keeps its established vector kernel. ++ if (!res.pipeline && (use_u32 || use_r4) && !ggml_metal_library_has_function(lib, base)) { ++ snprintf(base, 256, "kernel_mul_mv_id_%s_%s%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1), fallback_suffix); ++ snprintf(name, 256, "%s_nsg=%d_split=%d", base, nsg, split); ++ res = ggml_metal_library_get_pipeline(lib, name); ++ } + if (!res.pipeline) { + ggml_metal_cv_t cv = ggml_metal_cv_init(); + +diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h +index 492aafd34..282ff0def 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.h ++++ b/ggml/src/ggml-metal/ggml-metal-device.h +@@ -104,6 +104,7 @@ ggml_metal_library_t ggml_metal_library_init_from_source(ggml_metal_device_t dev + void ggml_metal_library_free(ggml_metal_library_t lib); + + ggml_metal_device_t ggml_metal_library_get_device(ggml_metal_library_t lib); ++bool ggml_metal_library_has_function(ggml_metal_library_t lib, const char * name); + + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline (ggml_metal_library_t lib, const char * name); + struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_metal_library_t lib, const char * base, const char * name, ggml_metal_cv_t cv); +diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m +index 52fe84b04..d4ce6a5d8 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.m ++++ b/ggml/src/ggml-metal/ggml-metal-device.m +@@ -131,6 +131,8 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi + X(FA_VEC_Q5_1, fa_vec_q5_1) \ + X(FA_VEC_Q8_0, fa_vec_q8_0) \ + X(MUL_MV, mul_mv) \ ++ X(ROUTED_U32, routed_u32) \ ++ X(ROUTED_U32_R4, routed_u32_r4) \ + X(MUL_MV_MMA, mul_mv_mma) \ + X(MUL_MM, mul_mm) \ + X(MUL_MM_TENSOR, mul_mm_tensor) \ +@@ -182,6 +184,9 @@ struct ggml_metal_library { + // kernels from a second metallib, resolved ahead of the combined library + NSSet * override_fns; + ++ // Immutable library contents; cache both positive and negative cold lookups. ++ NSMutableDictionary * available_fns; ++ + ggml_metal_device_t dev; + ggml_metal_pipelines_t pipelines; // cache of compiled pipelines + +@@ -851,6 +856,10 @@ void ggml_metal_library_free(ggml_metal_library_t lib) { + [lib->override_fns release]; + } + ++ if (lib->available_fns) { ++ [lib->available_fns release]; ++ } ++ + ggml_metal_pipelines_free(lib->pipelines); + + if (lib->pso_archive) { +@@ -870,6 +879,27 @@ ggml_metal_device_t ggml_metal_library_get_device(ggml_metal_library_t lib) { + return lib->dev; + } + ++bool ggml_metal_library_has_function(ggml_metal_library_t lib, const char * name) { ++ [lib->lock lock]; ++ if (!lib->available_fns) lib->available_fns = [NSMutableDictionary new]; ++ NSString * function_name = [NSString stringWithUTF8String:name]; ++ NSNumber * cached = lib->available_fns[function_name]; ++ if (cached) { ++ const bool found = [cached boolValue]; ++ [lib->lock unlock]; ++ return found; ++ } ++ bool found = lib->override_fns && [lib->override_fns containsObject:function_name]; ++ if (!found && lib->single_library) { ++ found = [[lib->objs[0] functionNames] containsObject:function_name]; ++ } else if (!found) { ++ found = lib->fn_to_lib[function_name] != nil; ++ } ++ lib->available_fns[function_name] = @(found); ++ [lib->lock unlock]; ++ return found; ++} ++ + struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline(ggml_metal_library_t lib, const char * name) { + [lib->lock lock]; + +diff --git a/ggml/src/ggml-metal/ggml-metal-routed-offsets.h b/ggml/src/ggml-metal/ggml-metal-routed-offsets.h +new file mode 100644 +index 000000000..30fc69a5d +--- /dev/null ++++ b/ggml/src/ggml-metal/ggml-metal-routed-offsets.h +@@ -0,0 +1,70 @@ ++#pragma once ++ ++#include "ggml-metal-device.h" ++#include ++#include ++ ++namespace ggml_metal_routed_offsets { ++ ++// M1 has complete repeated serving qualification. Other admitted chips retain ++// the original path by default; the private flag permits explicit diagnostics. ++inline bool requested(const char * value, ggml_metal_device_id device) { ++ return value ? std::strcmp(value, "1") == 0 : device == GGML_METAL_DEVICE_M1_ULTRA; ++} ++ ++// R8 has separate qualification; enabling it does not enable the R4 diagnostic. ++inline bool requested_r8(const char * value, ggml_metal_device_id device) { ++ return value ? std::strcmp(value, "1") == 0 : ++ device == GGML_METAL_DEVICE_M1_ULTRA || device == GGML_METAL_DEVICE_M5_MAX; ++} ++ ++// Inclusive bound on every byte touched relative to the tensor's bound base. ++// Handle quantized block strides and padded ID views without size_t overflow. ++inline bool fits_u32(const ggml_tensor * tensor) { ++ if (!tensor) return false; ++ uint64_t bytes = ggml_type_size(tensor->type); ++ const uint64_t limit = UINT32_MAX; ++ for (int dim = 0; dim < GGML_MAX_DIMS; ++dim) { ++ const int64_t blocks = dim == 0 ? ggml_blck_size(tensor->type) : 1; ++ if (tensor->ne[dim] <= 0 || tensor->ne[dim] % blocks != 0) return false; ++ const uint64_t steps = uint64_t(tensor->ne[dim]/blocks - 1); ++ if (bytes > limit || (steps && tensor->nb[dim] > (limit - bytes)/steps)) return false; ++ bytes += steps*tensor->nb[dim]; ++ } ++ return bytes <= limit; ++} ++ ++inline bool eligible_geometry(const ggml_tensor * op, ggml_metal_device_id device, ++ bool shared, int rows, int simdgroups, int required_rows, ++ int64_t min_tokens, int64_t max_tokens) { ++ if (!op || op->op != GGML_OP_MUL_MAT_ID || !shared || rows != required_rows || simdgroups != 2) return false; ++ if (device != GGML_METAL_DEVICE_M1_ULTRA && device != GGML_METAL_DEVICE_M4 && ++ device != GGML_METAL_DEVICE_M5_MAX) return false; ++ const auto * weights = op->src[0]; ++ const auto * input = op->src[1]; ++ const auto * ids = op->src[2]; ++ if (!weights || !input || !ids || weights->type != GGML_TYPE_Q4_1 || ++ input->type != GGML_TYPE_F32 || ids->type != GGML_TYPE_I32 || op->type != GGML_TYPE_F32) return false; ++ const int64_t inner = weights->ne[0], output = weights->ne[1]; ++ if (!((inner == 512 && output == 2048) || (inner == 2048 && output == 512))) return false; ++ if (weights->ne[2] != 128 && weights->ne[2] != 256) return false; ++ if (weights->ne[3] != 1 || input->ne[3] != 1 || op->ne[3] != 1 || ++ ids->ne[2] != 1 || ids->ne[3] != 1) return false; ++ if (ids->ne[0] != 8 || ids->ne[1] < min_tokens || ids->ne[1] > max_tokens || ids->nb[0] != sizeof(int32_t) || ++ input->ne[0] != inner || (input->ne[1] != 1 && input->ne[1] != 8) || ++ input->ne[2] != ids->ne[1] || op->ne[0] != output || op->ne[1] != 8 || op->ne[2] != ids->ne[1]) return false; ++ if (!ggml_is_contiguous(weights) || !ggml_is_contiguous(input) || !ggml_is_contiguous(op)) return false; ++ return fits_u32(weights) && fits_u32(input) && fits_u32(ids) && fits_u32(op); ++} ++ ++inline bool eligible(const ggml_tensor * op, ggml_metal_device_id device, ++ bool shared, int rows, int simdgroups) { ++ return eligible_geometry(op, device, shared, rows, simdgroups, 8, 3, 16); ++} ++ ++inline bool eligible_r4(const ggml_tensor * op, ggml_metal_device_id device, ++ bool shared, int rows, int simdgroups) { ++ return eligible_geometry(op, device, shared, rows, simdgroups, 4, 1, 16); ++} ++ ++} // namespace ggml_metal_routed_offsets +diff --git a/ggml/src/ggml-metal/ggml-metal-routed-tuning.h b/ggml/src/ggml-metal/ggml-metal-routed-tuning.h +new file mode 100644 +index 000000000..d65eb01aa +--- /dev/null ++++ b/ggml/src/ggml-metal/ggml-metal-routed-tuning.h +@@ -0,0 +1,27 @@ ++#pragma once ++ ++#include "ggml-metal-device.h" ++ ++namespace ggml_metal_routed_tuning { ++ ++// Reuse the per-lane activation registers across more output rows. Preserve ++// complete SIMDgroup row tiles: the vector bodies load every unrolled row. ++inline int rows(ggml_metal_device_id device, bool shared_buffers, ggml_type type, int64_t inner, ++ int64_t output, int64_t tokens, int nsg, int fallback, int64_t selections = 8) { ++ // Portable screen supports this down-projection shape only. Gate/up ++ // remains faster at the existing width on these two measured devices. ++ if ((device == GGML_METAL_DEVICE_M1_ULTRA || device == GGML_METAL_DEVICE_M4) && ++ shared_buffers && type == GGML_TYPE_Q4_1 && inner == 512 && output == 2048 && ++ tokens == 16 && selections == 8 && nsg == 2) { ++ return 8; ++ } ++ if (device != GGML_METAL_DEVICE_M5_MAX || !shared_buffers || tokens < 3 || inner < 512 || inner > 4096 || ++ output < 512 || tokens > 31 || nsg <= 0) { ++ return fallback; ++ } ++ const int candidate = type == GGML_TYPE_Q4_K ? 4 : type == GGML_TYPE_Q5_K ? 2 : ++ type == GGML_TYPE_Q4_1 ? 8 : fallback; ++ return output % (candidate * nsg) == 0 ? candidate : fallback; ++} ++ ++} // namespace ggml_metal_routed_tuning +diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal +index 08873502e..c50e197e0 100644 +--- a/ggml/src/ggml-metal/kernels/mul_mv.metal ++++ b/ggml/src/ggml-metal/kernels/mul_mv.metal +@@ -1,171 +1,5 @@ + #include "common.h" + #include "dequantize.h" +-// Q1_0 dot product: dot = d * (2 * Σ(yl[i] where bit=1) - sumy) +-inline float block_q_n_dot_y(device const block_q1_0 * qb_curr, float sumy, thread float * yl, int il) { +- device const uint8_t * qs = qb_curr->qs + il / 8; +- const uint8_t b0 = qs[0]; +- const uint8_t b1 = qs[1]; +- +- float acc = 0.0f; +- +- acc += select(0.0f, yl[ 0], bool(b0 & 0x01)); +- acc += select(0.0f, yl[ 1], bool(b0 & 0x02)); +- acc += select(0.0f, yl[ 2], bool(b0 & 0x04)); +- acc += select(0.0f, yl[ 3], bool(b0 & 0x08)); +- acc += select(0.0f, yl[ 4], bool(b0 & 0x10)); +- acc += select(0.0f, yl[ 5], bool(b0 & 0x20)); +- acc += select(0.0f, yl[ 6], bool(b0 & 0x40)); +- acc += select(0.0f, yl[ 7], bool(b0 & 0x80)); +- +- acc += select(0.0f, yl[ 8], bool(b1 & 0x01)); +- acc += select(0.0f, yl[ 9], bool(b1 & 0x02)); +- acc += select(0.0f, yl[10], bool(b1 & 0x04)); +- acc += select(0.0f, yl[11], bool(b1 & 0x08)); +- acc += select(0.0f, yl[12], bool(b1 & 0x10)); +- acc += select(0.0f, yl[13], bool(b1 & 0x20)); +- acc += select(0.0f, yl[14], bool(b1 & 0x40)); +- acc += select(0.0f, yl[15], bool(b1 & 0x80)); +- +- return qb_curr->d * (2.0f * acc - sumy); +-} +- +-// Q2_0 dot: d * (sum_lo(y) + 2*sum_hi(y) - sumy) via per-bit conditional adds +-inline float block_q_n_dot_y(device const block_q2_0 * qb_curr, float sumy, thread float * yl, int il) { +- device const uint8_t * qs = qb_curr->qs + (il / 4); +- const uint8_t b0 = qs[0]; +- const uint8_t b1 = qs[1]; +- const uint8_t b2 = qs[2]; +- const uint8_t b3 = qs[3]; +- +- // Accumulate where low bit is set (bits 0,2,4,6 of each byte) +- float acc_lo = 0.0f; +- acc_lo += select(0.0f, yl[ 0], bool(b0 & 0x01)); +- acc_lo += select(0.0f, yl[ 1], bool(b0 & 0x04)); +- acc_lo += select(0.0f, yl[ 2], bool(b0 & 0x10)); +- acc_lo += select(0.0f, yl[ 3], bool(b0 & 0x40)); +- acc_lo += select(0.0f, yl[ 4], bool(b1 & 0x01)); +- acc_lo += select(0.0f, yl[ 5], bool(b1 & 0x04)); +- acc_lo += select(0.0f, yl[ 6], bool(b1 & 0x10)); +- acc_lo += select(0.0f, yl[ 7], bool(b1 & 0x40)); +- acc_lo += select(0.0f, yl[ 8], bool(b2 & 0x01)); +- acc_lo += select(0.0f, yl[ 9], bool(b2 & 0x04)); +- acc_lo += select(0.0f, yl[10], bool(b2 & 0x10)); +- acc_lo += select(0.0f, yl[11], bool(b2 & 0x40)); +- acc_lo += select(0.0f, yl[12], bool(b3 & 0x01)); +- acc_lo += select(0.0f, yl[13], bool(b3 & 0x04)); +- acc_lo += select(0.0f, yl[14], bool(b3 & 0x10)); +- acc_lo += select(0.0f, yl[15], bool(b3 & 0x40)); +- +- // Accumulate where high bit is set (bits 1,3,5,7 of each byte) +- float acc_hi = 0.0f; +- acc_hi += select(0.0f, yl[ 0], bool(b0 & 0x02)); +- acc_hi += select(0.0f, yl[ 1], bool(b0 & 0x08)); +- acc_hi += select(0.0f, yl[ 2], bool(b0 & 0x20)); +- acc_hi += select(0.0f, yl[ 3], bool(b0 & 0x80)); +- acc_hi += select(0.0f, yl[ 4], bool(b1 & 0x02)); +- acc_hi += select(0.0f, yl[ 5], bool(b1 & 0x08)); +- acc_hi += select(0.0f, yl[ 6], bool(b1 & 0x20)); +- acc_hi += select(0.0f, yl[ 7], bool(b1 & 0x80)); +- acc_hi += select(0.0f, yl[ 8], bool(b2 & 0x02)); +- acc_hi += select(0.0f, yl[ 9], bool(b2 & 0x08)); +- acc_hi += select(0.0f, yl[10], bool(b2 & 0x20)); +- acc_hi += select(0.0f, yl[11], bool(b2 & 0x80)); +- acc_hi += select(0.0f, yl[12], bool(b3 & 0x02)); +- acc_hi += select(0.0f, yl[13], bool(b3 & 0x08)); +- acc_hi += select(0.0f, yl[14], bool(b3 & 0x20)); +- acc_hi += select(0.0f, yl[15], bool(b3 & 0x80)); +- +- return qb_curr->d * (acc_lo + 2.0f * acc_hi - sumy); +-} +- +-// function for calculate inner product between half a q4_0 block and 16 floats (yl), sumy is SUM(yl[i]) +-// il indicates where the q4 quants begin (0 or QK4_0/4) +-// we assume that the yl's have been multiplied with the appropriate scale factor +-// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) +-inline float block_q_n_dot_y(device const block_q4_0 * qb_curr, float sumy, thread float * yl, int il) { +- float d = qb_curr->d; +- +- float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; +- +- device const uint16_t * qs = ((device const uint16_t *) qb_curr + 1 + il/2); +- +- for (int i = 0; i < 8; i += 2) { +- acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F); +- acc[1] += yl[i + 1] * (qs[i / 2] & 0x0F00); +- acc[2] += yl[i + 8] * (qs[i / 2] & 0x00F0); +- acc[3] += yl[i + 9] * (qs[i / 2] & 0xF000); +- } +- +- return d * (sumy * -8.f + acc[0] + acc[1] + acc[2] + acc[3]); +-} +- +-// function for calculate inner product between half a q4_1 block and 16 floats (yl), sumy is SUM(yl[i]) +-// il indicates where the q4 quants begin (0 or QK4_0/4) +-// we assume that the yl's have been multiplied with the appropriate scale factor +-// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) +-inline float block_q_n_dot_y(device const block_q4_1 * qb_curr, float sumy, thread float * yl, int il) { +- float d = qb_curr->d; +- float m = qb_curr->m; +- +- float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; +- +- device const uint16_t * qs = ((device const uint16_t *) qb_curr + 2 + il/2); +- +- for (int i = 0; i < 8; i+=2) { +- acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F); +- acc[1] += yl[i + 1] * (qs[i / 2] & 0x0F00); +- acc[2] += yl[i + 8] * (qs[i / 2] & 0x00F0); +- acc[3] += yl[i + 9] * (qs[i / 2] & 0xF000); +- } +- +- return d * (acc[0] + acc[1] + acc[2] + acc[3]) + sumy * m; +-} +- +-// function for calculate inner product between half a q5_0 block and 16 floats (yl), sumy is SUM(yl[i]) +-// il indicates where the q5 quants begin (0 or QK5_0/4) +-// we assume that the yl's have been multiplied with the appropriate scale factor +-// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) +-inline float block_q_n_dot_y(device const block_q5_0 * qb_curr, float sumy, thread float * yl, int il) { +- float d = qb_curr->d; +- +- float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; +- +- device const uint16_t * qs = ((device const uint16_t *)qb_curr + 3 + il/2); +- const uint32_t qh = *((device const uint32_t *)qb_curr->qh); +- +- for (int i = 0; i < 8; i+=2) { +- acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)); +- acc[1] += yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); +- acc[2] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)); +- acc[3] += yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); +- } +- +- return d * (sumy * -16.f + acc[0] + acc[1] + acc[2] + acc[3]); +-} +- +-// function for calculate inner product between half a q5_1 block and 16 floats (yl), sumy is SUM(yl[i]) +-// il indicates where the q5 quants begin (0 or QK5_1/4) +-// we assume that the yl's have been multiplied with the appropriate scale factor +-// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) +-inline float block_q_n_dot_y(device const block_q5_1 * qb_curr, float sumy, thread float * yl, int il) { +- float d = qb_curr->d; +- float m = qb_curr->m; +- +- float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; +- +- device const uint16_t * qs = ((device const uint16_t *)qb_curr + 4 + il/2); +- const uint32_t qh = *((device const uint32_t *)qb_curr->qh); +- +- for (int i = 0; i < 8; i+=2) { +- acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)); +- acc[1] += yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); +- acc[2] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)); +- acc[3] += yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); +- } +- +- return d * (acc[0] + acc[1] + acc[2] + acc[3]) + sumy * m; +-} +- + template + static inline void helper_mv_reduce_and_write( + device float * dst_f32, +@@ -208,100 +42,7 @@ static inline void helper_mv_reduce_and_write( + } + } + +-constant short FC_mul_mv_nsg [[function_constant(FC_MUL_MV + 0)]]; +-constant short FC_mul_mv_nxpsg [[function_constant(FC_MUL_MV + 1)]]; +-constant short FC_mul_mv_ne12 [[function_constant(FC_MUL_MV + 2)]]; +-constant short FC_mul_mv_r2 [[function_constant(FC_MUL_MV + 3)]]; +-constant short FC_mul_mv_r3 [[function_constant(FC_MUL_MV + 4)]]; +-constant bool FC_mul_mv_split [[function_constant(FC_MUL_MV + 5)]]; +- +-template +-void mul_vec_q_n_f32_impl( +- args_t args, +- device const char * src0, +- device const char * src1, +- device char * dst, +- threadgroup char * shmem, +- uint3 tgpig, +- ushort tiisg, +- ushort sgitg) { +- const short NSG = FC_mul_mv_nsg; +- +- constexpr short NW = N_SIMDWIDTH; +- constexpr short NQ = 16; +- +- const int nb = args.ne00/QK4_0; +- +- const int r0 = (tgpig.x*NSG + sgitg)*NR0; +- //const int r0 = tgpig.x*NR0; +- const int r1 = tgpig.y; +- const int im = tgpig.z; +- +- const uint i12 = im%FC_mul_mv_ne12; +- const uint i13 = im/FC_mul_mv_ne12; +- +- //const uint64_t offset0 = r0*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03; +- const uint64_t offset1 = r1*args.nb11 + (i12 )*args.nb12 + (i13 )*args.nb13; +- +- //device const block_q_type * x = (device const block_q_type *) (src0 + offset0); +- device const float * y = (device const float *) (src1 + offset1); +- +- // pointers to src0 rows +- device const block_q_type * ax[NR0]; +- FOR_UNROLL (int row = 0; row < NR0; ++row) { +- const uint64_t offset0 = (r0 + row)*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03; +- +- ax[row] = (device const block_q_type *) ((device char *) src0 + offset0); +- } +- +- float sumf[NR0] = {0.f}; +- +- const short ix = (tiisg/(NW/NQ)); +- const short il = (tiisg%(NW/NQ))*8; +- +- //const int ib0 = sgitg*NQ + ix; +- const int ib0 = ix; +- +- float yl[16]; // src1 vector cache +- +- //device const float * yb = y + ix*QK4_0 + il; +- device const float * yb = y + ib0*QK4_0 + il; +- +- // each thread in a SIMD group deals with half a block. +- //for (int ib = ib0; ib < nb; ib += NSG*NQ) { +- for (int ib = ib0; ib < nb; ib += NQ) { +- float sumy[2] = { 0.f, 0.f }; +- +- FOR_UNROLL (short i = 0; i < 8; i += 2) { +- sumy[0] += yb[i + 0] + yb[i + 1]; +- yl[i + 0] = yb[i + 0]; +- yl[i + 1] = yb[i + 1]/256.f; +- +- sumy[1] += yb[i + 16] + yb[i + 17]; +- yl[i + 8] = yb[i + 16]/16.f; +- yl[i + 9] = yb[i + 17]/4096.f; +- } +- +- FOR_UNROLL (short row = 0; row < NR0; row++) { +- sumf[row] += block_q_n_dot_y(ax[row] + ib, sumy[0] + sumy[1], yl, il); +- } +- +- yb += QK4_0 * 16; +- //yb += NSG*NQ*QK4_0; +- } +- +- device float * dst_f32 = (device float *) dst + (uint64_t)im*args.ne0*args.ne1 + (uint64_t)r1*args.ne0; +- +- //helper_mv_reduce_and_write(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem); +- +- for (int row = 0; row < NR0; ++row) { +- const float tot = simd_sum(sumf[row]); +- +- if (tiisg == 0 && r0 + row < args.ne01) { +- dst_f32[r0 + row] = tot; +- } +- } +-} ++#include "mul_mv_q_n.h" + + template + void kernel_mul_mv_q1_0_f32_impl( +@@ -3529,6 +3270,7 @@ template [[host_name("kernel_mul_mv_id_q1_0_f32")]] kernel kernel_mul_mv_id_t + template [[host_name("kernel_mul_mv_id_q2_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q4_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q4_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; ++template [[host_name("kernel_mul_mv_id_q4_1_f32_r8")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + +@@ -3539,6 +3281,8 @@ template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t + template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q4_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q5_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; ++template [[host_name("kernel_mul_mv_id_q4_K_f32_r4")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; ++template [[host_name("kernel_mul_mv_id_q5_K_f32_r2")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_q6_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_iq1_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; + template [[host_name("kernel_mul_mv_id_iq1_m_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; +diff --git a/ggml/src/ggml-metal/kernels/mul_mv_q_n.h b/ggml/src/ggml-metal/kernels/mul_mv_q_n.h +new file mode 100644 +index 000000000..f156d5ca6 +--- /dev/null ++++ b/ggml/src/ggml-metal/kernels/mul_mv_q_n.h +@@ -0,0 +1,262 @@ ++#pragma once ++ ++// Q1_0 dot product: dot = d * (2 * Σ(yl[i] where bit=1) - sumy) ++inline float block_q_n_dot_y(device const block_q1_0 * qb_curr, float sumy, thread float * yl, int il) { ++ device const uint8_t * qs = qb_curr->qs + il / 8; ++ const uint8_t b0 = qs[0]; ++ const uint8_t b1 = qs[1]; ++ ++ float acc = 0.0f; ++ ++ acc += select(0.0f, yl[ 0], bool(b0 & 0x01)); ++ acc += select(0.0f, yl[ 1], bool(b0 & 0x02)); ++ acc += select(0.0f, yl[ 2], bool(b0 & 0x04)); ++ acc += select(0.0f, yl[ 3], bool(b0 & 0x08)); ++ acc += select(0.0f, yl[ 4], bool(b0 & 0x10)); ++ acc += select(0.0f, yl[ 5], bool(b0 & 0x20)); ++ acc += select(0.0f, yl[ 6], bool(b0 & 0x40)); ++ acc += select(0.0f, yl[ 7], bool(b0 & 0x80)); ++ ++ acc += select(0.0f, yl[ 8], bool(b1 & 0x01)); ++ acc += select(0.0f, yl[ 9], bool(b1 & 0x02)); ++ acc += select(0.0f, yl[10], bool(b1 & 0x04)); ++ acc += select(0.0f, yl[11], bool(b1 & 0x08)); ++ acc += select(0.0f, yl[12], bool(b1 & 0x10)); ++ acc += select(0.0f, yl[13], bool(b1 & 0x20)); ++ acc += select(0.0f, yl[14], bool(b1 & 0x40)); ++ acc += select(0.0f, yl[15], bool(b1 & 0x80)); ++ ++ return qb_curr->d * (2.0f * acc - sumy); ++} ++ ++// Q2_0 dot: d * (sum_lo(y) + 2*sum_hi(y) - sumy) via per-bit conditional adds ++inline float block_q_n_dot_y(device const block_q2_0 * qb_curr, float sumy, thread float * yl, int il) { ++ device const uint8_t * qs = qb_curr->qs + (il / 4); ++ const uint8_t b0 = qs[0]; ++ const uint8_t b1 = qs[1]; ++ const uint8_t b2 = qs[2]; ++ const uint8_t b3 = qs[3]; ++ ++ // Accumulate where low bit is set (bits 0,2,4,6 of each byte) ++ float acc_lo = 0.0f; ++ acc_lo += select(0.0f, yl[ 0], bool(b0 & 0x01)); ++ acc_lo += select(0.0f, yl[ 1], bool(b0 & 0x04)); ++ acc_lo += select(0.0f, yl[ 2], bool(b0 & 0x10)); ++ acc_lo += select(0.0f, yl[ 3], bool(b0 & 0x40)); ++ acc_lo += select(0.0f, yl[ 4], bool(b1 & 0x01)); ++ acc_lo += select(0.0f, yl[ 5], bool(b1 & 0x04)); ++ acc_lo += select(0.0f, yl[ 6], bool(b1 & 0x10)); ++ acc_lo += select(0.0f, yl[ 7], bool(b1 & 0x40)); ++ acc_lo += select(0.0f, yl[ 8], bool(b2 & 0x01)); ++ acc_lo += select(0.0f, yl[ 9], bool(b2 & 0x04)); ++ acc_lo += select(0.0f, yl[10], bool(b2 & 0x10)); ++ acc_lo += select(0.0f, yl[11], bool(b2 & 0x40)); ++ acc_lo += select(0.0f, yl[12], bool(b3 & 0x01)); ++ acc_lo += select(0.0f, yl[13], bool(b3 & 0x04)); ++ acc_lo += select(0.0f, yl[14], bool(b3 & 0x10)); ++ acc_lo += select(0.0f, yl[15], bool(b3 & 0x40)); ++ ++ // Accumulate where high bit is set (bits 1,3,5,7 of each byte) ++ float acc_hi = 0.0f; ++ acc_hi += select(0.0f, yl[ 0], bool(b0 & 0x02)); ++ acc_hi += select(0.0f, yl[ 1], bool(b0 & 0x08)); ++ acc_hi += select(0.0f, yl[ 2], bool(b0 & 0x20)); ++ acc_hi += select(0.0f, yl[ 3], bool(b0 & 0x80)); ++ acc_hi += select(0.0f, yl[ 4], bool(b1 & 0x02)); ++ acc_hi += select(0.0f, yl[ 5], bool(b1 & 0x08)); ++ acc_hi += select(0.0f, yl[ 6], bool(b1 & 0x20)); ++ acc_hi += select(0.0f, yl[ 7], bool(b1 & 0x80)); ++ acc_hi += select(0.0f, yl[ 8], bool(b2 & 0x02)); ++ acc_hi += select(0.0f, yl[ 9], bool(b2 & 0x08)); ++ acc_hi += select(0.0f, yl[10], bool(b2 & 0x20)); ++ acc_hi += select(0.0f, yl[11], bool(b2 & 0x80)); ++ acc_hi += select(0.0f, yl[12], bool(b3 & 0x02)); ++ acc_hi += select(0.0f, yl[13], bool(b3 & 0x08)); ++ acc_hi += select(0.0f, yl[14], bool(b3 & 0x20)); ++ acc_hi += select(0.0f, yl[15], bool(b3 & 0x80)); ++ ++ return qb_curr->d * (acc_lo + 2.0f * acc_hi - sumy); ++} ++ ++// function for calculate inner product between half a q4_0 block and 16 floats (yl), sumy is SUM(yl[i]) ++// il indicates where the q4 quants begin (0 or QK4_0/4) ++// we assume that the yl's have been multiplied with the appropriate scale factor ++// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) ++inline float block_q_n_dot_y(device const block_q4_0 * qb_curr, float sumy, thread float * yl, int il) { ++ float d = qb_curr->d; ++ ++ float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ++ ++ device const uint16_t * qs = ((device const uint16_t *) qb_curr + 1 + il/2); ++ ++ for (int i = 0; i < 8; i += 2) { ++ acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F); ++ acc[1] += yl[i + 1] * (qs[i / 2] & 0x0F00); ++ acc[2] += yl[i + 8] * (qs[i / 2] & 0x00F0); ++ acc[3] += yl[i + 9] * (qs[i / 2] & 0xF000); ++ } ++ ++ return d * (sumy * -8.f + acc[0] + acc[1] + acc[2] + acc[3]); ++} ++ ++// function for calculate inner product between half a q4_1 block and 16 floats (yl), sumy is SUM(yl[i]) ++// il indicates where the q4 quants begin (0 or QK4_0/4) ++// we assume that the yl's have been multiplied with the appropriate scale factor ++// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) ++inline float block_q_n_dot_y(device const block_q4_1 * qb_curr, float sumy, thread float * yl, int il) { ++ float d = qb_curr->d; ++ float m = qb_curr->m; ++ ++ float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ++ ++ device const uint16_t * qs = ((device const uint16_t *) qb_curr + 2 + il/2); ++ ++ for (int i = 0; i < 8; i+=2) { ++ acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F); ++ acc[1] += yl[i + 1] * (qs[i / 2] & 0x0F00); ++ acc[2] += yl[i + 8] * (qs[i / 2] & 0x00F0); ++ acc[3] += yl[i + 9] * (qs[i / 2] & 0xF000); ++ } ++ ++ return d * (acc[0] + acc[1] + acc[2] + acc[3]) + sumy * m; ++} ++ ++// function for calculate inner product between half a q5_0 block and 16 floats (yl), sumy is SUM(yl[i]) ++// il indicates where the q5 quants begin (0 or QK5_0/4) ++// we assume that the yl's have been multiplied with the appropriate scale factor ++// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) ++inline float block_q_n_dot_y(device const block_q5_0 * qb_curr, float sumy, thread float * yl, int il) { ++ float d = qb_curr->d; ++ ++ float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ++ ++ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 3 + il/2); ++ const uint32_t qh = *((device const uint32_t *)qb_curr->qh); ++ ++ for (int i = 0; i < 8; i+=2) { ++ acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)); ++ acc[1] += yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); ++ acc[2] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)); ++ acc[3] += yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); ++ } ++ ++ return d * (sumy * -16.f + acc[0] + acc[1] + acc[2] + acc[3]); ++} ++ ++// function for calculate inner product between half a q5_1 block and 16 floats (yl), sumy is SUM(yl[i]) ++// il indicates where the q5 quants begin (0 or QK5_1/4) ++// we assume that the yl's have been multiplied with the appropriate scale factor ++// that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) ++inline float block_q_n_dot_y(device const block_q5_1 * qb_curr, float sumy, thread float * yl, int il) { ++ float d = qb_curr->d; ++ float m = qb_curr->m; ++ ++ float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; ++ ++ device const uint16_t * qs = ((device const uint16_t *)qb_curr + 4 + il/2); ++ const uint32_t qh = *((device const uint32_t *)qb_curr->qh); ++ ++ for (int i = 0; i < 8; i+=2) { ++ acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)); ++ acc[1] += yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); ++ acc[2] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)); ++ acc[3] += yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); ++ } ++ ++ return d * (acc[0] + acc[1] + acc[2] + acc[3]) + sumy * m; ++} ++ ++constant short FC_mul_mv_nsg [[function_constant(FC_MUL_MV + 0)]]; ++constant short FC_mul_mv_nxpsg [[function_constant(FC_MUL_MV + 1)]]; ++constant short FC_mul_mv_ne12 [[function_constant(FC_MUL_MV + 2)]]; ++constant short FC_mul_mv_r2 [[function_constant(FC_MUL_MV + 3)]]; ++constant short FC_mul_mv_r3 [[function_constant(FC_MUL_MV + 4)]]; ++constant bool FC_mul_mv_split [[function_constant(FC_MUL_MV + 5)]]; ++ ++template ++void mul_vec_q_n_f32_impl( ++ args_t args, ++ device const char * src0, ++ device const char * src1, ++ device char * dst, ++ threadgroup char * shmem, ++ uint3 tgpig, ++ ushort tiisg, ++ ushort sgitg) { ++ const short NSG = FC_mul_mv_nsg; ++ ++ constexpr short NW = N_SIMDWIDTH; ++ constexpr short NQ = 16; ++ ++ const int nb = args.ne00/QK4_0; ++ ++ const int r0 = (tgpig.x*NSG + sgitg)*NR0; ++ //const int r0 = tgpig.x*NR0; ++ const int r1 = tgpig.y; ++ const int im = tgpig.z; ++ ++ const uint i12 = im%FC_mul_mv_ne12; ++ const uint i13 = im/FC_mul_mv_ne12; ++ ++ //const uint64_t offset0 = r0*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03; ++ const offset_t offset1 = offset_t(r1)*offset_t(args.nb11) + offset_t(i12)*offset_t(args.nb12) + offset_t(i13)*offset_t(args.nb13); ++ ++ //device const block_q_type * x = (device const block_q_type *) (src0 + offset0); ++ device const float * y = (device const float *) (src1 + offset1); ++ ++ // pointers to src0 rows ++ device const block_q_type * ax[NR0]; ++ FOR_UNROLL (int row = 0; row < NR0; ++row) { ++ const offset_t offset0 = offset_t(r0 + row)*offset_t(args.nb01) + offset_t(i12/FC_mul_mv_r2)*offset_t(args.nb02) + offset_t(i13/FC_mul_mv_r3)*offset_t(args.nb03); ++ ++ ax[row] = (device const block_q_type *) ((device char *) src0 + offset0); ++ } ++ ++ float sumf[NR0] = {0.f}; ++ ++ const short ix = (tiisg/(NW/NQ)); ++ const short il = (tiisg%(NW/NQ))*8; ++ ++ //const int ib0 = sgitg*NQ + ix; ++ const int ib0 = ix; ++ ++ float yl[16]; // src1 vector cache ++ ++ //device const float * yb = y + ix*QK4_0 + il; ++ device const float * yb = y + ib0*QK4_0 + il; ++ ++ // each thread in a SIMD group deals with half a block. ++ //for (int ib = ib0; ib < nb; ib += NSG*NQ) { ++ for (int ib = ib0; ib < nb; ib += NQ) { ++ float sumy[2] = { 0.f, 0.f }; ++ ++ FOR_UNROLL (short i = 0; i < 8; i += 2) { ++ sumy[0] += yb[i + 0] + yb[i + 1]; ++ yl[i + 0] = yb[i + 0]; ++ yl[i + 1] = yb[i + 1]/256.f; ++ ++ sumy[1] += yb[i + 16] + yb[i + 17]; ++ yl[i + 8] = yb[i + 16]/16.f; ++ yl[i + 9] = yb[i + 17]/4096.f; ++ } ++ ++ FOR_UNROLL (short row = 0; row < NR0; row++) { ++ sumf[row] += block_q_n_dot_y(ax[row] + ib, sumy[0] + sumy[1], yl, il); ++ } ++ ++ yb += QK4_0 * 16; ++ //yb += NSG*NQ*QK4_0; ++ } ++ ++ device float * dst_f32 = (device float *) dst + (uint64_t)im*args.ne0*args.ne1 + (uint64_t)r1*args.ne0; ++ ++ //helper_mv_reduce_and_write(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem); ++ ++ for (int row = 0; row < NR0; ++row) { ++ const float tot = simd_sum(sumf[row]); ++ ++ if (tiisg == 0 && r0 + row < args.ne01) { ++ dst_f32[r0 + row] = tot; ++ } ++ } ++} +diff --git a/ggml/src/ggml-metal/kernels/routed_u32.metal b/ggml/src/ggml-metal/kernels/routed_u32.metal +new file mode 100644 +index 000000000..182e21147 +--- /dev/null ++++ b/ggml/src/ggml-metal/kernels/routed_u32.metal +@@ -0,0 +1,75 @@ ++#include "common.h" ++#include "dequantize.h" ++#include "mul_mv_q_n.h" ++ ++kernel void kernel_mul_mv_id_q4_1_f32_r8_u32( ++ constant ggml_metal_kargs_mul_mv_id & args, ++ device const char * src0s, ++ device const char * src1, ++ device char * dst, ++ device const char * ids, ++ threadgroup char * shmem [[threadgroup(0)]], ++ uint3 tgpig[[threadgroup_position_in_grid]], ++ ushort tiitg[[thread_index_in_threadgroup]], ++ ushort tiisg[[thread_index_in_simdgroup]], ++ ushort sgitg[[simdgroup_index_in_threadgroup]], ++ ushort3 ntg [[threads_per_threadgroup]]) { ++ const int iid1 = tgpig.z/args.nei0; ++ const int idx = tgpig.z%args.nei0; ++ ++ tgpig.z = 0; ++ ++ const int32_t i02 = ((device const int32_t *) (ids + iid1*args.nbi1))[idx]; ++ ++ const uint i11 = idx % args.ne11; ++ const uint i12 = iid1; ++ ++ const uint i1 = idx; ++ const uint i2 = i12; ++ ++ device char * dst_cur = dst + (i1*uint(args.ne0) + i2*uint(args.ne1)*uint(args.ne0))*uint(sizeof(float)); ++ ++ if (i02 == -1) { ++ device float * dst_f32 = (device float *) dst_cur; ++ const ushort nth = ntg.x*ntg.y*ntg.z; ++ for (int i0 = tiitg; i0 < args.ne0; i0 += nth) { ++ dst_f32[i0] = 0.0f; ++ } ++ return; ++ } ++ ++ device const char * src0_cur = src0s + uint(i02)*uint(args.nb02); ++ device const char * src1_cur = src1 + i11*uint(args.nb11) + i12*uint(args.nb12); ++ ++ ggml_metal_kargs_mul_mv args0 = { ++ /*.ne00 =*/ args.ne00, ++ /*.ne01 =*/ args.ne01, ++ /*.ne02 =*/ 1, // args.ne02, ++ /*.nb00 =*/ args.nb00, ++ /*.nb01 =*/ args.nb01, ++ /*.nb02 =*/ args.nb02, ++ /*.nb03 =*/ args.nb02, // args.ne02 == 1 ++ /*.ne10 =*/ args.ne10, ++ /*.ne11 =*/ 1, // args.ne11, ++ /*.ne12 =*/ 1, // args.ne12, ++ /*.nb10 =*/ args.nb10, ++ /*.nb11 =*/ args.nb11, ++ /*.nb12 =*/ args.nb12, ++ /*.nb13 =*/ args.nb12, // ne12 == 1 ++ /*.ne0 =*/ args.ne0, ++ /*.ne1 =*/ 1, // args.ne1, ++ /*.nr0 =*/ args.nr0, ++ /*.r2 =*/ 1, ++ /*.r3 =*/ 1, ++ }; ++ ++ mul_vec_q_n_f32_impl( ++ args0, ++ /* src0 */ src0_cur, ++ /* src1 */ src1_cur, ++ /* dst */ dst_cur, ++ shmem, ++ tgpig, ++ tiisg, ++ sgitg); ++} +diff --git a/ggml/src/ggml-metal/kernels/routed_u32_r4.metal b/ggml/src/ggml-metal/kernels/routed_u32_r4.metal +new file mode 100644 +index 000000000..739da5659 +--- /dev/null ++++ b/ggml/src/ggml-metal/kernels/routed_u32_r4.metal +@@ -0,0 +1,75 @@ ++#include "common.h" ++#include "dequantize.h" ++#include "mul_mv_q_n.h" ++ ++kernel void kernel_mul_mv_id_q4_1_f32_r4_u32( ++ constant ggml_metal_kargs_mul_mv_id & args, ++ device const char * src0s, ++ device const char * src1, ++ device char * dst, ++ device const char * ids, ++ threadgroup char * shmem [[threadgroup(0)]], ++ uint3 tgpig[[threadgroup_position_in_grid]], ++ ushort tiitg[[thread_index_in_threadgroup]], ++ ushort tiisg[[thread_index_in_simdgroup]], ++ ushort sgitg[[simdgroup_index_in_threadgroup]], ++ ushort3 ntg [[threads_per_threadgroup]]) { ++ const int iid1 = tgpig.z/args.nei0; ++ const int idx = tgpig.z%args.nei0; ++ ++ tgpig.z = 0; ++ ++ const int32_t i02 = ((device const int32_t *) (ids + iid1*args.nbi1))[idx]; ++ ++ const uint i11 = idx % args.ne11; ++ const uint i12 = iid1; ++ ++ const uint i1 = idx; ++ const uint i2 = i12; ++ ++ device char * dst_cur = dst + (i1*uint(args.ne0) + i2*uint(args.ne1)*uint(args.ne0))*uint(sizeof(float)); ++ ++ if (i02 == -1) { ++ device float * dst_f32 = (device float *) dst_cur; ++ const ushort nth = ntg.x*ntg.y*ntg.z; ++ for (int i0 = tiitg; i0 < args.ne0; i0 += nth) { ++ dst_f32[i0] = 0.0f; ++ } ++ return; ++ } ++ ++ device const char * src0_cur = src0s + uint(i02)*uint(args.nb02); ++ device const char * src1_cur = src1 + i11*uint(args.nb11) + i12*uint(args.nb12); ++ ++ ggml_metal_kargs_mul_mv args0 = { ++ /*.ne00 =*/ args.ne00, ++ /*.ne01 =*/ args.ne01, ++ /*.ne02 =*/ 1, // args.ne02, ++ /*.nb00 =*/ args.nb00, ++ /*.nb01 =*/ args.nb01, ++ /*.nb02 =*/ args.nb02, ++ /*.nb03 =*/ args.nb02, // args.ne02 == 1 ++ /*.ne10 =*/ args.ne10, ++ /*.ne11 =*/ 1, // args.ne11, ++ /*.ne12 =*/ 1, // args.ne12, ++ /*.nb10 =*/ args.nb10, ++ /*.nb11 =*/ args.nb11, ++ /*.nb12 =*/ args.nb12, ++ /*.nb13 =*/ args.nb12, // ne12 == 1 ++ /*.ne0 =*/ args.ne0, ++ /*.ne1 =*/ 1, // args.ne1, ++ /*.nr0 =*/ args.nr0, ++ /*.r2 =*/ 1, ++ /*.r3 =*/ 1, ++ }; ++ ++ mul_vec_q_n_f32_impl( ++ args0, ++ /* src0 */ src0_cur, ++ /* src1 */ src1_cur, ++ /* dst */ dst_cur, ++ shmem, ++ tgpig, ++ tiisg, ++ sgitg); ++} +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index 64e6f1cca..d6d3d4533 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -416,6 +416,10 @@ if (NOT LLAMA_SANITIZE_ADDRESS AND NOT GGML_SCHED_NO_REALLOC) + llama_build_and_test(test-opt.cpp LABEL "main behavior backend" LINK ggml) + endif() + if (GGML_METAL AND NOT GGML_BACKEND_DL) ++ # Explicit hardware qualification, outside the default CTest roster. ++ llama_build(test-metal-routed-u32.cpp LINK ggml ggml-metal) ++ llama_test(test-metal-routed-u32 NAME metal_routed_u32_policy LABEL "main behavior backend" ARGS --policy-only) ++ target_include_directories(test-metal-routed-u32 PRIVATE ${PROJECT_SOURCE_DIR}/ggml/src ${PROJECT_SOURCE_DIR}/ggml/src/ggml-metal) + # calls the Metal backend's graph optimizer and fusion table directly + llama_build_and_test(test-metal-graph-optimize.cpp LABEL "main behavior backend" LINK ggml ggml-metal) + target_include_directories(test-metal-graph-optimize PRIVATE ${PROJECT_SOURCE_DIR}/ggml/src ${PROJECT_SOURCE_DIR}/ggml/src/ggml-metal) +diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp +index 3b73bb057..8d70e50af 100644 +--- a/tests/test-backend-ops.cpp ++++ b/tests/test-backend-ops.cpp +@@ -12145,7 +12145,12 @@ static const ggml_type other_types[] = { + #endif + + // Test cases for evaluation: should try to cover edge cases while using small input sizes to keep the runtime low ++#include "test-backend-portable-routed.h" ++ + static std::vector> make_test_cases_eval() { ++ if (std::getenv("SKIPPY_TEST_PORTABLE_R8")) { ++ return make_portable_routed_cases(); ++ } + std::vector> test_cases; + std::default_random_engine rng(0); + +diff --git a/tests/test-backend-portable-routed.h b/tests/test-backend-portable-routed.h +new file mode 100644 +index 000000000..9df3198a1 +--- /dev/null ++++ b/tests/test-backend-portable-routed.h +@@ -0,0 +1,43 @@ ++#pragma once ++ ++// Explicit opt-in native qualification, using the backend suite's actual ++// graph construction, CPU reference, strided views and negative/repeated IDs. ++template ++struct test_portable_routed final : Parent { ++ using Parent::Parent; ++ std::string op_desc(ggml_tensor *) override { return "PORTABLE_ROUTED_REUSE"; } ++}; ++ ++static std::vector> make_portable_routed_cases() { ++ std::vector> cases; ++ for (bool broadcast : {false,true}) { ++ for (bool offset : {false,true}) for (bool masked : {false,true}) { ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, broadcast, 2048, 16, 512, 0, offset, masked)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, broadcast, 2048, 16, 512, 0, offset, masked)); ++ } ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 256, 8, broadcast, 2048, 16, 512, 0, true, true)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 256, 8, broadcast, 2048, 16, 512, 0, true, true)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, broadcast, 2048, 16, 512, 2080, true, true)); ++ for (int tokens : {8,15,17}) { ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, broadcast, 2048, tokens, 512)); ++ } ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, broadcast, 512, 16, 2048)); ++ } ++ for (int selected : {4,16}) cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, selected, false, 2048, 16, 512)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q5_1, GGML_TYPE_F32, 16, 8, false, 2048, 16, 512)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, false, 2032, 16, 512)); ++ cases.emplace_back(new test_portable_routed( ++ GGML_TYPE_Q4_1, GGML_TYPE_F32, 16, 8, false, 2048, 16, 480)); ++ GGML_ASSERT(cases.size() == 35); ++ return cases; ++} +diff --git a/tests/test-metal-graph-optimize.cpp b/tests/test-metal-graph-optimize.cpp +index e9ebdb8df..b65d1d8bf 100644 +--- a/tests/test-metal-graph-optimize.cpp ++++ b/tests/test-metal-graph-optimize.cpp +@@ -8,6 +8,7 @@ + #include "ggml-metal-device.h" + #include "ggml-metal-fusion.h" + #include "ggml-metal-tuning.h" ++#include "ggml-metal-routed-tuning.h" + + #include + #include +@@ -344,6 +345,48 @@ static int run_unary_mul_cases() { + + int main() { + int preference_failures = 0; ++ using ggml_metal_routed_tuning::rows; ++ for (auto device : {GGML_METAL_DEVICE_M1_ULTRA, GGML_METAL_DEVICE_M4}) { ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2048, 16, 2, 4, 8) != 8; ++ for (int64_t tokens : {8, 15, 17, 32}) { ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2048, tokens, 2, 4, 8) != 4; ++ } ++ for (int64_t selections : {1, 4, 16}) { ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2048, 16, 2, 4, selections) != 4; ++ } ++ preference_failures += rows(device, false, GGML_TYPE_Q4_1, 512, 2048, 16, 2, 4, 8) != 4; ++ preference_failures += rows(device, true, GGML_TYPE_Q4_K, 512, 2048, 16, 2, 4, 8) != 4; ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 2048, 512, 16, 2, 4, 8) != 4; ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2032, 16, 2, 4, 8) != 4; ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2048, 16, 1, 4, 8) != 4; ++ } ++ for (auto device : {GGML_METAL_DEVICE_M1, GGML_METAL_DEVICE_M1_MAX, ++ GGML_METAL_DEVICE_M4_PRO, GGML_METAL_DEVICE_M4_MAX, GGML_METAL_DEVICE_M3_ULTRA}) { ++ preference_failures += rows(device, true, GGML_TYPE_Q4_1, 512, 2048, 16, 2, 4, 8) != 4; ++ } ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 2048, 512, 3, 2, 4) != 8; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 512, 2048, 31, 2, 4) != 8; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, false, GGML_TYPE_Q4_1, 2048, 512, 8, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M4_MAX, true, GGML_TYPE_Q4_1, 2048, 512, 8, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 2048, 512, 2, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 2048, 512, 32, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 2048, 520, 8, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 256, 512, 8, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_1, 4352, 512, 8, 2, 4) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, false, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 512, 1, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q5_K, 512, 2048, 2, 2, 1) != 1; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 512, 3, 2, 2) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q5_K, 512, 2048, 8, 2, 1) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 768, 24, 2, 2) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M4_MAX, true, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_PRO, true, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 256, 512, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 514, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 512, 32, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q6_K, 2048, 512, 8, 2, 2) != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 4096, 512, 31, 2, 2) != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 4352, 512, 8, 2, 2) != 2; + for (auto device : { GGML_METAL_DEVICE_M5_MAX, GGML_METAL_DEVICE_M5_PRO, + GGML_METAL_DEVICE_M4_MAX, GGML_METAL_DEVICE_GENERIC }) { + for (bool shared : { false, true }) { +diff --git a/tests/test-metal-routed-u32.cpp b/tests/test-metal-routed-u32.cpp +new file mode 100644 +index 000000000..341ce6ca4 +--- /dev/null ++++ b/tests/test-metal-routed-u32.cpp +@@ -0,0 +1,237 @@ ++#include "ggml.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++#include "ggml-metal-device.h" ++#include "ggml-metal-routed-offsets.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++static void require(bool ok, const char * why) { if (!ok) throw std::runtime_error(why); } ++static std::atomic compiled{0}; ++static std::atomic compiled_r4{0}; ++static void logger(ggml_log_level level, const char * text, void *) { ++ if (std::strstr(text, "compiling pipeline: base = 'kernel_mul_mv_id_q4_1_f32_r8_u32'")) ++compiled; ++ if (std::strstr(text, "compiling pipeline: base = 'kernel_mul_mv_id_q4_1_f32_r4_u32'")) ++compiled_r4; ++ if (level != GGML_LOG_LEVEL_DEBUG) std::fputs(text, stderr); ++} ++struct q4 { ggml_fp16_t d, m; uint8_t qs[16]; }; ++static_assert(sizeof(q4) == 20, "Q4_1 storage"); ++struct storage { ++ ggml_context * ctx = ggml_init({4*1024*1024, nullptr, true}); ++ ggml_backend_buffer_t buffer = nullptr; ++ ~storage() { if (buffer) ggml_backend_buffer_free(buffer); if (ctx) ggml_free(ctx); } ++}; ++ ++static int policy_checks() { ++ using namespace ggml_metal_routed_offsets; ++ storage s; require(s.ctx, "context"); ++ auto * w = ggml_new_tensor_3d(s.ctx, GGML_TYPE_Q4_1, 512, 2048, 256); ++ auto * x = ggml_new_tensor_3d(s.ctx, GGML_TYPE_F32, 512, 8, 16); ++ auto * ids = ggml_new_tensor_2d(s.ctx, GGML_TYPE_I32, 8, 16); ++ auto * out = ggml_mul_mat_id(s.ctx, w, x, ids); ++ const auto admitted = [&] { return eligible(out, GGML_METAL_DEVICE_M1_ULTRA, true, 8, 2); }; ++ int checks = 0; ++ for (auto device : {GGML_METAL_DEVICE_M1_ULTRA, GGML_METAL_DEVICE_M4, ++ GGML_METAL_DEVICE_M5_MAX, GGML_METAL_DEVICE_M3_ULTRA}) { ++ require(requested(nullptr,device)==(device==GGML_METAL_DEVICE_M1_ULTRA), "unqualified default"); ++checks; ++ require(!requested("0",device), "diagnostic opt-out"); ++checks; ++ require(requested("1",device), "explicit diagnostic opt-in"); ++checks; ++ require(requested_r8(nullptr,device)==(device==GGML_METAL_DEVICE_M1_ULTRA || device==GGML_METAL_DEVICE_M5_MAX), "R8 default policy"); ++checks; ++ require(!requested_r8("0",device), "R8 diagnostic opt-out"); ++checks; ++ require(requested_r8("1",device), "R8 diagnostic opt-in"); ++checks; ++ ++ } ++ ++ require(admitted(), "good geometry rejected"); ++checks; ++ require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, true, 4, 2), "NR4 must remain NR4"); ++checks; ++ require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, false, 8, 2), "private mode admitted"); ++checks; ++ require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, true, 8, 1), "wrong SIMD groups"); ++checks; ++ require(!eligible(out, GGML_METAL_DEVICE_M3_ULTRA, true, 8, 2), "unqualified device"); ++checks; ++ for (auto * tensor : {w, x, ids, out}) { ++ auto saved = *tensor; ++ tensor->nb[1] = UINT64_MAX; ++ require(!admitted(), "overflow stride admitted"); ++checks; *tensor = saved; ++ tensor->ne[3] = 2; ++ require(!admitted(), "extra dimension admitted"); ++checks; *tensor = saved; ++ } ++ const size_t stride = ids->nb[1]; ++ ids->nb[1] = 12*sizeof(int32_t); ++ require(admitted(), "padded ID rows rejected"); ++checks; ++ ids->nb[1] = stride; ++ for (int64_t tokens : {1, 3, 8, 15, 17, 32}) { ++ ids->ne[1] = tokens; require(!admitted(), "token fallback admitted"); ++checks; ++ } ++ ids->ne[1] = 16; ++ ggml_tensor boundary{}; boundary.type = GGML_TYPE_I8; ++ for (int i = 0; i < GGML_MAX_DIMS; ++i) { boundary.ne[i] = 1; boundary.nb[i] = 1; } ++ boundary.ne[0] = UINT32_MAX; ++ require(fits_u32(&boundary), "exact byte limit"); ++checks; ++ ++boundary.ne[0]; require(!fits_u32(&boundary), "limit overflow"); ++checks; ++ boundary.ne[0] = 1; boundary.ne[1] = 3; boundary.nb[1] = UINT64_MAX; ++ require(!fits_u32(&boundary), "stride overflow"); ++checks; ++ boundary.type = GGML_TYPE_Q4_1; boundary.ne[0] = 33; ++ require(!fits_u32(&boundary), "partial quant block"); ++checks; ++ for (int tokens : {1, 2, 3, 8, 15, 16, 17}) { ++ auto * xi = ggml_new_tensor_3d(s.ctx, GGML_TYPE_F32, 512, 8, tokens); ++ auto * idi = ggml_new_tensor_2d(s.ctx, GGML_TYPE_I32, 8, tokens); ++ auto * yi = ggml_mul_mat_id(s.ctx, w, xi, idi); ++ require(eligible_r4(yi, GGML_METAL_DEVICE_M1_ULTRA, true, 4, 2)==(tokens<=16), "R4 token admission"); ++checks; ++ require(!eligible_r4(yi, GGML_METAL_DEVICE_M1_ULTRA, true, 8, 2), "R4 changed row geometry"); ++checks; ++ require(!eligible_r4(yi, GGML_METAL_DEVICE_M1_ULTRA, false, 4, 2), "R4 private allocation"); ++checks; ++ idi->nb[1]=UINT64_MAX; ++ require(eligible_r4(yi, GGML_METAL_DEVICE_M1_ULTRA, true, 4, 2)==(tokens==1), "R4 ID span bound"); ++checks; ++ } ++ for (int tokens : {1, 2, 3, 8, 15, 16, 17}) { ++ auto * xi = ggml_new_tensor_3d(s.ctx, GGML_TYPE_F32, 512, 8, tokens); ++ auto * idi = ggml_new_tensor_2d(s.ctx, GGML_TYPE_I32, 8, tokens); ++ auto * yi = ggml_mul_mat_id(s.ctx, w, xi, idi); ++ require(eligible(yi, GGML_METAL_DEVICE_M5_MAX, true, 8, 2)==(tokens>=3 && tokens<=16), "R8 window admission"); ++checks; ++ require(!eligible(yi, GGML_METAL_DEVICE_M5_MAX, true, 4, 2), "R8 row geometry changed"); ++checks; ++ require(!eligible(yi, GGML_METAL_DEVICE_M5_MAX, false, 8, 2), "R8 private allocation"); ++checks; ++ } ++ std::printf("PASS policy_checks=%d\n", checks); ++ ++ ++ return checks; ++} ++ ++static void old_library_check() { ++ auto device = ggml_metal_device_init(0, 1); require(device, "device"); ++ auto old = ggml_metal_library_init_from_source(device, ++ "#include \nusing namespace metal;\nkernel void kernel_mul_mv_id_q4_1_f32_r8() {}\n", false); ++ require(old, "old combined library"); ++ require(ggml_metal_library_has_function(old, "kernel_mul_mv_id_q4_1_f32_r8"), "old function missing"); ++ require(!ggml_metal_library_has_function(old, "kernel_mul_mv_id_q4_1_f32_r8_u32"), "old function discovery false positive"); ++ require(!ggml_metal_library_has_function(old, "kernel_mul_mv_id_q4_1_f32_r8_u32"), "negative discovery cache false positive"); ++ require(ggml_metal_library_has_function(old, "kernel_mul_mv_id_q4_1_f32_r8"), "positive discovery cache lost function"); ++ ++ storage s; ++ auto * w = ggml_new_tensor_3d(s.ctx, GGML_TYPE_Q4_1, 512, 2048, 256); ++ auto * x = ggml_new_tensor_3d(s.ctx, GGML_TYPE_F32, 512, 8, 16); ++ auto * ids = ggml_new_tensor_2d(s.ctx, GGML_TYPE_I32, 8, 16); ++ auto * out = ggml_mul_mat_id(s.ctx, w, x, ids); ++ setenv("GGML_METAL_ROUTED_U32", "1", 1); ++ auto selected = ggml_metal_library_get_pipeline_mul_mv_id(old, out); ++ auto fallback = ggml_metal_library_get_pipeline(old, "kernel_mul_mv_id_q4_1_f32_r8_nsg=2_split=0"); ++ require(selected.pipeline && selected.pipeline == fallback.pipeline && selected.nr0 == 8, "old-library fallback failed"); ++ ggml_metal_library_free(old); ggml_metal_device_free(device); ++ device = ggml_metal_device_init(0, 1); require(device, "R4 fallback device"); ++ old = ggml_metal_library_init_from_source(device, ++ "#include \nusing namespace metal;\nkernel void kernel_mul_mv_id_q4_1_f32() {}\n", false); ++ require(old, "R4 old combined library"); ++ require(!ggml_metal_library_has_function(old,"kernel_mul_mv_id_q4_1_f32_r4_u32"), "R4 missing function"); ++ require(!ggml_metal_library_has_function(old,"kernel_mul_mv_id_q4_1_f32_r4_u32"), "R4 negative discovery cache"); ++ auto * x4 = ggml_new_tensor_3d(s.ctx, GGML_TYPE_F32, 512, 8, 1); ++ auto * ids4 = ggml_new_tensor_2d(s.ctx, GGML_TYPE_I32, 8, 1); ++ auto * out4 = ggml_mul_mat_id(s.ctx,w,x4,ids4); ++ setenv("GGML_METAL_ROUTED_U32_R4", "1", 1); ++ selected = ggml_metal_library_get_pipeline_mul_mv_id(old,out4); ++ fallback = ggml_metal_library_get_pipeline(old,"kernel_mul_mv_id_q4_1_f32_nsg=2_split=0"); ++ require(selected.pipeline && selected.pipeline==fallback.pipeline && selected.nr0==4,"R4 old library fallback failed"); ++ ggml_metal_library_free(old); ggml_metal_device_free(device); ++ std::puts("PASS old_combined_library_fallback=1 r4_fallback=1"); ++ ++} ++ ++static void run_case(ggml_backend_t backend, int k, int m, int experts, int tokens, ++ int input_rows, bool id_view, bool weight_view) { ++ storage s; auto * ctx = s.ctx; ++ const int weight_rows = m + (weight_view ? 16 : 0); ++ auto * weight_root = ggml_new_tensor_3d(ctx, GGML_TYPE_Q4_1, k, weight_rows, experts); ++ auto * weights = weight_view ? ggml_view_3d(ctx, weight_root, k, m, experts, weight_root->nb[1], weight_root->nb[2], 0) : weight_root; ++ auto * input = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, k, input_rows, tokens); ++ const int id_rows = id_view ? 12 : 8; ++ auto * id_root = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, id_rows, tokens); ++ auto * ids = id_view ? ggml_view_2d(ctx, id_root, 8, tokens, id_root->nb[1], sizeof(int32_t)) : id_root; ++ auto * out = ggml_mul_mat_id(ctx, weights, input, ids); ++ auto * graph = ggml_new_graph_custom(ctx, 64, false); ggml_build_forward_expand(graph, out); ++ s.buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); require(s.buffer, "native buffer allocation"); ++ std::vector w(ggml_nbytes(weight_root)/sizeof(q4)); ++ uint32_t random = 0x4158fc17; ++ for (size_t i = 0; i < w.size(); ++i) { ++ w[i].d = ggml_fp32_to_fp16(.0013f + .000071f*(i%31)); ++ w[i].m = ggml_fp32_to_fp16(-.013f + .00091f*(i%29)); ++ for (auto & q : w[i].qs) { random ^= random<<13; random ^= random>>17; random ^= random<<5; q = uint8_t(random); } ++ } ++ std::vector x(ggml_nelements(input)); ++ for (size_t i = 0; i < x.size(); ++i) x[i] = std::sin(double(i)*.017)*.25 + std::cos(double(i)*.041)*.13; ++ ggml_backend_tensor_set(weight_root, w.data(), 0, ggml_nbytes(weight_root)); ++ ggml_backend_tensor_set(input, x.data(), 0, ggml_nbytes(input)); ++ for (int frame : {0, 17}) { ++ std::vector route(id_rows*tokens, 0); ++ for (int t = 0; t < tokens; ++t) for (int r = 0; r < 8; ++r) route[t*id_rows+r+int(id_view)] = (t*17+r*13+frame*7)%experts; ++ route[int(id_view)+7] = -1; ++ route[(tokens-1)*id_rows+int(id_view)+7] = experts-1; ++ ggml_backend_tensor_set(id_root, route.data(), 0, ggml_nbytes(id_root)); ++ std::vector arms[2]; ++ for (int arm = 0; arm < 2; ++arm) { ++ setenv("GGML_METAL_ROUTED_U32", arm ? "1" : "0", 1); ++ setenv("GGML_METAL_ROUTED_U32_R4", arm ? "1" : "0", 1); ++ ++ std::vector poison(ggml_nelements(out), std::nanf("")); ++ ggml_backend_tensor_set(out, poison.data(), 0, ggml_nbytes(out)); ++ require(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS, "native graph failed"); ++ ggml_backend_synchronize(backend); ++ arms[arm].resize(ggml_nelements(out)); ggml_backend_tensor_get(out, arms[arm].data(), 0, ggml_nbytes(out)); ++ for (float value : arms[arm]) require(std::isfinite(value), "incomplete finite output coverage"); ++ double error = 0, scale = 0; ++ for (int t = 0; t < tokens; ++t) for (int r = 0; r < 8; ++r) { ++ const int expert = route[t*id_rows+r+int(id_view)]; ++ if (expert == -1) { for (int row = 0; row < m; ++row) require(arms[arm][(t*8+r)*m+row] == 0, "masked nonzero"); continue; } ++ for (int row : {0, 7, 8, 15, 16, 127, m/2, m-1}) { ++ double expected = 0; ++ for (int col = 0; col < k; ++col) { ++ const auto & q = w[(size_t(expert)*weight_rows+row)*(k/32)+col/32]; ++ const int code = col%32 < 16 ? q.qs[col%16]&15 : q.qs[col%16]>>4; ++ const double value = double(ggml_fp16_to_fp32(q.d))*code + ggml_fp16_to_fp32(q.m); ++ expected += value*x[(size_t(t)*input_rows+r%input_rows)*k+col]; ++ } ++ const double delta = arms[arm][(t*8+r)*m+row]-expected; ++ error += delta*delta; scale += expected*expected; ++ } ++ } ++ require(error/std::fmax(scale, 1e-30) < 1e-9, "native FP64 oracle mismatch"); ++ } ++ size_t different = 0; double delta2 = 0, ref2 = 0; ++ for (size_t i = 0; i < arms[0].size(); ++i) { different += std::memcmp(&arms[0][i], &arms[1][i], sizeof(float)) != 0; const double d = double(arms[0][i])-arms[1][i]; delta2 += d*d; ref2 += double(arms[0][i])*arms[0][i]; } ++ if (different) std::fprintf(stderr,"PAIR_DIFFERENCE k=%d m=%d frame=%d entries=%zu nmse=%.15g compiles=%d\n",k,m,frame,different,delta2/std::fmax(ref2,1e-30),compiled.load()); ++ require(std::memcmp(arms[0].data(), arms[1].data(), ggml_nbytes(out)) == 0, "native paired output differs"); ++ std::printf("PASS native_pair k=%d m=%d experts=%d tokens=%d input_rows=%d id_view=%d weight_view=%d frame=%d bytes=%zu\n", ++ k,m,experts,tokens,input_rows,id_view,weight_view,frame,ggml_nbytes(out)); ++ } ++} ++ ++int main(int argc, char ** argv) { ++ try { ++ const bool policy_only = argc==2 && std::strcmp(argv[1], "--policy-only")==0; ++ require(argc==1 || policy_only, "usage: test-metal-routed-u32 [--policy-only]"); ++ policy_checks(); if (policy_only) return 0; ++ ggml_log_set(logger, nullptr); old_library_check(); compiled.store(0); compiled_r4.store(0); ++ ggml_backend_load_all(); auto backend = ggml_backend_init_by_name("MTL0", nullptr); require(backend, "Metal backend missing"); ++ int cases = 0; ++ for (int k : {2048, 512}) for (int experts : {128, 256}) for (int inputs : {1, 8}) for (bool view : {false, true}) { ++ run_case(backend,k,k==2048?512:2048,experts,16,inputs,view,false); ++cases; ++ } ++ for (int tokens : {3,8,15,17}) for (int inputs : {1,8}) { run_case(backend,512,2048,128,tokens,inputs,true,false); ++cases; } ++ for (int k : {2048,512}) { run_case(backend,k,k==2048?512:2048,128,16,8,true,true); ++cases; } ++ for (int tokens : {1,2}) for (int k : {2048,512}) for (int inputs : {1,8}) { ++ run_case(backend,k,k==2048?512:2048,128,tokens,inputs,true,false); ++cases; ++ } ++ for (int tokens : {3,8,15}) for (int inputs : {1,8}) { ++ run_case(backend,2048,512,128,tokens,inputs,true,false); ++cases; ++ } ++ require(compiled.load() > 0, "new R8 native pipeline never compiled"); ++ require(compiled_r4.load() > 0, "new R4 native pipeline never compiled"); ++ ++ ++ std::printf("PASS native_cases=%d paired_outputs=%d fp64_checks=%d u32_pipeline_compiles=%d r4_pipeline_compiles=%d\n",cases,2*cases,4*cases,compiled.load(),compiled_r4.load()); ++ ggml_backend_free(backend); return 0; ++ } catch (const std::exception & error) { std::fprintf(stderr,"FAIL: %s\n",error.what()); return 1; } ++} +-- +2.56.0 + diff --git a/llama_cpp/patches/0071--metal-process-decode-convolution-channels-across-SIMD-lanes.patch b/llama_cpp/patches/0071--metal-process-decode-convolution-channels-across-SIMD-lanes.patch new file mode 100644 index 00000000..ea8416ac --- /dev/null +++ b/llama_cpp/patches/0071--metal-process-decode-convolution-channels-across-SIMD-lanes.patch @@ -0,0 +1,105 @@ +From 1bb53e3ee05eab29dee35b5624fc6313849e815d Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sun, 15 Nov 2026 21:45:46 +1100 +Subject: [PATCH] metal: process decode convolution channels across SIMD lanes + +--- + ggml/src/ggml-metal/ggml-metal-ops.cpp | 5 ++++- + ggml/src/ggml-metal/kernels/ssm.metal | 10 ++++++++-- + tests/test-backend-ops.cpp | 3 +++ + tests/test-backend-ssm-conv-channels.h | 18 ++++++++++++++++++ + 4 files changed, 33 insertions(+), 3 deletions(-) + create mode 100644 tests/test-backend-ssm-conv-channels.h + +diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp +index a8e346280..32e124d74 100644 +--- a/ggml/src/ggml-metal/ggml-metal-ops.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp +@@ -1946,7 +1946,10 @@ int ggml_metal_op_ssm_conv(ggml_metal_op_t ctx, int idx) { + ggml_metal_encoder_set_buffer(enc, ggml_metal_get_buffer_id(op->src[1]), 2); + ggml_metal_encoder_set_buffer(enc, bid_dst, 3); + +- ggml_metal_encoder_dispatch_threadgroups(enc, ne01, ne1, ne02, 1, 1, 1); ++ // Each SIMD lane computes an independent channel. ++ constexpr int channels_per_group = 32; ++ ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + channels_per_group - 1)/channels_per_group, ++ ne1, ne02, channels_per_group, 1, 1); + } + + if (n_fuse > 1 && ggml_metal_fusion_info_debug(ctx->finfo) > 1) { +diff --git a/ggml/src/ggml-metal/kernels/ssm.metal b/ggml/src/ggml-metal/kernels/ssm.metal +index b21c53b74..882be2b0f 100644 +--- a/ggml/src/ggml-metal/kernels/ssm.metal ++++ b/ggml/src/ggml-metal/kernels/ssm.metal +@@ -12,7 +12,10 @@ kernel void kernel_ssm_conv_f32_f32( + uint3 tgpig[[threadgroup_position_in_grid]], + uint3 tpitg[[thread_position_in_threadgroup]], + uint3 ntg[[threads_per_threadgroup]]) { +- const int64_t ir = tgpig.x; ++ const int64_t ir = tgpig.x*ntg.x + tpitg.x; ++ if (ir >= args.ne01) { ++ return; ++ } + const int64_t i2 = tgpig.y; + const int64_t i3 = tgpig.z; + +@@ -43,7 +46,10 @@ kernel void kernel_ssm_conv_f32_f32_4( + uint3 tgpig[[threadgroup_position_in_grid]], + uint3 tpitg[[thread_position_in_threadgroup]], + uint3 ntg[[threads_per_threadgroup]]) { +- const int64_t ir = tgpig.x; ++ const int64_t ir = tgpig.x*ntg.x + tpitg.x; ++ if (ir >= args.ne01) { ++ return; ++ } + const int64_t i2 = tgpig.y; + const int64_t i3 = tgpig.z; + +diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp +index 8d70e50af..19f9fbf9d 100644 +--- a/tests/test-backend-ops.cpp ++++ b/tests/test-backend-ops.cpp +@@ -5649,6 +5649,8 @@ struct test_ssm_conv_concat_fusion : public test_case { + } + }; + ++#include "test-backend-ssm-conv-channels.h" ++ + // GGML_OP_SSM_SCAN + struct test_ssm_scan : public test_case { + const ggml_type type; +@@ -12152,6 +12154,7 @@ static std::vector> make_test_cases_eval() { + return make_portable_routed_cases(); + } + std::vector> test_cases; ++ append_ssm_conv_channel_cases(test_cases); + std::default_random_engine rng(0); + + // unary ops +diff --git a/tests/test-backend-ssm-conv-channels.h b/tests/test-backend-ssm-conv-channels.h +new file mode 100644 +index 000000000..6f4f90d56 +--- /dev/null ++++ b/tests/test-backend-ssm-conv-channels.h +@@ -0,0 +1,18 @@ ++#pragma once ++ ++// Included after the SSM convolution test classes in test-backend-ops.cpp. ++// Exercise partial channel groups, scalar/float4 kernel widths, sequences, ++// and the fused/non-fused SiLU paths against the CPU reference. ++static void append_ssm_conv_channel_cases(std::vector> & cases) { ++ for (int64_t channels : { 1, 7, 31, 32, 33, 127, 129, 8192, 12288 }) { ++ for (int64_t width : { 3, 4, 5, 8 }) { ++ for (int64_t sequences : { 1, 3 }) { ++ const std::array input = { width, channels, sequences, 1 }; ++ const std::array kernel = { width, channels, 1, 1 }; ++ cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, input, kernel)); ++ cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, input, kernel, false)); ++ cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, input, kernel, true)); ++ } ++ } ++ } ++} +-- +2.56.0 + diff --git a/llama_cpp/patches/0072--quant-preserve-affine-codes-in-Q4K-to-Q41-conversion.patch b/llama_cpp/patches/0072--quant-preserve-affine-codes-in-Q4K-to-Q41-conversion.patch new file mode 100644 index 00000000..2eb9cf16 --- /dev/null +++ b/llama_cpp/patches/0072--quant-preserve-affine-codes-in-Q4K-to-Q41-conversion.patch @@ -0,0 +1,211 @@ +From fd760bec8fbe71871a6fc1017cd2fda5fd3f2c5d Mon Sep 17 00:00:00 2001 +From: Mesh-LLM CI +Date: Sun, 15 Nov 2026 07:46:13 +1100 +Subject: [PATCH] quant: preserve affine codes in Q4_K to Q4_1 conversion + +Transplant the existing 32-value integer grids and round only their affine coefficients to f16. Keep the ordinary quantizer when calibration is supplied or a coefficient cannot be represented. This format conversion is independent of the model-loading adjustments in patch 0003. +--- + src/llama-quant-affine.h | 42 ++++++++++++++++ + src/llama-quant.cpp | 16 +++++-- + tests/CMakeLists.txt | 1 + + tests/test-quantize-affine.cpp | 88 ++++++++++++++++++++++++++++++++++ + 4 files changed, 143 insertions(+), 4 deletions(-) + create mode 100644 src/llama-quant-affine.h + create mode 100644 tests/test-quantize-affine.cpp + +diff --git a/src/llama-quant-affine.h b/src/llama-quant-affine.h +new file mode 100644 +index 000000000..9b5039e36 +--- /dev/null ++++ b/src/llama-quant-affine.h +@@ -0,0 +1,42 @@ ++#pragma once ++ ++#include "../ggml/src/ggml-quants.h" ++ ++#include ++#include ++ ++// Each Q4_K sub-block is already a 32-value affine integer grid. Q4_1 can ++// carry its codes directly, with only the decoded scale/min rounded to f16. ++// Return false when those coefficients cannot be represented finitely. ++inline bool llama_quantize_affine_codes(const void * source, void * destination, int64_t elements) { ++ if (elements < 0 || elements % QK_K != 0) { ++ return false; ++ } ++ const auto * input = static_cast(source); ++ auto * output = static_cast(destination); ++ for (int64_t block = 0; block < elements/QK_K; ++block) { ++ const float scale = ggml_fp16_to_fp32(input[block].d); ++ const float minimum = ggml_fp16_to_fp32(input[block].dmin); ++ const uint8_t * packed = input[block].scales; ++ for (int group = 0; group < 8; ++group) { ++ const int scale_code = group < 4 ? packed[group] & 63 : ++ (packed[group + 4] & 15) | ((packed[group - 4] >> 6) << 4); ++ const int min_code = group < 4 ? packed[group + 4] & 63 : ++ (packed[group + 4] >> 4) | ((packed[group] >> 6) << 4); ++ auto & result = output[8*block + group]; ++ result.d = ggml_fp32_to_fp16(scale*scale_code); ++ result.m = ggml_fp32_to_fp16(-minimum*min_code); ++ if (!std::isfinite(ggml_fp16_to_fp32(result.d)) || ++ !std::isfinite(ggml_fp16_to_fp32(result.m))) { ++ return false; ++ } ++ const uint8_t * codes = input[block].qs + 32*(group/2); ++ const int shift = 4*(group%2); ++ for (int index = 0; index < 16; ++index) { ++ result.qs[index] = uint8_t(((codes[index] >> shift) & 15) | ++ (((codes[index + 16] >> shift) & 15) << 4)); ++ } ++ } ++ } ++ return true; ++} +diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp +index 7dc9cf36a..29a21d57b 100644 +--- a/src/llama-quant.cpp ++++ b/src/llama-quant.cpp +@@ -1,4 +1,5 @@ + #include "llama-impl.h" ++#include "llama-quant-affine.h" + #include "llama-model.h" + #include "llama-model-loader.h" + #include "llama-ext.h" +@@ -3714,6 +3715,17 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: + + const void * src = load_range(ir*row_size_src, nrows_cur*row_size_src); + ++ if (work.size() < nrows_cur*row_size_dst) { ++ work.resize(nrows_cur*row_size_dst); ++ } ++ if (tensor->type == GGML_TYPE_Q4_K && new_type == GGML_TYPE_Q4_1 && !imatrix && ++ llama_quantize_affine_codes(src, work.data(), nelements_cur)) { ++ const size_t size_cur = nrows_cur*row_size_dst; ++ fout.write((const char *) work.data(), size_cur); ++ new_size += size_cur; ++ continue; ++ } ++ + const float * f32_data; + if (tensor->type == GGML_TYPE_F32) { + f32_data = (const float *) src; +@@ -3725,10 +3737,6 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: + f32_data = (const float *) f32_conv_buf.data(); + } + +- if (work.size() < nrows_cur*row_size_dst) { +- work.resize(nrows_cur*row_size_dst); +- } +- + const int64_t nchunk = (nelements_cur + chunk_size - 1)/chunk_size; + const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1; + +diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt +index d6d3d4533..8f18b70a6 100644 +--- a/tests/CMakeLists.txt ++++ b/tests/CMakeLists.txt +@@ -459,6 +459,7 @@ if (NOT GGML_BACKEND_DL AND GGML_CPU) + # these tests use the backends directly and cannot be built with dynamic loading + llama_build_and_test(test-barrier.cpp LABEL "main behavior" LINK ggml) + llama_build_and_test(test-quantize-fns.cpp LABEL "main behavior" LINK ggml) ++ llama_build_and_test(test-quantize-affine.cpp LABEL "main behavior" LINK ggml) + llama_build_and_test(test-quantize-perf.cpp LABEL "main behavior backend" LINK ggml) + llama_build_and_test(test-rope.cpp LABEL "main behavior backend" LINK ggml) + llama_build_and_test(test-col2im-1d.cpp LABEL "main behavior backend" LINK ggml) +diff --git a/tests/test-quantize-affine.cpp b/tests/test-quantize-affine.cpp +new file mode 100644 +index 000000000..77101df97 +--- /dev/null ++++ b/tests/test-quantize-affine.cpp +@@ -0,0 +1,88 @@ ++#include "../src/llama-quant-affine.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++static bool check_codes(const block_q4_K & source, const std::array & output) { ++ for (int group = 0; group < 8; ++group) { ++ for (int index = 0; index < 32; ++index) { ++ const int before = (source.qs[32*(group/2) + index] >> (4*(group%2))) & 15; ++ const int after = (output[group].qs[index%16] >> (4*(index/16))) & 15; ++ if (before != after) { ++ return false; ++ } ++ } ++ } ++ return true; ++} ++ ++int main() { ++ auto * ctx = ggml_init({1024, nullptr, true}); ++ if (!ctx) { ++ return 1; ++ } ++ std::mt19937 rng(42); ++ std::normal_distribution normal; ++ double error = 0, energy = 0; ++ int tested = 0; ++ std::vector corpus; ++ for (float amplitude : {0.0f, 0.0001f, 0.01f, 1.0f, 100.0f}) { ++ for (int sample = 0; sample < 256; ++sample) { ++ std::array weights, before, after; ++ for (float & value : weights) { ++ value = amplitude*normal(rng); ++ } ++ block_q4_K packed; ++ quantize_row_q4_K_ref(weights.data(), &packed, QK_K); ++ corpus.push_back(packed); ++ std::array output; ++ if (!llama_quantize_affine_codes(&packed, output.data(), QK_K) || !check_codes(packed, output)) { ++ std::fprintf(stderr, "affine code conversion failed at amplitude=%g sample=%d\n", amplitude, sample); ++ return 1; ++ } ++ dequantize_row_q4_K(&packed, before.data(), QK_K); ++ dequantize_row_q4_1(output.data(), after.data(), QK_K); ++ for (int i = 0; i < QK_K; ++i) { ++ const double delta = double(after[i]) - before[i]; ++ error += delta*delta; ++ energy += double(before[i])*before[i]; ++ } ++ ++tested; ++ } ++ } ++ block_q4_1 guard; ++ std::memset(&guard, 0xa5, sizeof(guard)); ++ std::vector combined(corpus.size()*8 + 2, guard); ++ if (!llama_quantize_affine_codes(corpus.data(), combined.data() + 1, int64_t(corpus.size())*QK_K) || ++ std::memcmp(&combined.front(), &guard, sizeof(guard)) != 0 || ++ std::memcmp(&combined.back(), &guard, sizeof(guard)) != 0) { ++ std::fprintf(stderr, "multi-block conversion crossed its output bounds\n"); ++ return 1; ++ } ++ for (size_t block = 0; block < corpus.size(); ++block) { ++ std::array output; ++ std::copy_n(combined.data() + 1 + 8*block, 8, output.data()); ++ if (!check_codes(corpus[block], output)) { ++ std::fprintf(stderr, "multi-block conversion changed codes\n"); ++ return 1; ++ } ++ } ++ block_q4_K overflow = {}; ++ overflow.d = overflow.dmin = ggml_fp32_to_fp16(65504.0f); ++ std::fill(std::begin(overflow.scales), std::end(overflow.scales), uint8_t(255)); ++ std::array output; ++ if (llama_quantize_affine_codes(&overflow, output.data(), QK_K) || ++ llama_quantize_affine_codes(&overflow, output.data(), QK_K - 1) || ++ llama_quantize_affine_codes(&overflow, output.data(), -QK_K)) { ++ std::fprintf(stderr, "invalid coefficient/shape accepted\n"); ++ return 1; ++ } ++ const double nmse = error/std::max(energy, 1.0); ++ std::printf("affine code conversion: %d blocks, all codes identical, relative squared error %.9g\n", tested, nmse); ++ ggml_free(ctx); ++ return nmse < 1e-6 ? 0 : 1; ++} +-- +2.56.0 + diff --git a/llama_cpp/patches/0073--memory-avoid-redundant-recurrent-staging-and-admit-Metal-diagnostics.patch b/llama_cpp/patches/0073--memory-avoid-redundant-recurrent-staging-and-admit-Metal-diagnostics.patch new file mode 100644 index 00000000..aee06cea --- /dev/null +++ b/llama_cpp/patches/0073--memory-avoid-redundant-recurrent-staging-and-admit-Metal-diagnostics.patch @@ -0,0 +1,364 @@ +From e5cad9c47ecd27b4a78c87aafc8d8a141c870f7e Mon Sep 17 00:00:00 2001 +From: Skippy CI +Date: Mon, 23 Nov 2026 09:41:37 +1100 +Subject: [PATCH] memory: avoid redundant recurrent staging and admit Metal + diagnostics by capability + +--- + ggml/src/ggml-metal/ggml-metal-device.cpp | 2 +- + .../ggml-metal/ggml-metal-routed-offsets.h | 4 +- + .../src/ggml-metal/ggml-metal-routed-tuning.h | 13 +++- + ggml/src/ggml-metal/ggml-metal-tuning.cpp | 6 +- + ggml/src/ggml-metal/ggml-metal-tuning.h | 2 +- + ggml/src/ggml-metal/ggml-metal.cpp | 2 +- + src/CMakeLists.txt | 6 ++ + src/llama-memory-recurrent-copy.cpp | 68 ++++++++++++++++--- + src/llama-memory-recurrent-copy.h | 8 ++- + src/skippy/tests/recurrent_copy.cpp | 52 ++++++++++++++ + tests/test-metal-graph-optimize.cpp | 7 ++ + tests/test-metal-routed-u32.cpp | 3 +- + 12 files changed, 152 insertions(+), 21 deletions(-) + create mode 100644 src/skippy/tests/recurrent_copy.cpp + +diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp +index f9bac503d..51ad1fb4f 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-device.cpp +@@ -1594,7 +1594,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_m + + const auto * props = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); + const int tuned_rows = ggml_metal_routed_tuning::rows( +- props->device_id, props->use_shared_buffers, tsrc0, ne00, ne01, op->src[2]->ne[1], nsg, nr0, op->src[2]->ne[0]); ++ props->device_id, props->use_shared_buffers, tsrc0, ne00, ne01, op->src[2]->ne[1], nsg, nr0, op->src[2]->ne[0], props->gpu_family, std::getenv("GGML_METAL_ROUTED_ROWS")); + if (tuned_rows != nr0) { + nr0 = tuned_rows; + suffix = tsrc0 == GGML_TYPE_Q4_K ? "_r4" : tsrc0 == GGML_TYPE_Q4_1 ? "_r8" : "_r2"; +diff --git a/ggml/src/ggml-metal/ggml-metal-routed-offsets.h b/ggml/src/ggml-metal/ggml-metal-routed-offsets.h +index 30fc69a5d..d9aa8aeda 100644 +--- a/ggml/src/ggml-metal/ggml-metal-routed-offsets.h ++++ b/ggml/src/ggml-metal/ggml-metal-routed-offsets.h +@@ -38,8 +38,8 @@ inline bool eligible_geometry(const ggml_tensor * op, ggml_metal_device_id devic + bool shared, int rows, int simdgroups, int required_rows, + int64_t min_tokens, int64_t max_tokens) { + if (!op || op->op != GGML_OP_MUL_MAT_ID || !shared || rows != required_rows || simdgroups != 2) return false; +- if (device != GGML_METAL_DEVICE_M1_ULTRA && device != GGML_METAL_DEVICE_M4 && +- device != GGML_METAL_DEVICE_M5_MAX) return false; ++ // Eligibility is bounded by geometry and offset range, not the chip SKU. ++ GGML_UNUSED(device); + const auto * weights = op->src[0]; + const auto * input = op->src[1]; + const auto * ids = op->src[2]; +diff --git a/ggml/src/ggml-metal/ggml-metal-routed-tuning.h b/ggml/src/ggml-metal/ggml-metal-routed-tuning.h +index d65eb01aa..6c30b5b11 100644 +--- a/ggml/src/ggml-metal/ggml-metal-routed-tuning.h ++++ b/ggml/src/ggml-metal/ggml-metal-routed-tuning.h +@@ -1,21 +1,28 @@ + #pragma once + + #include "ggml-metal-device.h" ++#include + + namespace ggml_metal_routed_tuning { + + // Reuse the per-lane activation registers across more output rows. Preserve + // complete SIMDgroup row tiles: the vector bodies load every unrolled row. + inline int rows(ggml_metal_device_id device, bool shared_buffers, ggml_type type, int64_t inner, +- int64_t output, int64_t tokens, int nsg, int fallback, int64_t selections = 8) { ++ int64_t output, int64_t tokens, int nsg, int fallback, int64_t selections = 8, ++ int gpu_family = 0, const char * setting = nullptr) { ++ if (setting && std::strcmp(setting, "0") == 0) return fallback; ++ const bool diagnostic = setting && std::strcmp(setting, "1") == 0; ++ const bool older_family = diagnostic ? gpu_family >= 7 && gpu_family <= 9 : ++ device == GGML_METAL_DEVICE_M1_ULTRA || device == GGML_METAL_DEVICE_M4; ++ const bool newer_family = diagnostic ? gpu_family >= 10 : device == GGML_METAL_DEVICE_M5_MAX; + // Portable screen supports this down-projection shape only. Gate/up + // remains faster at the existing width on these two measured devices. +- if ((device == GGML_METAL_DEVICE_M1_ULTRA || device == GGML_METAL_DEVICE_M4) && ++ if (older_family && + shared_buffers && type == GGML_TYPE_Q4_1 && inner == 512 && output == 2048 && + tokens == 16 && selections == 8 && nsg == 2) { + return 8; + } +- if (device != GGML_METAL_DEVICE_M5_MAX || !shared_buffers || tokens < 3 || inner < 512 || inner > 4096 || ++ if (!newer_family || !shared_buffers || tokens < 3 || inner < 512 || inner > 4096 || + output < 512 || tokens > 31 || nsg <= 0) { + return fallback; + } +diff --git a/ggml/src/ggml-metal/ggml-metal-tuning.cpp b/ggml/src/ggml-metal/ggml-metal-tuning.cpp +index f8ff94114..5cc94f3e5 100644 +--- a/ggml/src/ggml-metal/ggml-metal-tuning.cpp ++++ b/ggml/src/ggml-metal/ggml-metal-tuning.cpp +@@ -6,8 +6,10 @@ + + namespace ggml_metal_tuning { + +-bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers) { +- return device == GGML_METAL_DEVICE_M5_MAX && shared_buffers; ++bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers, const char * setting) { ++ // Shared buffers make the host read legal. Only the measured M5 default ++ // is promoted; explicit diagnostics can exercise other shared devices. ++ return shared_buffers && (setting ? std::strcmp(setting, "1") == 0 : device == GGML_METAL_DEVICE_M5_MAX); + } + + int fa_vec_ne11_bucket(int64_t ne11) { +diff --git a/ggml/src/ggml-metal/ggml-metal-tuning.h b/ggml/src/ggml-metal/ggml-metal-tuning.h +index 3d858b56f..183cb0666 100644 +--- a/ggml/src/ggml-metal/ggml-metal-tuning.h ++++ b/ggml/src/ggml-metal/ggml-metal-tuning.h +@@ -10,7 +10,7 @@ namespace ggml_metal_tuning { + + // Qualified on M5 Max with shared graph buffers; leave other devices and + // private-buffer configurations on their existing sampling path. +-bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers); ++bool prefer_host_greedy(ggml_metal_device_id device, bool shared_buffers, const char * setting = nullptr); + + // FA vec selection buckets. ne01 (query rows) splits decode (==1) from batch (>=2), the + // batch side refined into {2,3,4,5}: Q>1 reuses one K/V load across rows, so it only pays +diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp +index 1e3b5e1c7..d6238a1ed 100644 +--- a/ggml/src/ggml-metal/ggml-metal.cpp ++++ b/ggml/src/ggml-metal/ggml-metal.cpp +@@ -1020,7 +1020,7 @@ static void ggml_backend_metal_fusion_set_enabled(ggml_backend_fusion_t finfo, b + + static bool ggml_backend_metal_prefers_host_greedy(ggml_backend_dev_t dev) { + const auto * props = ggml_metal_device_get_props((ggml_metal_device_t) dev->context); +- return ggml_metal_tuning::prefer_host_greedy(props->device_id, props->use_shared_buffers); ++ return ggml_metal_tuning::prefer_host_greedy(props->device_id, props->use_shared_buffers, std::getenv("GGML_METAL_HOST_GREEDY")); + } + + static void * ggml_backend_metal_get_proc_address(ggml_backend_reg_t reg, const char * name) { +diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt +index 829600868..449e8e546 100644 +--- a/src/CMakeLists.txt ++++ b/src/CMakeLists.txt +@@ -441,6 +441,12 @@ if (LLAMA_STAGE_BUILD_TESTS) + set_tests_properties(skippy_generate_gemma_fixture PROPERTIES + FIXTURES_SETUP skippy-model-loader-fixtures) + ++ add_executable(skippy-recurrent-copy skippy/tests/recurrent_copy.cpp) ++ target_include_directories(skippy-recurrent-copy PRIVATE .) ++ target_compile_features(skippy-recurrent-copy PRIVATE cxx_std_17) ++ target_link_libraries(skippy-recurrent-copy PRIVATE llama) ++ add_test(NAME skippy_recurrent_copy COMMAND skippy-recurrent-copy) ++ + add_executable(skippy-verify-rollback skippy/tests/verify_rollback.cpp) + target_include_directories(skippy-verify-rollback PRIVATE .) + target_compile_features(skippy-verify-rollback PRIVATE cxx_std_17) +diff --git a/src/llama-memory-recurrent-copy.cpp b/src/llama-memory-recurrent-copy.cpp +index 9c269200b..e92039d4b 100644 +--- a/src/llama-memory-recurrent-copy.cpp ++++ b/src/llama-memory-recurrent-copy.cpp +@@ -3,37 +3,87 @@ + #include "ggml-backend.h" + + #include ++#include ++#include "skippy/trace_scope.h" + +-void llama_recurrent_copy_rows( ++// A row view lets shared-memory and device backends copy in their own memory ++// domain. The caller has already synchronized recurrent state before relocation. ++static ggml_tensor recurrent_row_view(ggml_tensor * tensor, uint32_t row, size_t bytes) { ++ ggml_tensor view = *tensor; ++ view.data = static_cast(tensor->data) + row * tensor->nb[1]; ++ view.view_src = nullptr; ++ view.view_offs = 0; ++ for (int dim = 1; dim < GGML_MAX_DIMS; ++dim) { ++ view.ne[dim] = 1; ++ view.nb[dim] = bytes; ++ } ++ return view; ++} ++ ++llama_recurrent_copy_stats llama_recurrent_copy_rows( + const std::vector & tensors, + const std::vector> & groups, + std::vector & scratch) { +- for (auto * tensor : tensors) { +- if (!tensor || !tensor->buffer) { +- continue; ++ skippy_trace::scope trace("native.recurrent_rollback_copy"); ++ llama_recurrent_copy_stats stats; ++ for (const auto & group : groups) { ++ std::vector rows; ++ std::set destinations; ++ for (const auto & row : group) { ++ if (!row.zero && row.source == row.destination) { ++ ++stats.skipped_rows; ++ continue; ++ } ++ GGML_ASSERT(destinations.insert(row.destination).second); ++ rows.push_back(row); ++ } ++ // No destination may destroy a source another row still needs. If ++ // there is an alias (including cycles/fan-out), retain gather-before-write. ++ bool aliases = false; ++ for (const auto & row : rows) { ++ aliases |= !row.zero && destinations.count(row.source) != 0; + } +- const size_t row_bytes = ggml_row_size(tensor->type, tensor->ne[0]); +- for (const auto & rows : groups) { +- if (rows.empty()) continue; ++ for (auto * tensor : tensors) { ++ if (!tensor || !tensor->buffer || rows.empty()) continue; ++ const size_t row_bytes = ggml_row_size(tensor->type, tensor->ne[0]); ++ for (const auto & row : rows) { ++ GGML_ASSERT(row.destination < tensor->ne[1]); ++ GGML_ASSERT(row.zero || row.source < tensor->ne[1]); ++ } ++ if (!aliases) { ++ for (const auto & row : rows) { ++ auto destination = recurrent_row_view(tensor, row.destination, row_bytes); ++ if (row.zero) { ++ ggml_backend_tensor_memset(&destination, 0, 0, row_bytes); ++ } else { ++ auto source = recurrent_row_view(tensor, row.source, row_bytes); ++ ggml_backend_tensor_copy(&source, &destination); ++ } ++ stats.direct_bytes += row_bytes; ++ } ++ continue; ++ } + const size_t needed = rows.size() * row_bytes; + if (scratch.size() < needed) scratch.resize(needed); + for (size_t i = 0; i < rows.size(); ++i) { + const auto & row = rows[i]; +- GGML_ASSERT(row.destination < tensor->ne[1]); + auto * output = scratch.data() + i * row_bytes; + if (row.zero) { + std::memset(output, 0, row_bytes); + } else { +- GGML_ASSERT(row.source < tensor->ne[1]); + ggml_backend_tensor_get(tensor, output, row.source * tensor->nb[1], row_bytes); ++ stats.staged_bytes += row_bytes; + } + } + for (size_t i = 0; i < rows.size(); ++i) { + ggml_backend_tensor_set(tensor, scratch.data() + i * row_bytes, + rows[i].destination * tensor->nb[1], row_bytes); ++ stats.staged_bytes += row_bytes; + } + } + } ++ trace.set_value("host_staging_bytes", stats.staged_bytes); ++ return stats; + } + + void llama_memory_recurrent::preserve_peer_rollback(uint32_t first, uint32_t last, uint32_t n_seqs) { +diff --git a/src/llama-memory-recurrent-copy.h b/src/llama-memory-recurrent-copy.h +index 6577e206d..7ed33ed71 100644 +--- a/src/llama-memory-recurrent-copy.h ++++ b/src/llama-memory-recurrent-copy.h +@@ -12,9 +12,15 @@ struct llama_recurrent_copy_row { + bool zero = false; + }; + ++struct llama_recurrent_copy_stats { ++ size_t staged_bytes = 0; ++ size_t direct_bytes = 0; ++ size_t skipped_rows = 0; ++}; ++ + // Groups must be ordered by destination snapshot plane. Sources are from the + // same or a later plane; gather each group before writing to preserve aliases. +-void llama_recurrent_copy_rows( ++llama_recurrent_copy_stats llama_recurrent_copy_rows( + const std::vector & tensors, + const std::vector> & groups, + std::vector & scratch); +diff --git a/src/skippy/tests/recurrent_copy.cpp b/src/skippy/tests/recurrent_copy.cpp +new file mode 100644 +index 000000000..ca9641b9a +--- /dev/null ++++ b/src/skippy/tests/recurrent_copy.cpp +@@ -0,0 +1,52 @@ ++#include "llama-memory-recurrent-copy.h" ++#include "ggml.h" ++#include "ggml-alloc.h" ++#include "ggml-backend.h" ++#include ++#include ++#include ++#include ++#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "CHECK failed: %s:%d %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0) ++ ++static void check(ggml_backend_buffer_type_t buft, ++ const std::vector> & groups, ++ bool direct) { ++ auto * ctx = ggml_init({1024*1024, nullptr, true}); ++ auto * tensor = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1024, 8); ++ auto buffer = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); ++ CHECK(buffer); ++ std::vector expected(8192), actual(8192); ++ for (size_t i = 0; i < expected.size(); ++i) expected[i] = float(i + 1); ++ ggml_backend_tensor_set(tensor, expected.data(), 0, ggml_nbytes(tensor)); ++ for (const auto & rows : groups) { ++ const auto before = expected; ++ for (const auto & row : rows) { ++ for (size_t i = 0; i < 1024; ++i) { ++ expected[row.destination * 1024 + i] = row.zero ? 0 : before[row.source * 1024 + i]; ++ } ++ } ++ } ++ std::vector scratch; ++ const auto stats = llama_recurrent_copy_rows({tensor}, groups, scratch); ++ ggml_backend_tensor_get(tensor, actual.data(), 0, ggml_nbytes(tensor)); ++ CHECK(actual == expected); ++ if (direct) CHECK(scratch.empty() && stats.staged_bytes == 0); ++ else CHECK(!scratch.empty() && stats.staged_bytes > 0); ++ std::printf("staged=%zu direct=%zu skipped=%zu scratch=%zu\n", ++ stats.staged_bytes, stats.direct_bytes, stats.skipped_rows, scratch.size()); ++ ggml_backend_buffer_free(buffer); ++ ggml_free(ctx); ++} ++ ++int main(int argc, char ** argv) { ++ ggml_backend_load_all(); ++ auto * device = ggml_backend_dev_by_name(argc > 1 ? argv[1] : "CPU"); ++ CHECK(device); ++ auto buft = ggml_backend_dev_buffer_type(device); ++ check(buft, {{{0, 0}, {1, 1}, {2, 5}, {2, 6}, {0, 7, true}}}, true); ++ check(buft, {{{0, 1}, {1, 0}, {2, 2}}}, false); // swap ++ check(buft, {{{0, 1}, {1, 2}, {2, 0}, {0, 3}}}, false); // cycle and fan-out ++ check(buft, {{{0, 1}, {0, 0, true}}}, false); // zeroing must not destroy a source ++ check(buft, {{{4, 0}, {5, 1}}, {{6, 4}, {7, 5}}}, true); // ascending snapshot planes ++ check(buft, {{{0, 0}, {1, 1}}}, true); // identity-only: no allocation/copy ++} +diff --git a/tests/test-metal-graph-optimize.cpp b/tests/test-metal-graph-optimize.cpp +index b65d1d8bf..75d4dd856 100644 +--- a/tests/test-metal-graph-optimize.cpp ++++ b/tests/test-metal-graph-optimize.cpp +@@ -396,6 +396,13 @@ int main() { + preference_failures += !ok; + } + } ++ preference_failures += !ggml_metal_tuning::prefer_host_greedy(GGML_METAL_DEVICE_M3_ULTRA, true, "1"); ++ preference_failures += ggml_metal_tuning::prefer_host_greedy(GGML_METAL_DEVICE_M3_ULTRA, false, "1"); ++ preference_failures += ggml_metal_tuning::prefer_host_greedy(GGML_METAL_DEVICE_M5_MAX, true, "0"); ++ preference_failures += rows(GGML_METAL_DEVICE_M3_ULTRA, true, GGML_TYPE_Q4_1, 512, 2048, 16, 2, 4, 8, 9, "1") != 8; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_PRO, true, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2, 8, 10, "1") != 4; ++ preference_failures += rows(GGML_METAL_DEVICE_M3_ULTRA, true, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2, 8, 9, "1") != 2; ++ preference_failures += rows(GGML_METAL_DEVICE_M5_MAX, true, GGML_TYPE_Q4_K, 2048, 512, 8, 2, 2, 8, 10, "0") != 2; + const std::vector devices = { + { "native simdgroup matrices", true, true }, + { "probed or no simdgroup matrices", false, true }, +diff --git a/tests/test-metal-routed-u32.cpp b/tests/test-metal-routed-u32.cpp +index 341ce6ca4..d15a76355 100644 +--- a/tests/test-metal-routed-u32.cpp ++++ b/tests/test-metal-routed-u32.cpp +@@ -50,10 +50,11 @@ static int policy_checks() { + } + + require(admitted(), "good geometry rejected"); ++checks; ++ require(eligible(out, GGML_METAL_DEVICE_M3_ULTRA, true, 8, 2), "M3 diagnostic geometry rejected"); ++checks; + require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, true, 4, 2), "NR4 must remain NR4"); ++checks; + require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, false, 8, 2), "private mode admitted"); ++checks; + require(!eligible(out, GGML_METAL_DEVICE_M1_ULTRA, true, 8, 1), "wrong SIMD groups"); ++checks; +- require(!eligible(out, GGML_METAL_DEVICE_M3_ULTRA, true, 8, 2), "unqualified device"); ++checks; ++ require(eligible(out, GGML_METAL_DEVICE_M3_ULTRA, true, 8, 2), "capable device diagnostic"); ++checks; + for (auto * tensor : {w, x, ids, out}) { + auto saved = *tensor; + tensor->nb[1] = UINT64_MAX; +-- +2.56.0 + diff --git a/llama_cpp/patches/0074--skippy-count-decode-work-once-after-fences.patch b/llama_cpp/patches/0074--skippy-count-decode-work-once-after-fences.patch new file mode 100644 index 00000000..c86867da --- /dev/null +++ b/llama_cpp/patches/0074--skippy-count-decode-work-once-after-fences.patch @@ -0,0 +1,49 @@ +From 794e49fa7afef94bbb4abbef441830e659cb0ad2 Mon Sep 17 00:00:00 2001 +From: Skippy CI +Date: Sat, 28 Nov 2026 18:37:46 +1100 +Subject: [PATCH] skippy: count decode work once after synchronization fences + +--- + src/llama-context.cpp | 6 ------ + src/skippy/tests/async_state.cpp | 8 +++++++- + 2 files changed, 7 insertions(+), 7 deletions(-) + +diff --git a/src/llama-context.cpp b/src/llama-context.cpp +index f2a65001e..b6bd6ff99 100644 +--- a/src/llama-context.cpp ++++ b/src/llama-context.cpp +@@ -2439,12 +2439,6 @@ int llama_context::decode( + output_swaps.clear(); + embd_batch_idxs.clear(); + +- // Synchronizing the preceding decode must not account this batch's work. +- if (t_compute_start_us == 0) { +- t_compute_start_us = ggml_time_us(); +- } +- n_queued_tokens += n_tokens_all; +- + sched_reserve(graph_build_inputs); + + if (t_compute_start_us == 0) { +diff --git a/src/skippy/tests/async_state.cpp b/src/skippy/tests/async_state.cpp +index efe8d28ba..1937d38b7 100644 +--- a/src/skippy/tests/async_state.cpp ++++ b/src/skippy/tests/async_state.cpp +@@ -200,7 +200,13 @@ void test_sampler_reservations(skippy_session * first, skippy_session * second) + 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); ++ // The pinned context invalidates the graph when an attached sampler is removed. ++ CHECK(first->ctx->get_sched_reserve_count() > reserved_before_detach); ++ const uint64_t reserved_after_detach = first->ctx->get_sched_reserve_count(); ++ // Removing an already absent sampler is a no-op. ++ CHECK(llama_set_sampler(first->ctx, first->seq_id, nullptr)); ++ first->ctx->sched_reserve(); ++ CHECK(first->ctx->get_sched_reserve_count() == reserved_after_detach); + llama_sampler_free(replacement); + llama_sampler_free(shape_chain); + } +-- +2.56.0 + diff --git a/llama_cpp/patches/0075--import-raw-kv-pages-from-borrowed-chunks.patch b/llama_cpp/patches/0075--import-raw-kv-pages-from-borrowed-chunks.patch new file mode 100644 index 00000000..9dcc1bbf --- /dev/null +++ b/llama_cpp/patches/0075--import-raw-kv-pages-from-borrowed-chunks.patch @@ -0,0 +1,341 @@ +From 189fdd57775c79eafa75cb96f6924cc00e0fe3de Mon Sep 17 00:00:00 2001 +From: Skippy contributors +Date: Mon, 23 Nov 2026 14:44:16 +1100 +Subject: [PATCH] skippy: import raw KV pages from borrowed chunks + +--- + include/skippy/state.h | 18 +++++++ + src/llama-kv-cache.cpp | 83 ++++++++++++++++++++++++++------ + src/llama-kv-cache.h | 11 +++++ + src/skippy/state.cpp | 63 +++++++++++++++++++++--- + src/skippy/tests/async_state.cpp | 24 ++++++++- + 5 files changed, 177 insertions(+), 22 deletions(-) + +diff --git a/include/skippy/state.h b/include/skippy/state.h +index 6f8a93484..489d72a4c 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -218,6 +218,24 @@ LLAMA_API enum skippy_status skippy_import_kv_page( + size_t input_bytes, + struct skippy_error ** out_error); + ++/** @brief A borrowed range of raw KV page bytes. */ ++struct skippy_kv_page_chunk { ++ const void * data; ++ size_t bytes; ++}; ++ ++/** @brief Imports a single raw KV page from non-empty chunks in wire order. ++ * The ranges must remain readable until return and together cover exactly ++ * desc->payload_bytes. Unsupported layouts or backends leave the session ++ * untouched, so the caller can retry with a contiguous payload. ++ */ ++LLAMA_API enum skippy_status skippy_import_kv_page_chunks( ++ struct skippy_session * session, ++ const struct skippy_kv_page_desc * desc, ++ const struct skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ struct skippy_error ** out_error); ++ + /** @brief Imports validated CacheGen records directly into resident KV storage. */ + LLAMA_API enum skippy_status skippy_import_cachegen_kv_page_v1( + struct skippy_session * session, +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index c030afcfe..6074b0a1d 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -2183,11 +2183,54 @@ 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; + } ++ const skippy_kv_page_chunk chunk{input, input_bytes}; ++ bool unsupported = false; ++ return stage_import_kv_page_chunks(seq_id, desc, &chunk, 1, input_bytes, error, unsupported, validate_only); ++} ++ ++namespace { ++ ++class kv_page_reader { ++public: ++ explicit kv_page_reader(const skippy_kv_page_chunk * chunks) : chunk(chunks) {} ++ ++ void write(ggml_tensor * tensor, size_t offset, size_t bytes) { ++ while (bytes != 0) { ++ const size_t count = std::min(bytes, chunk->bytes - consumed); ++ const auto * source = static_cast(chunk->data); ++ ggml_backend_tensor_set(tensor, source + consumed, offset, count); ++ consumed += count; ++ if (consumed == chunk->bytes) { ++ ++chunk; ++ consumed = 0; ++ } ++ offset += count; ++ bytes -= count; ++ } ++ } ++ ++private: ++ const skippy_kv_page_chunk * chunk; ++ size_t consumed = 0; ++}; ++ ++} // namespace ++ ++bool llama_kv_cache::stage_import_kv_page_chunks( ++ llama_seq_id seq_id, ++ const skippy_kv_page_desc & desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ size_t input_bytes, ++ std::string & error, ++ bool & unsupported, ++ bool validate_only) { ++ skippy_trace::scope trace("llama.kv_page_import", "bytes", (int64_t) input_bytes); ++ unsupported = false; + if (desc.version != 1) { + error = "unsupported native KV page descriptor version"; + return false; +@@ -2291,6 +2334,21 @@ bool llama_kv_cache::stage_import_kv_page( + return true; + } + ++ // Fragmented writes are cheap on host and shared Metal buffers. A device ++ // buffer could turn every input chunk into a synchronous upload. ++ if (chunk_count > 1 && !std::all_of(selected.begin(), selected.end(), [strm](const kv_layer * layer) { ++ const auto host = [](const std::vector & streams, uint32_t index) { ++ return index >= streams.size() || streams[index] == nullptr || ++ skippy_kv_buffer_pages_are_host(streams[index]->view_src ? ++ streams[index]->view_src->buffer : streams[index]->buffer); ++ }; ++ return host(layer->k_stream, strm) && host(layer->v_stream, strm) && host(layer->k_idx_stream, strm); ++ })) { ++ unsupported = true; ++ error = "chunked KV page import requires host-visible cache buffers"; ++ return false; ++ } ++ + llama_ubatch ubatch = {}; + auto udata = std::make_shared(); + const uint32_t n_tokens = static_cast(desc.token_count); +@@ -2368,13 +2426,12 @@ bool llama_kv_cache::stage_import_kv_page( + apply_ubatch(sinfo, ubatch, overwrites_full_rows); + + const auto cell_runs = llama_kv_cache_cell_runs(sinfo.idxs[0]); +- const char * src = static_cast(input); ++ kv_page_reader reader(chunks); + for (const auto * layer : selected) { + auto * k = layer->k_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.k_row_bytes; +- ggml_backend_tensor_set(k, src, static_cast(run.first) * desc.k_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(k, static_cast(run.first) * desc.k_row_bytes, ++ static_cast(run.count) * desc.k_row_bytes); + } + } + +@@ -2386,9 +2443,8 @@ bool llama_kv_cache::stage_import_kv_page( + } + auto * v = layer->v_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.v_row_bytes; +- ggml_backend_tensor_set(v, src, static_cast(run.first) * desc.v_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(v, static_cast(run.first) * desc.v_row_bytes, ++ static_cast(run.count) * desc.v_row_bytes); + } + } + } else { +@@ -2400,10 +2456,8 @@ bool llama_kv_cache::stage_import_kv_page( + const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(layer->il); + for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.v_element_bytes; + const size_t dst_offset = (static_cast(run.first) + static_cast(j) * cells.size()) * desc.v_element_bytes; +- ggml_backend_tensor_set(v, src, dst_offset, run_bytes); +- src += run_bytes; ++ reader.write(v, dst_offset, static_cast(run.count) * desc.v_element_bytes); + } + } + } +@@ -2414,14 +2468,13 @@ bool llama_kv_cache::stage_import_kv_page( + for (const auto * layer : selected) { + auto * k_idx = layer->k_idx_stream[strm]; + for (const auto & run : cell_runs) { +- const size_t run_bytes = static_cast(run.count) * desc.k_idx_row_bytes; +- ggml_backend_tensor_set(k_idx, src, static_cast(run.first) * desc.k_idx_row_bytes, run_bytes); +- src += run_bytes; ++ reader.write(k_idx, static_cast(run.first) * desc.k_idx_row_bytes, ++ static_cast(run.count) * desc.k_idx_row_bytes); + } + } + } + +- return src == static_cast(input) + input_bytes; ++ return true; + } + + static uint16_t skippy_cachegen_read_u16(const uint8_t * bytes) { +diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h +index 52c06ffa4..e1763c7ad 100644 +--- a/src/llama-kv-cache.h ++++ b/src/llama-kv-cache.h +@@ -15,6 +15,7 @@ struct llama_hparams; + struct llama_model; + struct llama_context; + struct skippy_kv_page_desc; ++struct skippy_kv_page_chunk; + struct skippy_cachegen_record_v1; + + // +@@ -220,6 +221,16 @@ public: + std::string & error, + bool validate_only = false); + ++ bool stage_import_kv_page_chunks( ++ llama_seq_id seq_id, ++ const skippy_kv_page_desc & desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ size_t input_bytes, ++ std::string & error, ++ bool & unsupported, ++ bool validate_only = false); ++ + bool stage_import_cachegen_kv_page( + llama_seq_id seq_id, + const skippy_kv_page_desc & desc, +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +index bab58a50f..bc842ee9e 100644 +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -479,6 +479,18 @@ static bool skippy_validate_composite_desc(const skippy_kv_page_desc & desc, siz + return true; + } + ++static skippy_status skippy_finish_kv_page_import( ++ skippy_session * session, const skippy_kv_page_desc & desc, skippy_error ** out_error) { ++ if (llm_graph_result * graph = session->ctx->get_gf_res_prev_active()) { ++ graph->reset(); ++ } ++ 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); ++ skippy_clear_verify_windows(session); ++ session->ctx->synchronize(); ++ return skippy_success(out_error); ++} ++ + enum skippy_status skippy_import_kv_page( + struct skippy_session * session, + const struct skippy_kv_page_desc * desc, +@@ -530,14 +542,53 @@ enum skippy_status skippy_import_kv_page( + skippy_set_error(out_error, status, error.c_str()); + return status; + } +- if (llm_graph_result * graph = session->ctx->get_gf_res_prev_active()) { +- graph->reset(); ++ return skippy_finish_kv_page_import(session, *desc, out_error); ++} ++ ++enum skippy_status skippy_import_kv_page_chunks( ++ skippy_session * session, ++ const skippy_kv_page_desc * desc, ++ const skippy_kv_page_chunk * chunks, ++ size_t chunk_count, ++ skippy_error ** out_error) { ++ if (session == nullptr || session->ctx == nullptr || desc == nullptr || chunks == nullptr || chunk_count == 0 || ++ chunk_count > desc->payload_bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session, descriptor, and KV chunks are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ size_t bytes = 0; ++ for (size_t i = 0; i < chunk_count; ++i) { ++ if (chunks[i].data == nullptr || chunks[i].bytes == 0 || ++ chunks[i].bytes > std::numeric_limits::max() - bytes || ++ chunks[i].bytes > desc->payload_bytes - bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "invalid KV page chunk"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ bytes += chunks[i].bytes; ++ } ++ if (bytes != desc->payload_bytes) { ++ skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "KV chunks do not cover the page"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (desc->codec != 0 && desc->codec != SKIPPY_KV_PAGE_CODEC_SINGLE_V1) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "chunked KV import requires a single raw page"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ auto * kv = skippy_get_kv_cache(session, nullptr); ++ if (kv == nullptr) { ++ skippy_set_error(out_error, SKIPPY_STATUS_UNSUPPORTED, "runtime memory does not support single raw KV pages"); ++ return SKIPPY_STATUS_UNSUPPORTED; + } +- 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); +- skippy_clear_verify_windows(session); + session->ctx->synchronize(); +- return skippy_success(out_error); ++ skippy_mark_context_synchronized(session->stage_model); ++ std::string error; ++ bool unsupported = false; ++ if (!kv->stage_import_kv_page_chunks(session->seq_id, *desc, chunks, chunk_count, bytes, error, unsupported)) { ++ const auto status = unsupported ? SKIPPY_STATUS_UNSUPPORTED : SKIPPY_STATUS_RUNTIME_ERROR; ++ skippy_set_error(out_error, status, error.c_str()); ++ return status; ++ } ++ return skippy_finish_kv_page_import(session, *desc, out_error); + } + + enum skippy_status skippy_import_cachegen_kv_page_v1(struct skippy_session * session, +diff --git a/src/skippy/tests/async_state.cpp b/src/skippy/tests/async_state.cpp +index 1937d38b7..972a8b25b 100644 +--- a/src/skippy/tests/async_state.cpp ++++ b/src/skippy/tests/async_state.cpp +@@ -71,6 +71,13 @@ void test_plain_restore_parity(skippy_session * source, skippy_session * target) + CHECK(skippy_export_kv_page(source, 0, layers, 0, 2, &page, payload.data(), payload.size(), &bytes, &error) == + SKIPPY_STATUS_OK); + ++ std::vector chunks; ++ for (size_t offset = 0; offset < payload.size();) { ++ const size_t count = std::min(17, payload.size() - offset); ++ chunks.push_back({payload.data() + offset, count}); ++ offset += count; ++ } ++ CHECK(chunks.size() > 1); + 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); +@@ -86,8 +93,23 @@ void test_plain_restore_parity(skippy_session * source, skippy_session * target) + 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); ++ if (attempt % 2 == 0) { ++ CHECK(skippy_import_kv_page(target, &page, payload.data(), payload.size(), &error) == SKIPPY_STATUS_OK); ++ CHECK(skippy_import_kv_page_chunks(target, &page, chunks.data(), chunks.size() - 1, &error) == ++ SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ error = nullptr; ++ CHECK(target->n_past == 2); ++ } else { ++ CHECK(skippy_import_kv_page_chunks(target, &page, chunks.data(), chunks.size(), &error) == SKIPPY_STATUS_OK); ++ } + CHECK(!source->stage_model->context_work_pending.load()); ++ std::vector restored(bytes); ++ size_t restored_bytes = 0; ++ skippy_kv_page_desc restored_page{}; ++ CHECK(skippy_export_kv_page(target, 0, layers, 0, 2, ++ &restored_page, restored.data(), restored.size(), &restored_bytes, &error) == SKIPPY_STATUS_OK); ++ CHECK(restored_bytes == bytes && restored == payload); + std::vector scores(selected); + skippy_token_score_request readout{ ids.data(), ids.size(), scores.data() }; + const llama_token token = 2; +-- +2.56.0 + diff --git a/llama_cpp/patches/0076--batch-native-kv-page-reads.patch b/llama_cpp/patches/0076--batch-native-kv-page-reads.patch new file mode 100644 index 00000000..ae7d9360 --- /dev/null +++ b/llama_cpp/patches/0076--batch-native-kv-page-reads.patch @@ -0,0 +1,109 @@ +From 67b190e636e2f867f0955c5bb0817bfb57bf4e6c Mon Sep 17 00:00:00 2001 +From: Skippy contributors +Date: Tue, 1 Dec 2026 13:25:16 +1100 +Subject: [PATCH] skippy: batch native KV page reads + +Skip backend fences for descriptor-only queries. Preserve the existing page +layout while batching device reads for bounded groups of spans. +--- + src/llama-kv-cache.cpp | 39 ++++++++++++++++++++++++++++++--------- + src/skippy/state.cpp | 6 +++++- + 2 files changed, 35 insertions(+), 10 deletions(-) + +diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp +index 6074b0a1d..34df70182 100644 +--- a/src/llama-kv-cache.cpp ++++ b/src/llama-kv-cache.cpp +@@ -2120,13 +2120,36 @@ bool llama_kv_cache::stage_export_kv_page( + } + + const auto cell_runs = llama_kv_cache_cell_runs(cell_idxs); +- char * dst = static_cast(output); ++ // Each span writes directly into its original place in the K, V, index ++ // layout. Submit bounded batches so CUDA can share a transfer fence. ++ constexpr size_t batch_capacity = 256; ++ std::array tensors; ++ std::array offsets; ++ std::array sizes; ++ std::array data_offsets; ++ size_t batch_size = 0; ++ size_t output_offset = 0; ++ const auto flush = [&]() { ++ if (batch_size != 0) { ++ ggml_backend_tensor_get_n(tensors.data(), output, offsets.data(), sizes.data(), data_offsets.data(), batch_size); ++ batch_size = 0; ++ } ++ }; ++ const auto read = [&](const ggml_tensor * tensor, size_t offset, size_t bytes) { ++ tensors[batch_size] = tensor; ++ offsets[batch_size] = offset; ++ sizes[batch_size] = bytes; ++ data_offsets[batch_size] = output_offset; ++ output_offset += bytes; ++ if (++batch_size == batch_capacity) { ++ flush(); ++ } ++ }; + for (const auto * layer : selected) { + auto * k = layer->k_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * k_row_bytes; +- ggml_backend_tensor_get(k, dst, static_cast(run.first) * k_row_bytes, run_bytes); +- dst += run_bytes; ++ read(k, static_cast(run.first) * k_row_bytes, run_bytes); + } + } + +@@ -2138,8 +2161,7 @@ bool llama_kv_cache::stage_export_kv_page( + auto * v = layer->v_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * v_row_bytes; +- ggml_backend_tensor_get(v, dst, static_cast(run.first) * v_row_bytes, run_bytes); +- dst += run_bytes; ++ read(v, static_cast(run.first) * v_row_bytes, run_bytes); + } + } + } else { +@@ -2153,8 +2175,7 @@ bool llama_kv_cache::stage_export_kv_page( + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * v_element_bytes; + const size_t src_offset = (static_cast(run.first) + static_cast(j) * cells.size()) * v_element_bytes; +- ggml_backend_tensor_get(v, dst, src_offset, run_bytes); +- dst += run_bytes; ++ read(v, src_offset, run_bytes); + } + } + } +@@ -2168,10 +2189,10 @@ bool llama_kv_cache::stage_export_kv_page( + auto * k_idx = layer->k_idx_stream[strm]; + for (const auto & run : cell_runs) { + const size_t run_bytes = static_cast(run.count) * k_idx_row_bytes; +- ggml_backend_tensor_get(k_idx, dst, static_cast(run.first) * k_idx_row_bytes, run_bytes); +- dst += run_bytes; ++ read(k_idx, static_cast(run.first) * k_idx_row_bytes, run_bytes); + } + } ++ flush(); + + return true; + } +diff --git a/src/skippy/state.cpp b/src/skippy/state.cpp +index bc842ee9e..72567ec90 100644 +--- a/src/skippy/state.cpp ++++ b/src/skippy/state.cpp +@@ -433,7 +433,11 @@ enum skippy_status skippy_export_kv_page( + skippy_set_error(out_error, SKIPPY_STATUS_INVALID_ARGUMENT, "session is required"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } +- session->ctx->synchronize(); ++ // A size query reads cell ownership and tensor layout maintained by the ++ // host. Only a payload export needs completed device writes. ++ if (output != nullptr) { ++ session->ctx->synchronize(); ++ } + std::string error; + bool ok = false; + if (auto * iswa = skippy_get_iswa_cache(session)) { +-- +2.56.0 + diff --git a/llama_cpp/patches/0077--export-resident-kv-in-bounded-slices.patch b/llama_cpp/patches/0077--export-resident-kv-in-bounded-slices.patch new file mode 100644 index 00000000..8a3b2af9 --- /dev/null +++ b/llama_cpp/patches/0077--export-resident-kv-in-bounded-slices.patch @@ -0,0 +1,231 @@ +From 18dc36591d4bed54b24709537bf4c7c139884268 Mon Sep 17 00:00:00 2001 +From: Skippy contributors +Date: Tue, 1 Dec 2026 13:25:16 +1100 +Subject: [PATCH] skippy: export resident KV in bounded slices + +Expose independent sliding-window components and recurrent byte ranges to +allow eviction and generation between checkpoint copy steps. +--- + include/skippy/state.h | 27 ++++++++ + src/skippy/resident_prefix.cpp | 91 ++++++++++++++++++++++++++- + src/skippy/tests/sampling_history.cpp | 29 +++++++++ + 3 files changed, 145 insertions(+), 2 deletions(-) + +diff --git a/include/skippy/state.h b/include/skippy/state.h +index 489d72a4c..be7323fb3 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -277,6 +277,24 @@ LLAMA_API enum skippy_status skippy_session_export_resident_kv_page( + size_t * out_bytes, + struct skippy_error ** out_error); + ++/** @brief Exports an absolute token range from one resident sliding-window page component. ++ * The selected range must still be resident in that component. ++ * The returned descriptor is a single page, with no component offset. ++ */ ++LLAMA_API enum skippy_status skippy_session_export_resident_kv_component( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ enum skippy_kv_page_component_role role, ++ 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, +@@ -286,6 +304,15 @@ LLAMA_API enum skippy_status skippy_session_export_resident_recurrent_state( + size_t * out_bytes, + struct skippy_error ** out_error); + ++/** @brief Copies exactly `bytes` starting at `offset` in a cache-owned recurrent checkpoint. */ ++LLAMA_API enum skippy_status skippy_session_copy_resident_recurrent_range( ++ struct skippy_session * session, ++ int32_t cache_seq_id, ++ size_t offset, ++ void * output, ++ size_t 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, +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +index 57b1d78ac..10127d4ab 100644 +--- a/src/skippy/resident_prefix.cpp ++++ b/src/skippy/resident_prefix.cpp +@@ -19,6 +19,7 @@ + #include + #include + #include ++#include + #include + + namespace { +@@ -433,10 +434,72 @@ enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session + } 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, ++enum skippy_status skippy_session_copy_resident_recurrent_range(skippy_session * session, ++ int32_t cache_seq_id, size_t offset, void * output, size_t bytes, skippy_error ** error) { ++ if (!output || bytes == 0) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent destination range is required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ 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 & prefixes = session->stage_model->resident_prefixes; ++ const auto found = prefixes.find(cache_seq_id); ++ if (found == prefixes.end() || offset > found->second.recurrent.size() ++ || bytes > found->second.recurrent.size() - offset) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "recurrent copy exceeds the saved prefix"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ std::memcpy(output, found->second.recurrent.data() + offset, bytes); ++ return skippy_success(error); ++ } catch (const std::exception & exception) { return native_error(error, exception); } ++} ++ ++} // extern "C" ++ ++namespace { ++ ++skippy_status export_resident_kv_component(skippy_session * session, int32_t cache_seq_id, ++ skippy_kv_page_component_role role, 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 (!descriptor || !bytes || ++ (role != SKIPPY_KV_PAGE_COMPONENT_BASE && role != SKIPPY_KV_PAGE_COMPONENT_SWA)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "valid component and descriptor outputs are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ auto * iswa = skippy_memory_iswa_adapter(session->ctx->get_memory()); ++ if (!iswa) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "runtime memory has no composite KV page"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ auto * kv = role == SKIPPY_KV_PAGE_COMPONENT_BASE ? iswa->get_base() : iswa->get_swa(); ++ if (output) { ++ session->ctx->synchronize(); ++ } ++ *descriptor = {}; ++ std::string message; ++ const bool exported = kv->stage_export_kv_page(cache_seq_id, layer_start, layer_end, token_start, ++ token_count, descriptor, output, capacity, bytes, message); ++ descriptor->codec = SKIPPY_KV_PAGE_CODEC_SINGLE_V1; ++ if (!exported) { ++ const auto status = *bytes > capacity ? SKIPPY_STATUS_BUFFER_TOO_SMALL : SKIPPY_STATUS_RUNTIME_ERROR; ++ skippy_set_error(error, status, message.c_str()); ++ return status; ++ } ++ if (!output) { ++ skippy_set_error(error, SKIPPY_STATUS_BUFFER_TOO_SMALL, "KV component output buffer is required"); ++ return SKIPPY_STATUS_BUFFER_TOO_SMALL; ++ } ++ return skippy_success(error); ++} ++ ++skippy_status 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, ++ std::optional role) { + if (bytes) { *bytes = 0; } + const auto valid = validate_session(session, cache_seq_id, error); + if (valid != SKIPPY_STATUS_OK) { return valid; } +@@ -449,6 +512,10 @@ enum skippy_status skippy_session_export_resident_kv_page(skippy_session * sessi + skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "resident KV export exceeds the saved prefix"); + return SKIPPY_STATUS_INVALID_ARGUMENT; + } ++ if (role) { ++ return export_resident_kv_component(session, cache_seq_id, *role, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error); ++ } + // This stack view neither claims an execution lane nor changes its + // state. Only the explicitly requested cold payload is materialized. + skippy_session view{}; +@@ -461,4 +528,24 @@ enum skippy_status skippy_session_export_resident_kv_page(skippy_session * sessi + } catch (const std::exception & exception) { return native_error(error, exception); } + } + ++} // namespace ++ ++extern "C" { ++ ++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) { ++ return export_resident_kv_page(session, cache_seq_id, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error, std::nullopt); ++} ++ ++enum skippy_status skippy_session_export_resident_kv_component(skippy_session * session, ++ int32_t cache_seq_id, skippy_kv_page_component_role role, 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) { ++ return export_resident_kv_page(session, cache_seq_id, layer_start, layer_end, ++ token_start, token_count, descriptor, output, capacity, bytes, error, role); ++} ++ + } // extern "C" +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index fea240bea..8764d65f8 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -826,6 +826,21 @@ void resident_prefix_ownership(skippy_model * model, bool typed = false) { + 0, prefix.size(), &persistent.page, persistent.payload.data(), kv_bytes, + &kv_bytes, &error), error); + CHECK(persistent.payload == source_page); ++ if (persistent.page.codec == SKIPPY_KV_PAGE_CODEC_ISWA_COMPOSITE_V1) { ++ for (const auto & component : persistent.page.components) { ++ skippy_kv_page_desc slice{}; ++ std::vector payload(component.payload_bytes); ++ size_t bytes = 0; ++ error = nullptr; ++ ok(skippy_session_export_resident_kv_component(a, cache_id, ++ static_cast(component.role), 0, persistent.layers, ++ component.token_start, component.token_count, &slice, payload.data(), payload.size(), ++ &bytes, &error), error); ++ CHECK(bytes == payload.size()); ++ CHECK(slice.codec == SKIPPY_KV_PAGE_CODEC_SINGLE_V1 && slice.component_count == 0); ++ CHECK(std::equal(payload.begin(), payload.end(), source_page.begin() + component.payload_offset)); ++ } ++ } + size_t recurrent_bytes = 0; + error = nullptr; + const auto recurrent_status = skippy_session_export_resident_recurrent_state(a, +@@ -839,6 +854,20 @@ void resident_prefix_ownership(skippy_model * model, bool typed = false) { + ok(skippy_session_export_resident_recurrent_state(a, cache_id, + retained_recurrent.data(), recurrent_bytes, &recurrent_bytes, &error), error); + CHECK(retained_recurrent == persistent.recurrent); ++ const size_t split = recurrent_bytes / 3; ++ CHECK(split > 0); ++ std::vector sliced_recurrent(recurrent_bytes); ++ error = nullptr; ++ ok(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ 0, sliced_recurrent.data(), split, &error), error); ++ error = nullptr; ++ ok(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ split, sliced_recurrent.data() + split, recurrent_bytes - split, &error), error); ++ CHECK(sliced_recurrent == retained_recurrent); ++ error = nullptr; ++ CHECK(skippy_session_copy_resident_recurrent_range(a, cache_id, ++ recurrent_bytes, sliced_recurrent.data(), 1, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(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); +-- +2.56.0 + diff --git a/llama_cpp/patches/model_support/0026-skippy-bump-abi-for-merged-runtime.patch b/llama_cpp/patches/model_support/0026-skippy-bump-abi-for-merged-runtime.patch new file mode 100644 index 00000000..ed82ca33 --- /dev/null +++ b/llama_cpp/patches/model_support/0026-skippy-bump-abi-for-merged-runtime.patch @@ -0,0 +1,16 @@ +From: Skippy contributors +Subject: [PATCH] skippy: distinguish merged runtime ABI + +--- +diff --git a/include/skippy/common.h b/include/skippy/common.h +--- 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 88 ++#define SKIPPY_ABI_VERSION_PATCH 94 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch b/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch new file mode 100644 index 00000000..e9511a92 --- /dev/null +++ b/llama_cpp/patches/model_support/0027-skippy-bump-abi-for-resident-cache-slices.patch @@ -0,0 +1,17 @@ +From: Skippy contributors +Subject: [PATCH] skippy: bump native ABI for resident cache slice exports + +--- +diff --git a/include/skippy/common.h b/include/skippy/common.h +index 465c7bf45..f3887a80e 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 94 ++#define SKIPPY_ABI_VERSION_PATCH 95 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) diff --git a/llama_cpp/patches/model_support/series b/llama_cpp/patches/model_support/series index 9e42b5b1..a2d89dff 100644 --- a/llama_cpp/patches/model_support/series +++ b/llama_cpp/patches/model_support/series @@ -23,3 +23,5 @@ 0023-muse-glimmer-retain-token-aware-turn-boundaries.patch 0024-models-preserve-checkpoint-layouts-and-head-scales.patch 0025-abi-distinguish-b12780-upstream-c-layouts.patch +0026-skippy-bump-abi-for-merged-runtime.patch +0027-skippy-bump-abi-for-resident-cache-slices.patch diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh index 7ec7dcc6..70d47600 100755 --- a/scripts/build-llama.sh +++ b/scripts/build-llama.sh @@ -604,6 +604,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 @@ -615,6 +616,7 @@ if [[ "$LLAMA_STAGE_BUILD_TESTS" == "ON" ]]; then skippy-selected-logits skippy-noalloc-graph-planning skippy-recurrent-retention + skippy-recurrent-copy skippy-renamed-multishard-planning skippy-stage-slice-plan skippy-verify-rollback diff --git a/scripts/ci-product.py b/scripts/ci-product.py index bd7c0fc0..2eb2e28d 100644 --- a/scripts/ci-product.py +++ b/scripts/ci-product.py @@ -13,7 +13,7 @@ from lib import ci_artifacts as artifacts from lib.ci_process import cancel_on_signal, capture, command from lib.ci_targets import require_host, targets, validate_native_identity -from lib.ci_smoke import artifact_smoke, smoke +from lib.ci_smoke import artifact_smoke, smoke, unpack_product from lib.ci_vulkan import toolchain as vulkan_toolchain @@ -162,14 +162,16 @@ def package(host, runtime, host_input, runtime_input): def main(): parser = argparse.ArgumentParser(description=__doc__) actions = parser.add_subparsers(dest="action", required=True) - for name in ("host", "runtime", "package", "smoke", "artifact-smoke"): + for name in ("host", "runtime", "package", "smoke", "artifact-smoke", "extract-runtime"): action = actions.add_parser(name) action.add_argument("id") if name == "package": action.add_argument("host_input", type=Path) action.add_argument("runtime_input", type=Path) - elif name in ("smoke", "artifact-smoke"): + elif name in ("smoke", "artifact-smoke", "extract-runtime"): action.add_argument("product_input", type=Path) + if name == "extract-runtime": + action.add_argument("output", type=Path) args = parser.parse_args() hosts, runtimes = targets() if args.action == "host": @@ -183,6 +185,9 @@ def main(): package(host, runtime, args.host_input, args.runtime_input) elif args.action == "artifact-smoke": artifact_smoke(host, runtime, args.product_input) + elif args.action == "extract-runtime": + unpack_product(host, runtime, args.product_input, args.output) + validate_native_identity(args.output / "native-runtimes" / args.id, host, runtime) else: smoke(host, runtime, args.product_input) diff --git a/scripts/inference-execute.py b/scripts/inference-execute.py index a8d43b87..c1aef33f 100644 --- a/scripts/inference-execute.py +++ b/scripts/inference-execute.py @@ -105,13 +105,20 @@ def execute(profile, key, mode): if available_memory() < sum(file["size"] for file in inputs["files"]) + 16 * 1024**3: raise ValueError("insufficient free unified memory for weights and runtime reserve") peer_context = PeerControl.from_environment(sha, key, profile) if mode == "split" else nullcontext() - with peer_context as peer: + with ( + peer_context as peer, + tempfile.TemporaryDirectory(prefix="skippy-inference-kv-", dir=Path.cwd()) as cache_dir, + ): if peer is not None: peer.phase = "preparing" model = admit(key, inputs) coordinate = f'{inputs["repo"]}@{inputs["revision"]}' context = 4096 if profile == "pr" else 65536 - args = ["target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300"] + # A persistent runner's default L3 can warm the next job's uncached probe. + args = [ + "target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300", + "--kv-cache-disk-dir", cache_dir, + ] if not worker: args += ["--speculative-strategy", "disabled", "--generation-concurrency", "1"] if mode == "split": diff --git a/scripts/lib/ci_smoke.py b/scripts/lib/ci_smoke.py index 51b8e0e0..78126e4c 100644 --- a/scripts/lib/ci_smoke.py +++ b/scripts/lib/ci_smoke.py @@ -16,10 +16,14 @@ from .ci_vulkan import preflight as vulkan_preflight -def verify_product(host, runtime, product_input, product): +def unpack_product(host, runtime, product_input, product): require_host(host) artifacts.unpack(product_input, product, check_space=True) artifacts.verify(product, "product", host["target"], runtime["id"]) + + +def verify_product(host, runtime, product_input, product): + unpack_product(host, runtime, product_input, product) binary = artifacts.binary(product.resolve(), host["os"]) env = environment() for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "DYLD_LIBRARY_PATH", diff --git a/scripts/lib/inference_baselines.py b/scripts/lib/inference_baselines.py index 932a4630..c5a56cfb 100644 --- a/scripts/lib/inference_baselines.py +++ b/scripts/lib/inference_baselines.py @@ -6,7 +6,7 @@ from .inference_nightly_metrics import metric_value -TOLERANCE = Decimal("0.05") +TOLERANCE = Decimal("0.01") DIRECTION = { "prefill_tok_s": 1, "decode_tok_s": 1, "output_tok_s": 1, "ttft_p95_ms": -1, "itl_p95_ms": -1, diff --git a/scripts/lib/inference_nightly_results.py b/scripts/lib/inference_nightly_results.py index 3e210bb9..6142db53 100644 --- a/scripts/lib/inference_nightly_results.py +++ b/scripts/lib/inference_nightly_results.py @@ -93,6 +93,6 @@ def nightly_run(root: Path, source, run_id, attempt, started_at, matrix_passed): "published": True, "configurations": configs, "note": ( "AgentX values are means of two trial summaries. Request counts are combined. " - "The performance tolerance and improvement threshold are 5%." + "The performance tolerance and improvement threshold are 1%." ), } diff --git a/scripts/prepare-llama.sh b/scripts/prepare-llama.sh index cc31b85f..93e8ef1c 100755 --- a/scripts/prepare-llama.sh +++ b/scripts/prepare-llama.sh @@ -102,36 +102,6 @@ is_partial_llama_workdir() { [[ -n "$(git -C "$LLAMA_WORKDIR" config --get extensions.partialClone 2>/dev/null || true)" ]] } -# Re-clone unless $LLAMA_WORKDIR is genuinely its own complete git repository. -# A bare `[[ ! -d "$LLAMA_WORKDIR/.git" ]]` check passes a partial/corrupt -# checkout (dir present, .git missing or incomplete) straight through to the -# `git -C` operations below; combined with discovery walking upward, that is -# what lets this script escape into an enclosing repo. A blobless checkout is -# also unsuitable: `git am --3way` must read both older upstream preimages and -# patch-result object IDs, which a promisor remote can incorrectly try to -# fetch from upstream. `rev-parse --git-dir` only succeeds for a real repo -# rooted at the workdir (discovery cannot escape past GIT_CEILING_DIRECTORIES -# set above). clone_llama_workdir rm -rf's first, so re-cloning this generated -# dependency worktree is safe. -if ! git -C "$LLAMA_WORKDIR" rev-parse --git-dir >/dev/null 2>&1 || - is_partial_llama_workdir; then - clone_llama_workdir -fi - -case "$MODE" in - pinned) - TARGET_SHA="$(tr -d '[:space:]' < "$PIN_FILE")" - ;; - latest) - git -C "$LLAMA_WORKDIR" remote set-url origin "$LLAMA_UPSTREAM_URL" - git_retry git -C "$LLAMA_WORKDIR" fetch origin master --tags - TARGET_SHA="$(git -C "$LLAMA_WORKDIR" rev-parse origin/master)" - ;; - *) - TARGET_SHA="$MODE" - ;; -esac - PATCHES=() while IFS= read -r patch; do PATCHES+=("$patch") @@ -273,6 +243,42 @@ compute_patch_digest() { PATCH_DIGEST="$(compute_patch_digest)" +if [[ "$MODE" == --patch-digest ]]; then + printf '%s\n' "$PATCH_DIGEST" + exit 0 +fi + +# Re-clone unless $LLAMA_WORKDIR is genuinely its own complete git repository. +# A bare `[[ ! -d "$LLAMA_WORKDIR/.git" ]]` check passes a partial/corrupt +# checkout (dir present, .git missing or incomplete) straight through to the +# `git -C` operations below; combined with discovery walking upward, that is +# what lets this script escape into an enclosing repo. A blobless checkout is +# also unsuitable: `git am --3way` must read both older upstream preimages and +# patch-result object IDs, which a promisor remote can incorrectly try to +# fetch from upstream. `rev-parse --git-dir` only succeeds for a real repo +# rooted at the workdir (discovery cannot escape past GIT_CEILING_DIRECTORIES +# set above). clone_llama_workdir rm -rf's first, so re-cloning this generated +# dependency worktree is safe. +if ! git -C "$LLAMA_WORKDIR" rev-parse --git-dir >/dev/null 2>&1 || + is_partial_llama_workdir; then + clone_llama_workdir +fi + +case "$MODE" in + pinned) + TARGET_SHA="$(tr -d '[:space:]' < "$PIN_FILE")" + ;; + latest) + git -C "$LLAMA_WORKDIR" remote set-url origin "$LLAMA_UPSTREAM_URL" + git_retry git -C "$LLAMA_WORKDIR" fetch origin master --tags + TARGET_SHA="$(git -C "$LLAMA_WORKDIR" rev-parse origin/master)" + ;; + *) + TARGET_SHA="$MODE" + ;; +esac + + # Runtime identity files must never enter a repair commit via git add -A. exclude_file="$(git -C "$LLAMA_WORKDIR" rev-parse --git-path info/exclude)" if [[ "$exclude_file" != /* ]]; then diff --git a/scripts/tests/inference_failure.py b/scripts/tests/inference_failure.py index 26fe4896..d3a105fa 100644 --- a/scripts/tests/inference_failure.py +++ b/scripts/tests/inference_failure.py @@ -61,17 +61,32 @@ def test_execute_captures_evidence_before_cleanup_and_actions_retains_it(self): patch("lib.inference_failure.resources", return_value={"memory.max": "unlimited"}): output, stream = Path(directory), io.StringIO() server = Mock(pid=123) + cache_dirs = [] + + def start(args, **_kwargs): + cache_dir = Path(args[args.index("--kv-cache-disk-dir") + 1]) + self.assertEqual(list(cache_dir.iterdir()), []) + self.assertFalse(cache_dir.is_relative_to(output)) + cache_dirs.append(cache_dir) + (cache_dir / "checkpoint").touch() + return server + def stop(_server): self.assertTrue((output / "failure-diagnostics.json").exists()) + self.assertTrue((cache_dirs[-1] / "checkpoint").is_file()) with patch.dict(execute.__globals__, { "authority": lambda: ("a" * 40, "GB10"), "plan": lambda *_: {"rows": [{"id": "fixture-standalone"}]}, "record": Mock(), "available_memory": lambda: 10**15, "fixture": lambda _: {"files": [{"size": 1}], "repo": "Fixture/Model", "revision": "b" * 40}, - "admit": Mock(), "port_available": Mock(), "start": lambda *_args, **_kw: server, + "admit": Mock(), "port_available": Mock(), "start": start, "stop": stop, "wait_for": Mock(side_effect=RuntimeError("CUDA startup exited")), - }), redirect_stdout(stream), self.assertRaisesRegex(RuntimeError, "CUDA startup exited"): - execute("pr", "fixture", "standalone") + }), redirect_stdout(stream): + for _ in range(2): + with self.assertRaisesRegex(RuntimeError, "CUDA startup exited"): + execute("pr", "fixture", "standalone") + self.assertFalse(cache_dirs[-1].exists()) + self.assertNotEqual(*cache_dirs) pilot = Mock() pilot.api.return_value = {"run_id": "run_test", "cursor": 1, "caught_up": True, "complete": True, "gap_at": None, "chunks": [{"seq": 1, "text": stream.getvalue()}]} diff --git a/scripts/tests/inference_nightly.py b/scripts/tests/inference_nightly.py index a9e28cdb..0907cde5 100644 --- a/scripts/tests/inference_nightly.py +++ b/scripts/tests/inference_nightly.py @@ -127,10 +127,11 @@ def test_matrix_preserves_existing_profiles_and_uses_pr_smoke(self): matrix("release", SOURCE, include_smoke=True) def test_metric_direction_and_exact_tolerance(self): - self.assertEqual(classify("decode_tok_s", 95, 100), "passed") - self.assertEqual(classify("decode_tok_s", 94.99, 100), "regressed") - self.assertEqual(classify("ttft_p95_ms", 105.01, 100), "regressed") - self.assertEqual(classify("ttft_p95_ms", 94, 100), "improved") + self.assertEqual(classify("decode_tok_s", 99, 100), "passed") + self.assertEqual(classify("decode_tok_s", 98.99, 100), "regressed") + self.assertEqual(classify("ttft_p95_ms", 101, 100), "passed") + self.assertEqual(classify("ttft_p95_ms", 101.01, 100), "regressed") + self.assertEqual(classify("ttft_p95_ms", 98.99, 100), "improved") def test_promotes_independent_improvement_and_never_walks_baseline_down(self): metrics = [ @@ -146,9 +147,9 @@ def run(number, sha, values, saved): "configurations": [config]}, saved) _, seeded = run(1, SOURCE, [100, 100], []) - _, passing = run(2, "b" * 40, [97, 97], seeded) + _, passing = run(2, "b" * 40, [99.5, 99.5], seeded) self.assertEqual(passing[0]["value"], 100) - self.assertEqual(passing[0]["latest_passing"]["value"], 97) + self.assertEqual(passing[0]["latest_passing"]["value"], 99.5) failed, next_baselines = run(3, "d" * 40, [94, 110], passing) self.assertEqual(failed["outcome"], "failed") self.assertEqual({item["metric"]: item["value"] for item in next_baselines}, diff --git a/tools/xtask/Cargo.toml b/tools/xtask/Cargo.toml new file mode 100644 index 00000000..a7615aeb --- /dev/null +++ b/tools/xtask/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "xtask" +version.workspace = true +edition.workspace = true +publish = false +description = "Skippy KV cache qualification" + +[dependencies] +process-supervision = { package = "skippy-subprocess", path = "../process-supervision" } +skippy-model-artifact = { path = "../../crates/skippy-model-artifact" } +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +hex = "0.4" +tar = "0.4" +tempfile = "3" + +[lints] +workspace = true diff --git a/tools/xtask/src/artifact.rs b/tools/xtask/src/artifact.rs new file mode 100644 index 00000000..4382442c --- /dev/null +++ b/tools/xtask/src/artifact.rs @@ -0,0 +1,20 @@ +//! File identity used by native build and packaging adapters. +use crate::command::DynResult; +use sha2::{Digest, Sha256}; +use std::{io::Read, path::Path}; + +pub(crate) fn sha256(path: &Path) -> DynResult { + digest(std::fs::File::open(path)?) +} +pub(crate) fn digest(mut reader: impl Read) -> DynResult { + let mut hash = Sha256::new(); + let mut buffer = [0_u8; 65536]; + loop { + let count = reader.read(&mut buffer)?; + if count == 0 { + break; + } + hash.update(&buffer[..count]); + } + Ok(hex::encode(hash.finalize())) +} diff --git a/tools/xtask/src/cache_qualification.rs b/tools/xtask/src/cache_qualification.rs new file mode 100644 index 00000000..bcd0bbcf --- /dev/null +++ b/tools/xtask/src/cache_qualification.rs @@ -0,0 +1,410 @@ +//! Run each GPU cache fixture independently and retain every outcome. + +use crate::{ + artifact, + command::DynResult, + execution::{self, strings}, + huggingface, +}; +use serde::{Deserialize, Serialize}; +use skippy_model_artifact::kv_fixtures::{KvFixture, KvFixtureManifest, valid_sha256}; +use std::{ + collections::BTreeMap, + env, fs, + path::{Path, PathBuf}, +}; + +pub(crate) const MANIFEST: &str = "crates/skippy-model-artifact/src/kv_fixtures/models.json"; +const CONVERSATIONS: [&str; 3] = ["first_follow_up", "second_follow_up", "divergent_tail"]; +const STRUCTURED: [&str; 3] = ["json_schema", "named_tool", "long_retrieval"]; +const CELL_TIMEOUT_SECONDS: u64 = 1800; +const TEST_CASE: &str = "frontend::tests::cache_qualification::cross_tier"; + +mod packaged; +mod prepare; +pub(crate) mod verify; + +const SUMMARY_VERSION: u32 = 2; + +#[derive(Clone, Copy)] +pub(crate) enum Backend { + Metal, + Cuda, + CudaArm64, +} + +impl Backend { + fn parse(name: &str) -> DynResult { + match name { + "metal" => Ok(Self::Metal), + "cuda" => Ok(Self::Cuda), + "cuda-arm64" => Ok(Self::CudaArm64), + _ => Err(format!("unknown cache qualification backend {name:?}").into()), + } + } + + fn profile(self) -> &'static str { + match self { + Self::Metal => "macos-arm64-metal", + Self::Cuda => "linux-x86_64-cuda", + Self::CudaArm64 => "linux-aarch64-cuda", + } + } + + fn recipe(self) -> &'static str { + match self { + Self::Metal => "cache-correctness-metal", + Self::Cuda | Self::CudaArm64 => "cache-correctness-cuda", + } + } + + fn name(self) -> &'static str { + match self { + Self::Metal => "metal", + Self::Cuda => "cuda", + Self::CudaArm64 => "cuda-arm64", + } + } + + fn runtime_backend(self) -> &'static str { + match self { + Self::Metal => "metal", + Self::Cuda | Self::CudaArm64 => "cuda", + } + } +} + +pub(crate) fn read_manifest(body: &str) -> DynResult { + let manifest = KvFixtureManifest::parse(body).map_err(|error| format!("{error:#}"))?; + if manifest + .models + .iter() + .any(|row| !row.required_sidecars.is_empty()) + { + return Err("cache qualification does not support attaching model sidecars".into()); + } + Ok(manifest) +} + +struct Inputs { + fixtures: Fixtures, + reference: Option, + runner: TestRunner, +} + +enum TestRunner { + Cargo(PathBuf), + Packaged { binary: PathBuf, runtime: PathBuf }, +} + +enum Fixtures { + Directory(PathBuf), + HuggingFace, +} + +impl Fixtures { + fn resolve(&self, model: &KvFixture) -> DynResult { + let path = match self { + Self::Directory(directory) => directory.join(&model.file), + Self::HuggingFace => { + huggingface::download(&model.repo, &model.revision, &[&model.file], 1800)? + } + }; + if !path.is_file() { + return Err(format!("missing pinned fixture {}", path.display()).into()); + } + Ok(path) + } +} + +impl Inputs { + fn load(backend: Backend, prepare_builds: bool, download: bool) -> DynResult { + let fixtures = if download { + Fixtures::HuggingFace + } else { + Fixtures::Directory(existing_input( + "SKIPPY_CACHE_QUAL_FIXTURE_DIR", + Path::is_dir, + )?) + }; + let native_build = if prepare_builds { + prepare::build_native(backend)? + } else { + existing_input("LLAMA_STAGE_BUILD_DIR", Path::is_dir)? + }; + Ok(Self { + fixtures, + reference: prepare::diagnostic_reference()?, + runner: TestRunner::Cargo(native_build), + }) + } +} + +fn existing_input(name: &str, valid: impl FnOnce(&Path) -> bool) -> DynResult { + let path = PathBuf::from(env::var_os(name).ok_or_else(|| format!("set {name}"))?); + if !path.is_absolute() || !valid(&path) { + return Err(format!("{name} must name an existing absolute path").into()); + } + Ok(path.canonicalize()?) +} + +#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Status { + Pass, + Fail, +} + +#[derive(Deserialize)] +struct Report { + schema_version: u32, + qualification_contract: String, + status: Status, + backend: String, + fixture: KvFixture, + model_sha256: Option, + skippy_binary_sha256: Option, + reference: Option, + error: Option, + conversation_results: BTreeMap, + structured_results: BTreeMap, + template_result: Option, +} + +#[derive(Deserialize)] +struct ReferenceIdentity { + binary_sha256: String, +} + +#[derive(Deserialize)] +struct ScenarioReport { + status: Status, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Cell { + family: String, + status: Status, + report: Option, + report_sha256: Option, + error: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Summary { + schema_version: u32, + source_head: String, + source_tree_clean: bool, + fixture_manifest_sha256: String, + profile: String, + status: Status, + cells: Vec, +} + +pub fn run(args: &[String]) -> DynResult<()> { + let (backend, output, prepare_builds, download) = match args { + [command, variant, profile, product, output] if command == "package" => { + return packaged::run(variant, profile, Path::new(product), Path::new(output)); + } + [command, backend, source, directory] if command == "verify" => { + return verify::run(Backend::parse(backend)?, source, Path::new(directory)); + } + [backend, output] => (backend, output, false, false), + [backend, output, flag] if flag == "--build" => (backend, output, true, false), + [backend, output, build, hf] if build == "--build" && hf == "--hf" => { + (backend, output, true, true) + } + _ => { + return Err( + "usage: cache-qualification BACKEND FRESH_REPORT_DIR [--build [--hf]] | package VARIANT short|full PRODUCT_DIR FRESH_REPORT_DIR | verify BACKEND SOURCE_SHA REPORT_DIR".into(), + ); + } + }; + let backend = Backend::parse(backend)?; + let output = Path::new(output); + fs::create_dir(output)?; + let output = output.canonicalize()?; + let manifest_bytes = fs::read_to_string(MANIFEST)?; + let manifest = read_manifest(&manifest_bytes)?; + let start = verify::Source::capture(&output)?; + let inputs = Inputs::load(backend, prepare_builds, download); + let cells = manifest + .models + .iter() + .map(|model| match &inputs { + Ok(inputs) => run_cell(backend, &output, model, inputs), + Err(error) => failure(model, None, None, error.to_string()), + }) + .collect::>(); + let end = verify::Source::capture(&output)?; + write_summary(backend, &output, start, end, &manifest_bytes, cells) +} + +fn write_summary( + backend: Backend, + output: &Path, + start: verify::Source, + end: verify::Source, + manifest: &str, + cells: Vec, +) -> DynResult<()> { + let status = if cells.iter().all(|row| row.status == Status::Pass) { + Status::Pass + } else { + Status::Fail + }; + let source_tree_clean = start.clean && end.clean && start.head == end.head; + let summary = Summary { + schema_version: SUMMARY_VERSION, + source_head: start.head, + source_tree_clean, + fixture_manifest_sha256: artifact::digest(manifest.as_bytes())?, + profile: backend.profile().into(), + status, + cells, + }; + let report_path = output.join("batch-result.json"); + serde_json::to_writer_pretty(fs::File::create(&report_path)?, &summary)?; + println!( + "Cache qualification matrix report {}", + report_path.display() + ); + if status == Status::Fail { + return Err("one or more cache qualification cells failed".into()); + } + Ok(()) +} + +fn run_cell(backend: Backend, output: &Path, model: &KvFixture, inputs: &Inputs) -> Cell { + let fixture = match inputs.fixtures.resolve(model) { + Ok(path) => path, + Err(error) => return failure(model, None, None, error.to_string()), + }; + let family = model.family.as_str(); + let directory = output.join(family); + let relative_report = PathBuf::from(family).join("result.json"); + let mut environment = vec![ + ("SKIPPY_CACHE_QUAL_BACKEND", backend.name().into()), + ("LLAMA_STAGE_BACKEND", backend.runtime_backend().into()), + ("SKIPPY_CACHE_QUAL_FAMILY", family.into()), + ( + "SKIPPY_CACHE_QUAL_MODEL", + fixture.to_string_lossy().into_owned(), + ), + ( + "SKIPPY_CACHE_QUAL_REPORT_DIR", + directory.to_string_lossy().into_owned(), + ), + ]; + if let Some(reference) = &inputs.reference { + environment.push(( + "SKIPPY_CACHE_QUAL_LLAMA_SERVER", + reference.to_string_lossy().into_owned(), + )); + } + let result = match &inputs.runner { + TestRunner::Cargo(native_build) => { + environment.push(( + "LLAMA_STAGE_BUILD_DIR", + native_build.to_string_lossy().into_owned(), + )); + execution::run( + "just", + &strings(&[backend.recipe()]), + &environment, + CELL_TIMEOUT_SECONDS, + ) + } + TestRunner::Packaged { binary, runtime } => { + packaged::run_test(binary, runtime, TEST_CASE, environment) + } + }; + let path = output.join(&relative_report); + let bytes = fs::read(&path).ok(); + let report_sha256 = match bytes.as_deref().map(artifact::digest).transpose() { + Ok(digest) => digest, + Err(error) => return failure(model, Some(relative_report), None, error.to_string()), + }; + let evidence = bytes.as_deref().map(serde_json::from_slice::); + let path = path.is_file().then_some(relative_report); + match assess_report(backend, model, result, evidence) { + Ok(()) => Cell { + family: family.into(), + status: Status::Pass, + report: path, + report_sha256, + error: None, + }, + Err(error) => failure(model, path, report_sha256, error.to_string()), + } +} + +fn assess_report( + backend: Backend, + model: &KvFixture, + child: DynResult<()>, + evidence: Option>, +) -> DynResult<()> { + let report = match evidence { + Some(evidence) => evidence?, + None => { + child?; + return Err("qualification exited without a result report".into()); + } + }; + if report.schema_version != 11 + || report.qualification_contract != "behavior_and_reuse_v1" + || report.backend != backend.profile() + || report.fixture != *model + { + return Err("qualification result identity does not match the requested cell".into()); + } + if report.status == Status::Fail { + return Err(report + .error + .unwrap_or_else(|| "qualification reported a failure".into()) + .into()); + } + if report.error.is_some() + || report.model_sha256.as_deref() != Some(model.sha256.as_str()) + || !report + .skippy_binary_sha256 + .as_deref() + .is_some_and(valid_sha256) + || !all_scenarios_pass(&report.conversation_results, &CONVERSATIONS) + || !all_scenarios_pass(&report.structured_results, &STRUCTURED) + || report.template_result != Some(Status::Pass) + { + return Err("passing report lacks complete passing scenario evidence".into()); + } + child +} + +fn all_scenarios_pass(results: &BTreeMap, names: &[&str]) -> bool { + results.len() == names.len() + && names.iter().all(|name| { + results + .get(*name) + .is_some_and(|row| row.status == Status::Pass) + }) +} + +fn failure( + model: &KvFixture, + report: Option, + report_sha256: Option, + error: String, +) -> Cell { + Cell { + family: model.family.as_str().into(), + status: Status::Fail, + report, + report_sha256, + error: Some(error), + } +} + +#[cfg(test)] +mod tests; diff --git a/tools/xtask/src/cache_qualification/packaged.rs b/tools/xtask/src/cache_qualification/packaged.rs new file mode 100644 index 00000000..e273466a --- /dev/null +++ b/tools/xtask/src/cache_qualification/packaged.rs @@ -0,0 +1,181 @@ +use super::{ + Backend, Fixtures, Inputs, MANIFEST, Report, Status, TestRunner, artifact, execution, prepare, + read_manifest, run_cell, strings, verify, write_summary, +}; +use crate::command::{DynResult, write_json_file}; +use serde::Deserialize; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +const SMOKE_CASE: &str = "frontend::tests::cache_qualification::smoke::packaged_cache_smoke"; + +pub(super) fn run(variant: &str, profile: &str, input: &Path, output: &Path) -> DynResult<()> { + let (backend, full) = match (variant, profile) { + ("darwin-aarch64-metal", "short") => (Backend::Metal, false), + ("linux-x86_64-cuda13", "short") => (Backend::Cuda, false), + ("linux-aarch64-cuda13", "short") => (Backend::CudaArm64, false), + ("darwin-aarch64-metal", "full") => (Backend::Metal, true), + ("linux-aarch64-cuda13", "full") => (Backend::CudaArm64, true), + _ => return Err(format!("unsupported KV profile {profile:?} for {variant:?}").into()), + }; + let temp = tempfile::tempdir()?; + let product = temp.path().join("product"); + execution::run( + "just", + &strings(&[ + "ci-extract-runtime", + variant, + &input.to_string_lossy(), + &product.to_string_lossy(), + ]), + &[], + 600, + )?; + let runtime = product.join("native-runtimes"); + let variant_dir = runtime.join(variant); + + fs::create_dir(output)?; + let output = output.canonicalize()?; + let start = verify::Source::capture(&output)?; + write_json_file( + &output.join("runtime.json"), + &serde_json::json!({ + "source": start.head, + "variant": variant, + "profile": profile, + "manifest_sha256": artifact::sha256(&variant_dir.join("manifest.json"))? + }), + )?; + let binary = compile_test()?; + let manifest = fs::read_to_string(MANIFEST)?; + let fixtures = read_manifest(&manifest)?; + if !full { + let model = fixtures + .models + .iter() + .find(|model| model.family.as_str() == "dense-attention") + .ok_or("missing the pinned dense-attention KV fixture")?; + let fixture = Fixtures::HuggingFace.resolve(model)?; + let report_dir = output.join(model.family.as_str()); + run_test( + &binary, + &runtime, + SMOKE_CASE, + vec![ + ("SKIPPY_CACHE_QUAL_BACKEND", backend.name().into()), + ( + "SKIPPY_CACHE_QUAL_MODEL", + fixture.to_string_lossy().into_owned(), + ), + ( + "SKIPPY_CACHE_QUAL_REPORT_DIR", + report_dir.to_string_lossy().into_owned(), + ), + ], + )?; + let report: Report = + serde_json::from_slice(&fs::read(report_dir.join("smoke-result.json"))?)?; + if report.schema_version != 11 + || report.qualification_contract != "behavior_and_reuse_v1" + || report.status != Status::Pass + || report.backend != backend.profile() + || report.fixture != *model + { + return Err( + "missing passing KV smoke evidence for the selected fixture and backend".into(), + ); + } + return Ok(()); + } + + let inputs = Inputs { + fixtures: Fixtures::HuggingFace, + reference: prepare::diagnostic_reference()?, + runner: TestRunner::Packaged { binary, runtime }, + }; + let cells = fixtures + .models + .iter() + .map(|model| run_cell(backend, &output, model, &inputs)) + .collect(); + let end = verify::Source::capture(&output)?; + write_summary(backend, &output, start, end, &manifest, cells) +} + +pub(super) fn run_test( + binary: &Path, + runtime: &Path, + test: &str, + mut environment: Vec<(&str, String)>, +) -> DynResult<()> { + environment.push(( + "SKIPPY_NATIVE_RUNTIME_BUNDLE_DIR", + runtime.to_string_lossy().into_owned(), + )); + execution::run( + &binary.to_string_lossy(), + &strings(&[test, "--ignored", "--exact", "--nocapture"]), + &environment, + if test == SMOKE_CASE { + 600 + } else { + super::CELL_TIMEOUT_SECONDS + }, + ) +} + +fn compile_test() -> DynResult { + let messages = execution::capture_for( + "just", + &strings(&[ + "with-lld", + "cargo", + "test", + "--locked", + "-p", + "skippy-serving", + "--features", + "dynamic-native-runtime", + "--lib", + "--no-run", + "--message-format=json", + ]), + &[], + 1800, + )?; + test_executable(&messages) +} + +#[derive(Deserialize)] +struct CargoMessage { + reason: String, + target: Option, + executable: Option, +} + +#[derive(Deserialize)] +struct CargoTarget { + name: String, + kind: Vec, +} + +fn test_executable(messages: &str) -> DynResult { + let paths = messages + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|message| { + message.reason == "compiler-artifact" + && message + .target + .as_ref() + .is_some_and(|target| target.name == "skippy_serving" && target.kind == ["lib"]) + }) + .filter_map(|message| message.executable) + .collect::>(); + match paths.as_slice() { + [path] => Ok(path.canonicalize()?), + _ => Err("expected exactly one skippy-serving test executable".into()), + } +} diff --git a/tools/xtask/src/cache_qualification/prepare.rs b/tools/xtask/src/cache_qualification/prepare.rs new file mode 100644 index 00000000..d467c336 --- /dev/null +++ b/tools/xtask/src/cache_qualification/prepare.rs @@ -0,0 +1,53 @@ +use super::{Backend, execution, existing_input, strings}; +use crate::command::DynResult; +use std::{ + env, + path::{Path, PathBuf}, +}; + +pub(super) fn build_native(backend: Backend) -> DynResult { + let mut environment = vec![ + ("LLAMA_STAGE_BACKEND", backend.runtime_backend().to_owned()), + ("LLAMA_STAGE_LINK_MODE", "static".into()), + ]; + environment.extend(native_environment(backend)?); + if env::var_os("LLAMA_STAGE_BUILD_DIR").is_some() { + return existing_input("LLAMA_STAGE_BUILD_DIR", Path::is_dir); + } + execution::run("just", &strings(&["llama-build"]), &environment, 7200)?; + let directory = execution::capture( + "just", + &strings(&["cache-correctness-native-dir"]), + &environment, + )?; + Ok(Path::new(directory.trim()).canonicalize()?) +} + +pub(super) fn diagnostic_reference() -> DynResult> { + env::var_os("SKIPPY_CACHE_QUAL_LLAMA_SERVER") + .map(|_| existing_input("SKIPPY_CACHE_QUAL_LLAMA_SERVER", Path::is_file)) + .transpose() +} + +fn native_environment(backend: Backend) -> DynResult> { + let variant = match backend { + Backend::Metal => return Ok(Vec::new()), + Backend::Cuda => "linux-x86_64-cuda13", + Backend::CudaArm64 => "linux-aarch64-cuda13", + }; + let plan = execution::output("just", &strings(&["ci-plan"]))?; + let plan: serde_json::Value = serde_json::from_str(&plan)?; + let runtimes = plan["runtimes"]["include"] + .as_array() + .ok_or("CI plan omitted runtimes")?; + let toolkit = runtimes + .iter() + .find(|row| row["id"] == variant) + .and_then(|row| row["toolkit"].as_str()) + .filter(|value| !value.is_empty()) + .ok_or("CI plan omitted the CUDA toolkit")?; + Ok(vec![ + ("SKIPPY_CUDA_VERSION", toolkit.to_owned()), + ("LLAMA_STAGE_CUDA_ARCHITECTURES", "native".into()), + ]) +} diff --git a/tools/xtask/src/cache_qualification/tests.rs b/tools/xtask/src/cache_qualification/tests.rs new file mode 100644 index 00000000..d8caa552 --- /dev/null +++ b/tools/xtask/src/cache_qualification/tests.rs @@ -0,0 +1,85 @@ +use super::*; + +#[test] +fn batch_admits_only_all_four_distinct_safe_fixture_paths() { + let body = include_str!("../../../../crates/skippy-model-artifact/src/kv_fixtures/models.json"); + assert!(read_manifest(body).is_ok()); + assert!(read_manifest(&body.replace("hybrid-moe", "attention-moe")).is_err()); + assert!(read_manifest(&body.replace("Qwen3-4B-Q4_K_M.gguf", "../model.gguf")).is_err()); +} + +#[test] +fn a_passing_child_cannot_hide_missing_or_mismatched_evidence() { + let manifest = KvFixtureManifest::bundled().unwrap(); + let model = &manifest.models[0]; + assert!(assess_report(Backend::Metal, model, Ok(()), None).is_err()); + let report = |status, backend: &str| Report { + schema_version: 11, + qualification_contract: "behavior_and_reuse_v1".into(), + status, + backend: backend.into(), + fixture: KvFixtureManifest::bundled().unwrap().models.remove(0), + model_sha256: Some(model.sha256.clone()), + skippy_binary_sha256: Some("f".repeat(64)), + reference: None, + error: (status == Status::Fail).then(|| "a measured difference".into()), + conversation_results: CONVERSATIONS + .into_iter() + .map(|name| (name.into(), ScenarioReport { status })) + .collect(), + structured_results: STRUCTURED + .into_iter() + .map(|name| (name.into(), ScenarioReport { status })) + .collect(), + template_result: Some(status), + }; + let evidence = |status, backend: &str| Some(Ok(report(status, backend))); + let metal = Backend::Metal.profile(); + assert!(assess_report(Backend::Metal, model, Ok(()), evidence(Status::Pass, metal)).is_ok()); + assert!(assess_report(Backend::Cuda, model, Ok(()), evidence(Status::Pass, metal)).is_err()); + let error = assess_report( + Backend::Metal, + model, + Err("child failed".into()), + evidence(Status::Fail, metal), + ) + .unwrap_err(); + assert_eq!(error.to_string(), "a measured difference"); + let mut incomplete = report(Status::Pass, metal); + incomplete.conversation_results.remove("divergent_tail"); + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(incomplete))).is_err()); + let mut failed = report(Status::Pass, metal); + failed + .conversation_results + .get_mut("divergent_tail") + .unwrap() + .status = Status::Fail; + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(failed))).is_err()); + assert!( + assess_report( + Backend::Metal, + model, + Err("child failed".into()), + evidence(Status::Pass, metal), + ) + .is_err() + ); + let mut missing = report(Status::Pass, metal); + missing.structured_results.remove("long_retrieval"); + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(missing))).is_err()); + let mut missing_template = report(Status::Pass, metal); + missing_template.template_result = None; + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(missing_template))).is_err()); + let mut old_contract = report(Status::Pass, metal); + old_contract.schema_version = 10; + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(old_contract))).is_err()); + let mut wrong_contract = report(Status::Pass, metal); + wrong_contract.qualification_contract = "numerical_v10".into(); + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(wrong_contract))).is_err()); + let mut stale = report(Status::Pass, metal); + stale.fixture.revision = "e".repeat(40); + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(stale))).is_err()); + let mut foreign = report(Status::Pass, metal); + foreign.model_sha256 = Some("e".repeat(64)); + assert!(assess_report(Backend::Metal, model, Ok(()), Some(Ok(foreign))).is_err()); +} diff --git a/tools/xtask/src/cache_qualification/verify.rs b/tools/xtask/src/cache_qualification/verify.rs new file mode 100644 index 00000000..096eff75 --- /dev/null +++ b/tools/xtask/src/cache_qualification/verify.rs @@ -0,0 +1,238 @@ +use super::{ + Backend, MANIFEST, SUMMARY_VERSION, Status, Summary, artifact, assess_report, execution, + read_manifest, strings, +}; +use crate::command::DynResult; +use skippy_model_artifact::kv_fixtures::{KvFixtureManifest, valid_sha256}; +use std::{ + collections::BTreeSet, + fs, + path::{Path, PathBuf}, +}; + +pub(super) struct Source { + pub(super) head: String, + pub(super) clean: bool, +} + +impl Source { + pub(super) fn capture(output: &Path) -> DynResult { + let head = execution::output("git", &strings(&["rev-parse", "HEAD"]))?; + let root = execution::output("git", &strings(&["rev-parse", "--show-toplevel"]))?; + let mut args = strings(&[ + "status", + "--porcelain=v1", + "--untracked-files=all", + "--", + ".", + ]); + if let Ok(relative) = output.strip_prefix(Path::new(root.trim())) { + let relative = relative + .to_str() + .ok_or("report directory must be Unicode")?; + args.push(format!(":(top,exclude,literal){relative}")); + } + let clean = execution::output("git", &args)?.trim().is_empty(); + Ok(Self { + head: head.trim().into(), + clean, + }) + } +} + +pub(super) fn run(backend: Backend, source: &str, directory: &Path) -> DynResult<()> { + let manifest = fs::read_to_string(MANIFEST)?; + let digest = artifact::digest(manifest.as_bytes())?; + let fixtures = read_manifest(&manifest)?; + let directory = directory.canonicalize()?; + let summary: Summary = + serde_json::from_slice(&read_file(&directory.join("batch-result.json"))?)?; + validate_summary(backend, source, &digest, &fixtures, &summary)?; + let staging = tempfile::tempdir()?; + for model in &fixtures.models { + let family = model.family.as_str(); + let cell = summary + .cells + .iter() + .find(|cell| cell.family == family) + .ok_or_else(|| format!("missing correctness cell {family}"))?; + let evidence_directory = directory.join(family); + if !evidence_directory.symlink_metadata()?.file_type().is_dir() { + return Err(format!("expected a regular correctness directory for {family}").into()); + } + let report = read_file(&evidence_directory.join("result.json"))?; + let observed_sha = artifact::digest(report.as_slice())?; + if cell.report_sha256.as_deref() != Some(&observed_sha) { + return Err(format!("changed correctness report for {family}").into()); + } + let measured = serde_json::from_slice::(&report)?; + validate_report_binaries(&measured)?; + assess_report(backend, model, Ok(()), Some(Ok(measured)))?; + let staged = staging.path().join(format!("{family}.json")); + fs::write(&staged, report)?; + let staged = staged + .to_str() + .ok_or("temporary report path must be Unicode")?; + execution::run( + "just", + &strings(&["cache-correctness-verify", backend.name(), staged]), + &[("CARGO_NET_OFFLINE", "true".into())], + 1800, + ) + .map_err(|error| { + format!("{family} correctness evidence failed offline validation: {error}") + })?; + } + println!( + "Verified {} correctness evidence for {source}", + backend.name() + ); + Ok(()) +} + +fn validate_report_binaries(report: &super::Report) -> DynResult<()> { + report + .skippy_binary_sha256 + .as_deref() + .filter(|hash| valid_sha256(hash)) + .ok_or("missing correctness test executable digest")?; + if report + .reference + .as_ref() + .is_some_and(|reference| !valid_sha256(&reference.binary_sha256)) + { + return Err("invalid diagnostic reference executable digest".into()); + } + Ok(()) +} + +fn validate_summary( + backend: Backend, + source: &str, + manifest_sha256: &str, + fixtures: &KvFixtureManifest, + summary: &Summary, +) -> DynResult<()> { + if source.len() != 40 + || !source + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + || !source.bytes().any(|byte| byte != b'0') + || summary.schema_version != SUMMARY_VERSION + || summary.source_head != source + || !summary.source_tree_clean + || summary.profile != backend.profile() + || summary.fixture_manifest_sha256 != manifest_sha256 + { + return Err( + "correctness matrix identity does not match the requested source and profile".into(), + ); + } + if summary.status != Status::Pass || summary.cells.len() != fixtures.models.len() { + return Err("correctness matrix lacks a complete passing roster".into()); + } + let expected: BTreeSet<_> = fixtures + .models + .iter() + .map(|model| model.family.as_str()) + .collect(); + let mut families = BTreeSet::new(); + for cell in &summary.cells { + let expected_path = PathBuf::from(&cell.family).join("result.json"); + if !expected.contains(cell.family.as_str()) + || !families.insert(cell.family.as_str()) + || cell.status != Status::Pass + || cell.error.is_some() + || cell.report.as_ref() != Some(&expected_path) + || !cell.report_sha256.as_deref().is_some_and(valid_sha256) + { + return Err(format!("invalid correctness matrix cell {}", cell.family).into()); + } + } + Ok(()) +} + +fn read_file(path: &Path) -> DynResult> { + if !path.symlink_metadata()?.file_type().is_file() { + return Err(format!("expected a regular evidence file {}", path.display()).into()); + } + Ok(fs::read(path)?) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cache_qualification::Cell; + + #[test] + fn offline_verification_requires_the_test_digest_and_valid_optional_diagnostics() { + let model = KvFixtureManifest::bundled().unwrap().models.remove(0); + let mut report = super::super::Report { + schema_version: 11, + qualification_contract: "behavior_and_reuse_v1".into(), + status: Status::Pass, + backend: Backend::Metal.profile().into(), + model_sha256: Some(model.sha256.clone()), + fixture: model, + error: None, + skippy_binary_sha256: Some("a".repeat(64)), + reference: Some(super::super::ReferenceIdentity { + binary_sha256: "b".repeat(64), + }), + conversation_results: Default::default(), + structured_results: Default::default(), + template_result: None, + }; + assert!(validate_report_binaries(&report).is_ok()); + report.skippy_binary_sha256 = Some("0".repeat(64)); + assert!(validate_report_binaries(&report).is_err()); + report.skippy_binary_sha256 = Some("a".repeat(64)); + report.reference = None; + assert!(validate_report_binaries(&report).is_ok()); + } + + #[test] + fn matrix_admission_requires_a_clean_pinned_source_and_unique_matching_cells() { + let source = "1".repeat(40); + let digest = "a".repeat(64); + let manifest = KvFixtureManifest::bundled().unwrap(); + let mut summary = Summary { + schema_version: SUMMARY_VERSION, + source_head: source.clone(), + source_tree_clean: true, + fixture_manifest_sha256: digest.clone(), + profile: Backend::Metal.profile().into(), + status: Status::Pass, + cells: manifest + .models + .iter() + .map(|model| { + let family = model.family.as_str(); + Cell { + family: family.into(), + status: Status::Pass, + report: Some(PathBuf::from(family).join("result.json")), + report_sha256: Some("b".repeat(64)), + error: None, + } + }) + .collect(), + }; + let validate = |summary: &Summary| { + validate_summary(Backend::Metal, &source, &digest, &manifest, summary) + }; + assert!(validate(&summary).is_ok()); + assert!(validate_summary(Backend::Cuda, &source, &digest, &manifest, &summary).is_err()); + summary.source_tree_clean = false; + assert!(validate(&summary).is_err()); + summary.source_tree_clean = true; + summary.source_head = "2".repeat(40); + assert!(validate(&summary).is_err()); + summary.source_head = source.clone(); + summary.cells[1].report = Some(PathBuf::from("../external.json")); + assert!(validate(&summary).is_err()); + summary.cells[1].family = summary.cells[0].family.clone(); + summary.cells[1].report = summary.cells[0].report.clone(); + assert!(validate(&summary).is_err()); + } +} diff --git a/tools/xtask/src/command.rs b/tools/xtask/src/command.rs new file mode 100644 index 00000000..14eb4322 --- /dev/null +++ b/tools/xtask/src/command.rs @@ -0,0 +1,14 @@ +use std::error::Error; +use std::path::Path; + +pub(crate) type DynResult = Result>; + +pub(crate) fn write_json_file(path: &Path, value: &T) -> DynResult<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut bytes = serde_json::to_vec_pretty(value)?; + bytes.push(b'\n'); + std::fs::write(path, bytes)?; + Ok(()) +} diff --git a/tools/xtask/src/execution.rs b/tools/xtask/src/execution.rs new file mode 100644 index 00000000..76e4da46 --- /dev/null +++ b/tools/xtask/src/execution.rs @@ -0,0 +1,142 @@ +//! Bounded commands for CI artifact production. Children never inherit publisher tokens. +use crate::command::DynResult; +use process_supervision::{ + Cancellation, Completion, Limits, ProcessSpec, RawCaptureOptions, Readiness, Value, +}; +use std::{ + ffi::OsString, + path::{Path, PathBuf}, + time::Duration, +}; + +pub fn executable(name: &str) -> DynResult { + let direct = Path::new(name); + if direct.components().count() > 1 && direct.is_file() { + return Ok(direct.canonicalize()?); + } + for directory in std::env::split_paths(&std::env::var_os("PATH").ok_or("PATH is unset")?) { + let candidate = directory.join(name); + if candidate.is_file() { + return Ok(candidate.canonicalize()?); + } + if cfg!(windows) { + let candidate = directory.join(format!("{name}.exe")); + if candidate.is_file() { + return Ok(candidate.canonicalize()?); + } + } + } + Err(format!("required tool is unavailable on PATH: {name}").into()) +} + +pub fn specification( + program: &str, + args: &[String], + env: &[(&str, String)], +) -> DynResult { + let mut environment = std::env::vars_os() + .filter(|(key, _)| { + let key = key.to_string_lossy(); + !key.contains("TOKEN") + && !key.contains("SECRET") + && !key.contains("PASSWORD") + && !matches!( + key.as_ref(), + "GITHUB_ENV" | "GITHUB_OUTPUT" | "GITHUB_PATH" | "GITHUB_STEP_SUMMARY" + ) + }) + .map(|(key, value)| (key, Value::Public(value))) + .collect::>(); + for (key, value) in env { + let value = if key.contains("TOKEN") || key.contains("SECRET") || key.contains("PASSWORD") { + Value::Secret(value.into()) + } else { + Value::Public(value.into()) + }; + environment.insert(OsString::from(key), value); + } + Ok(ProcessSpec { + executable: executable(program)?, + arguments: args + .iter() + .map(|value| Value::Public(value.into())) + .collect(), + cwd: std::env::current_dir()?.canonicalize()?, + environment, + }) +} + +pub fn limits(seconds: u64) -> Limits { + Limits { + execution: Duration::from_secs(seconds), + graceful_shutdown: Duration::from_secs(20), + forced_shutdown: Duration::from_secs(10), + retained_bytes_per_stream: 1024 * 1024, + readiness: Readiness::None, + completion: Completion::Exit, + } +} + +pub fn capture(program: &str, args: &[String], env: &[(&str, String)]) -> DynResult { + capture_for(program, args, env, 180) +} + +pub fn capture_for( + program: &str, + args: &[String], + env: &[(&str, String)], + seconds: u64, +) -> DynResult { + let report = process_supervision::supervise_raw( + &specification(program, args, env)?, + &limits(seconds), + &Cancellation::default(), + RawCaptureOptions { + stdout: std::num::NonZeroUsize::new(16 * 1024 * 1024), + stderr: None, + }, + )?; + if !report.process.success() { + return Err(format!( + "{program} failed: {:?}: {}", + report.process.outcome, + String::from_utf8_lossy(&report.process.stderr.bytes_retained) + ) + .into()); + } + Ok(String::from_utf8( + report + .stdout + .ok_or("missing captured stdout")? + .as_bytes() + .to_vec(), + )?) +} + +pub fn run(program: &str, args: &[String], env: &[(&str, String)], seconds: u64) -> DynResult<()> { + let report = process_supervision::supervise_inherited( + &specification(program, args, env)?, + &limits(seconds), + &Cancellation::default(), + )?; + if report.outcome == process_supervision::Outcome::Exited + && report.status.is_some_and(|status| status.success()) + && report.cleanup.complete + { + Ok(()) + } else { + Err(format!( + "{program} failed: {:?}, {:?}", + report.outcome, report.status + ) + .into()) + } +} + +pub fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +pub fn output(program: &str, arguments: &[String]) -> DynResult { + capture(program, arguments, &[]) +} diff --git a/tools/xtask/src/huggingface.rs b/tools/xtask/src/huggingface.rs new file mode 100644 index 00000000..eb86fc8b --- /dev/null +++ b/tools/xtask/src/huggingface.rs @@ -0,0 +1,66 @@ +use crate::{command::DynResult, execution}; +use std::path::{Path, PathBuf}; + +pub(crate) fn download( + repo: &str, + revision: &str, + files: &[&str], + timeout_seconds: u64, +) -> DynResult { + println!( + "Resolving Hugging Face fixtures {repo}@{revision}: {}", + files.join(", ") + ); + let mut args = execution::strings(&["download", repo, "--revision", revision, "--quiet"]); + args.extend(files.iter().map(|file| (*file).to_owned())); + let output = execution::capture_for( + "hf", + &args, + &[("HF_HUB_DISABLE_XET", "1".into())], + timeout_seconds, + )?; + downloaded_path(&output) +} + +fn downloaded_path(text: &str) -> DynResult { + for line in text.lines().rev() { + let line = line.trim(); + let candidate = line + .strip_prefix("path:") + .or_else(|| line.strip_prefix("path=")) + .map(str::trim) + .unwrap_or(line); + if Path::new(candidate).is_absolute() && !candidate.contains('\u{1b}') { + return Ok(PathBuf::from(candidate)); + } + } + Err("hf download returned no absolute artifact path".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn download_paths_support_legacy_and_formatted_cli_output() { + let file = if cfg!(windows) { + "C:/models/a.gguf" + } else { + "/models/a.gguf" + }; + assert_eq!(downloaded_path(file).unwrap(), PathBuf::from(file)); + assert_eq!( + downloaded_path(&format!( + "\u{1b}[32m✓ Downloaded\u{1b}[0m\n path: {file}\n" + )) + .unwrap(), + PathBuf::from(file) + ); + assert!(downloaded_path("Downloaded successfully").is_err()); + assert!(downloaded_path("path: relative.gguf").is_err()); + assert_eq!( + downloaded_path(&format!("path={file}\n")).unwrap(), + PathBuf::from(file) + ); + } +} diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs new file mode 100644 index 00000000..30d83d44 --- /dev/null +++ b/tools/xtask/src/main.rs @@ -0,0 +1,16 @@ +mod artifact; +mod cache_qualification; +mod command; +mod execution; +mod huggingface; + +fn main() -> std::process::ExitCode { + let args = std::env::args().skip(1).collect::>(); + match cache_qualification::run(&args) { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error}"); + std::process::ExitCode::FAILURE + } + } +}